text:
[![Build Status](https://travis-ci.org/scott4dev/KataNumbersInWords.svg?branch=master)](https://travis-ci.org/scott4dev/KataNumbersInWords)

A simple implementation of this [kata] (http://www.codingdojo.org/cgi-bin/index.pl?KataNumbersInWords)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Subscribo\Omnipay\Shared;

use Omnipay\Tests\GatewayTestCase;
use Subscribo\Omnipay\Shared\AbstractGateway;

class SharedAbstractGatewayTest extends GatewayTestCase
{
    protected $testedClassName = 'Subscribo\\Omnipay\\Shared\\AbstractGateway';

    public function setUp()
    {
        $this->gateway = new ExtendedAbstractGatewayForTesting($this->getHttpClient(), $this->getHttpRequest());
    }

    public function testAttachPsrLogger()
    {
        $logger = $this->getMock('Psr\\Log\\LoggerInterface');
        $this->assertTrue($this->gateway->attachPsrLogger($logger));
        $this->assertNull($this->gateway->attachPsrLogger($logger));
        $this->assertNull($this->gateway->attachPsrLogger($logger));
    }
}

class ExtendedAbstractGatewayForTesting extends AbstractGateway
{
    public function getName()
    {
        return 'Extended Gateway for testing';
    }
}


text:
author: "Adam Presley"
date: 2013-02-12T13:32:00Z
tags: ["python", "itertools"]
title: "Python itertools - Filtering items"
slug: "python-itertools-filtering-items"
---

Continuing my exploration of the **itertools** module in Python I wanted
to look at the **ifilter()** method. **ifilter()** is a method that
returns an iterator of items that return true from a test function (or
lambda expression). In this sample I have an array of products. I want
to get a list of products that have inventory in stock and are allowed
to be drop-shipped.

{{< highlight python >}}
import json
from itertools import ifilter

products = [
   {"id": "SHIRT-BLU15", "category": "T-Shirt", "color": "Blue", "size": "large", "instock": 125, "backorder": 50, "shipTypes": ["tostore", "dropship"], "price": 25.99},
   {"id": "SHIRT-BLU13", "category": "T-Shirt", "color": "Blue", "size": "small", "instock": 105, "backorder": 20, "shipTypes": ["tostore", "dropship"], "price": 23.99},
   {"id": "SHIRT-RED15", "category": "T-Shirt", "color": "Red", "size": "large", "instock": 145, "backorder": 20, "shipTypes": ["tostore"], "price": 26.99},
   {"id": "SHIRT-RED13", "category": "T-Shirt", "color": "Red", "size": "small", "instock": 25, "backorder": 75, "shipTypes": ["tostore"], "price": 20.99},
   {"id": "SHIRT-GRN15", "category": "T-Shirt", "color": "Green", "size": "large", "instock": 102, "backorder": 0, "shipTypes": ["tostore", "dropship"], "price": 21.99},
   {"id": "SHIRT-GRN13", "category": "T-Shirt", "color": "Green", "size": "small", "instock": 0, "backorder": 100, "shipTypes": ["tostore", "dropship"], "price": 21.99},
   {"id": "SHIRT-PUR15", "category": "T-Shirt", "color": "Purple", "size": "large", "instock": 25, "backorder": 60, "shipTypes": ["tostore"], "price": 27.99},
   {"id": "SHIRT-PUR13", "category": "T-Shirt", "color": "Purple", "size": "small", "instock": 0, "backorder": 100, "shipTypes": ["tostore"], "price": 26.99}
]

#
# Give me all shirts that are in stock and allow drop-ship
#
matches = [item for item in ifilter(lambda k: k["instock"] > 0 and "dropship" in k["shipTypes"], products)]

for i in matches:
   print "Item ID %s is in stock and available for drop-ship" % i["id"]
{{< / highlight >}}

Much like most Python list and array manipulation methods I'm using a list comprehension here. The cool part is the call to **ifilter()**. The first argument is a lambda expression that checks the current item to see if we have a value greater than zero for *instock*, and if
*dropship* is an item in the *shipTypes* array. The end result is an array of items that match, and I loop over that to show what's
available.

The more I use Python's list comprehensions and the **itertools** module the more I find I like it! Cheers, and happy coding!


text:
import React from 'react';
import { View, TextInput, Button, Text, StyleSheet } from 'react-native';
import { Signal, Video } from 'bit6';

import InCallManager from 'react-native-incall-manager';

export class CallingScreen extends React.Component {
  static navigationOptions = ({ navigation }) => ({
                                                  title: `Logged as ${navigation.state.params.accessToken.identity}/${navigation.state.params.accessToken.device}`,
                                                  });

  constructor(props,context) {
    super(props,context);

    this.signalSvc = new Signal(this.props.navigation.state.params.accessToken)

    this.onSession = this.onSession.bind(this)
    this.onParticipant = this.onParticipant.bind(this)
    this.handleVideoElemChange = this.handleVideoElemChange.bind(this)
    this.leaveSession = this.leaveSession.bind(this)

    this.signalSvc.on('message', function(msg) {
         console.log('Received direct signal', this);
    });

    // Init Video Service
    this.videoSvc = new Video(this.signalSvc);
    this.videoSvc.on('session', this.onSession);

    // Get notified about video elements for local video feed
    // v - video element to add or remove
    // op - operation. 1 - add, 0 - update, -1 - remove
    this.videoSvc.capture.on('video', function(v, op) {
      console.log('Local video elem', op, v);
      this.handleVideoElemChange(v, null, null, op);
    }.bind(this));

    this.state = {
      session : null,
      sessionId : '',
      remoteStream: null,
      localStream: null,
      participant: null,
      publishing: { audio: true, video: true },
      subscribedTo: { audio: true, video: true }
    }
  }

  render() {
    const { sessionId, session, remoteStream, localStream, participant, subscribedTo, publishing } = this.state
    if (session === null) {
    return (
            <View style={{padding: 10}}>
              <TextInput style={{height: 40}} placeholder='session-id' onChangeText={(sessionId) => this.setState({sessionId})} autoCapitalize='none' value={sessionId}/>
              <Button onPress={() => this.joinCall()} title='Join'/>
              <Button onPress={() => this.createCall()} title='Create'/>
            </View>
            )
    }
    else {
      return (
              <View style={{padding: 10}}>
                  <Text>Session Id: {sessionId}</Text>
                  <Button onPress={() => this.leaveSession()} title='LEAVE SESSION'/>

                  <View style={styles.publish}>
                  <Text>Me (Publishing)</Text>
                  <View style={styles.buttons}>
                    <Button onPress={() => this.updatePublish('audio', publishing['audio'])} title={`Audio (${publishing['audio']})`}/>
                    <Button onPress={() => this.updatePublish('video', publishing['video'])} title={`Video (${publishing['video']})`}/>
                  </View>
                  { localStream !== null ? <RTCView streamURL={localStream} style={styles.selfView}/> : <View></View> }
                  <Button onPress={() => this.switchCamera()} title='Switch Camera'/>
                  </View>

                  <View style={styles.subscribe}>
                  <Text>Participant (subscribed to)</Text>
                  { participant !== null ?
                      <View style={styles.buttons}>
                        <Button onPress={() => this.updateSubscribedTo(participant, 'audio', subscribedTo['audio'])} title={`Audio (${subscribedTo['audio']})`}/>
                        <Button onPress={() => this.updateSubscribedTo(participant, 'video', subscribedTo['video'])} title={`Video (${subscribedTo['video']})`}/>
                      </View>
                    : <View></View>
                  }
                  { remoteStream !== null ? <RTCView streamURL={remoteStream} style={styles.remoteView}/> : <View></View> }
                  </View>
              </View>
              )
    }
  }

  joinCall() {
    const { sessionId } = this.state;
    if ( sessionId !== '' ) {
      this.videoSvc.join(sessionId, function(err, s) {
        console.log('Session joined', err, s.id);
      });
    }
  }

  createCall() {
    this.videoSvc.create({mode: 'p2p'}, function(err, s) {
      console.log('Session created', err, s.id);
    });
  }

  switchCamera() {
    const localStream = this.videoSvc.capture.localStream
    if (localStream) {
        const videoTracks = localStream.getVideoTracks()
        if (videoTracks.length === 1) {
            videoTracks[0]._switchCamera()
        }
    }
  }

  onSession(s, op) {
    console.log('Video Session', op, s);
    if (op > 0) {
      this.setState({ sessionId: s.id, session: s })

      s.on('participant', this.onParticipant);

      // Get notified about new video elements for remote video feeds.
      // v - video element to add or remove
      // p - participant
      // op - operation. 1 - add, 0 - update, -1 - remove
      s.on('video', function(v, p, op) {
        this.handleVideoElemChange(v, s, p, op);
      }.bind(this));

      var media = { audio: true, video: true };
      s.me.publish(media);

      InCallManager.setKeepScreenOn(true)
      InCallManager.start({ media: 'video' });
    }
    else if (op < 0) {
      this.setState({ session: null, remoteStream: null, localStream: null, participant: null, publishing: { audio: true, video: true }, subscribedTo: { audio: true, video: true } })

      InCallManager.setKeepScreenOn(false)
      InCallManager.stop();
    }
  }

  leaveSession() {
    this.state.session.leave()
  }

  onParticipant(p, op) {
   console.log('Video Participant', op, p);
   if ( op > 0 ) {
     this.setState({participant:p})
     p.subscribe(this.state.subscribedTo);
   }
   else if ( op < 0 ) {
     this.setState({participant:null})
   }
  }

  updatePublish(kind, value) {
    var state = this.state.publishing
    state[kind] = !value
    var newMedia = {[kind]:state[kind]}
    this.state.session.me.publish(newMedia);
    this.setState({publishing:state})
  }

  updateSubscribedTo(p, kind, value) {
    var state = this.state.subscribedTo
    state[kind] = !value
    var newMedia = {[kind]:state[kind]}
    p.subscribe(newMedia);
    this.setState({subscribeTo:state})
  }

  // v.srcObject - stream to add or remove
  // s - Session that has this video or null if it is a local feed
  // p - Session Participant that has this video or null if it is a local feed
  // op - operation. 1 - add, 0 - update, -1 - remove
  handleVideoElemChange(v, s, p, op) {
    if ( op != 0 ) {
      if ( p ) {
        this.setState({ remoteStream: op > 0 ? v.srcObject.toURL() : null});
      }
      else {
        this.setState({ localStream: op > 0 ? v.srcObject.toURL() : null});
      }
    }
  }

}

const styles = StyleSheet.create({
                                 selfView: { width: 200, height: 150 },
                                 publish: { backgroundColor: 'rgba(164, 205, 255, 1.0)' },
                                 subscribe: { backgroundColor: 'rgba(255, 153, 102, 1.0)' },
                                 remoteView: { width: 200, height: 150, flexGrow: 1 },
                                 buttons: { flex: 0, flexDirection: 'row', height: 50 }
                                 });


text:
<!DOCTYPE html>

  <title>Free HTML5 Templates</title>
  <meta name="description" content="website description" />
  <meta name="keywords" content="website keywords, website keywords" />
  <meta http-equiv="content-type" content="text/html; charset=windows-1252" />
  <link rel="stylesheet" type="text/css" href="css/style.css" />

Welcome To Free HTML5 Water

Home

Our Work

Testimonials

Projects

Contact Us

New Website

Welcome to our new website. Please have a look around, any feedback is much appreciated.

Latest Update

March 2013

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque cursus tempor enim.

February 2013

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque cursus tempor enim.

Contact

Phone: +44 (0)1234 567891

Email: info@youremail.co.uk

Welcome To Your Website

This standards compliant, simple, fixed width website template is released as an 'open source' design (under the Creative Commons Attribution 3.0 Licence), which means that you are free to download and use it for anything you want (including modifying and amending it). If you wish to remove the “website template by Free HTML5 Templates”, all I ask is for a donation of £20.00 GBP. Please feel free to contact me with any questions you may have about my free HTML5 website templates or bespoke work.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi elit sapien, tempus sit amet hendrerit volutpat, euismod vitae risus. Etiam consequat, sem et vulputate dapibus, diam enim tristique est, vitae porta eros mauris ut orci. Praesent sed velit odio. Ut massa arcu, suscipit viverra molestie at, aliquet a metus. Nullam sit amet tellus dui, ut tincidunt justo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec iaculis egestas laoreet. Nunc non ipsum metus, non laoreet urna. Vestibulum quis risus quis diam mattis tempus. Vestibulum suscipit pretium tempor.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque cursus tempor enim. Aliquam facilisis neque non nunc posuere eget volutpat metus tincidunt.

		      Read more

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque cursus tempor enim. Aliquam facilisis neque non nunc posuere eget volutpat metus tincidunt.

		      Read more

	  Home | Our Work | Testimonials | Projects | Contact

	  Images |  Web Hosting  | website template by Free HTML5 Templates


text:
require 'test_helper'

class FullTurnTest < ActionDispatch::IntegrationTest

  test 'A full turn' do

    # Normally deactivated, because very long
    return

    @gb = create( :g_game_board_with_event_ready_to_move_investigators )
    @gb.update_attribute( :aasm_state, 'prof_move' )
    @avoidance_list = [ [ 17, 1 ], [ 14, 1 ], [ 10, 2 ], [ 11, 2 ], [ 4, 2 ], [ 9, 1 ] ]

    get '/'
    assert_response :success

    1.upto(18).each do |dices_result|
      # puts '*'*100
      # puts "Dice result : #{dices_result}"

      1.upto(2).each do |i|
        # puts "Turn : #{i}"
        prof = @gb.p_professor
        road = create( :inv_road )
        prof.current_location = road.src_city
        prof.save!
        prof_dest = prof.current_location.destinations.first

        # We call it because normally use should call it
        get map_show_url
        get move_g_game_board_professor_actions_url( g_game_board_id: @gb.id, zone_id: prof_dest.id, zone_class: prof_dest.class )
        assert_redirected_to map_show_url

        follow_redirect!
        assert_response :success

        get dont_breed_g_game_board_professor_actions_url( g_game_board_id: @gb.id )
        assert_redirected_to map_show_url

        follow_redirect!
        assert_response :success

        1.upto(4).each do

          inv = @gb.next_moving_investigator
          raise "No investigators : #{@gb.i_investigators.inspect}" unless inv

          GameCore::Events.stubs( :event_dices ).returns( dices_result )
          MapController.any_instance.stubs( :event_dices ).returns( dices_result )

          if inv&.inv_move?
            # puts "Investigator : #{inv.code_name}, Event table : #{inv.event_table}"
            road = create( :inv_road )
            inv.current_location = road.src_city
            inv.save!
            inv_dest = inv.current_location.destinations.first

            # We call it because normally use should call it
            get map_show_url
            get move_g_game_board_investigators_action_url( g_game_board_id: @gb.id, id: inv.id, zone_id: inv_dest.id, zone_class: inv_dest.class )
            assert_redirected_to map_show_url

            follow_redirect!
            assert_response :success
          end

        end
      end
    end
  end
end


text:
'use strict';

var Link = function (relation, href, attributes) {
  this.relation = relation;
  this.href = href;
  this.attributes = attributes;
};

module.exports = Link;


text:
using Agent.Sdk;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker.Build;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using BuildWebApi = Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.DistributedTask.Logging;
using Newtonsoft.Json.Linq;

namespace Microsoft.VisualStudio.Services.Agent.Worker
{
    public sealed class VariableScope : IDisposable
    {
        private Variables Data;
        private HashSet<string> Names;

        public VariableScope(Variables data)
        {
            Data = data;
            Names = new HashSet<string>();
        }

        public void Set(string name, string val, bool secret = false)
        {
            Names.Add(name);
            Data.Set(name, val, secret);
        }

        public void Dispose()
        {
            foreach (string name in Names)
            {
                Data.Unset(name);
            }
        }
    }

    public sealed class Variables
    {
        private readonly IHostContext _hostContext;
        private readonly ConcurrentDictionary<string, Variable> _nonexpanded = new ConcurrentDictionary<string, Variable>(StringComparer.OrdinalIgnoreCase);
        private readonly ISecretMasker _secretMasker;
        private readonly object _setLock = new object();
        private readonly Tracing _trace;
        private ConcurrentDictionary<string, Variable> _expanded;

        public delegate string TranslationMethod(string val);
        public TranslationMethod StringTranslator = DefaultStringTranslator;

        public static string DefaultStringTranslator(string val)
        {
            return val;
        }

        public IEnumerable<KeyValuePair<string, string>> Public
        {
            get
            {
                return _expanded.Values
                    .Where(x => !x.Secret)
                    .Select(x => new KeyValuePair<string, string>(x.Name, StringTranslator(x.Value)));
            }
        }

        public IEnumerable<KeyValuePair<string, string>> Private
        {
            get
            {
                return _expanded.Values
                    .Where(x => x.Secret)
                    .Select(x => new KeyValuePair<string, string>(x.Name, StringTranslator(x.Value)));
            }
        }

        public Variables(IHostContext hostContext, IDictionary<string, VariableValue> copy, out List<string> warnings)
        {
            ArgUtil.NotNull(hostContext, nameof(hostContext));

            // Store/Validate args.
            _hostContext = hostContext;
            _secretMasker = _hostContext.SecretMasker;
            _trace = _hostContext.GetTrace(nameof(Variables));

            // Validate the dictionary, remove any variable with empty variable name.
            ArgUtil.NotNull(copy, nameof(copy));
            if (copy.Keys.Any(k => string.IsNullOrWhiteSpace(k)))
            {
                _trace.Info($"Remove {copy.Keys.Count(k => string.IsNullOrWhiteSpace(k))} variables with empty variable name.");
            }

            // Initialize the variable dictionary.
            List<Variable> variables = new List<Variable>();
            foreach (var variable in copy)
            {
                if (!string.IsNullOrWhiteSpace(variable.Key))
                {
                    variables.Add(new Variable(variable.Key, variable.Value.Value, variable.Value.IsSecret, variable.Value.IsReadOnly));
                }
            }

            foreach (Variable variable in variables)
            {
                // Store the variable. The initial secret values have already been
                // registered by the Worker class.
                _nonexpanded[variable.Name] = variable;
            }

            // Recursively expand the variables.
            RecalculateExpanded(out warnings);
        }

        // DO NOT add file path variable to here.
        // All file path variables needs to be retrieved and set through ExecutionContext, so it can handle container file path translation.

        public TaskResult? Agent_JobStatus
        {
            get
            {
                return GetEnum<TaskResult>(Constants.Variables.Agent.JobStatus);
            }

            set
            {
                Set(Constants.Variables.Agent.JobStatus, $"{value}");
            }
        }

        public string Agent_ProxyUrl => Get(Constants.Variables.Agent.ProxyUrl);

        public string Agent_ProxyUsername => Get(Constants.Variables.Agent.ProxyUsername);

        public string Agent_ProxyPassword => Get(Constants.Variables.Agent.ProxyPassword);

        public int? Build_BuildId => GetInt(BuildWebApi.BuildVariables.BuildId);

        public string Build_BuildUri => Get(BuildWebApi.BuildVariables.BuildUri);

        public BuildCleanOption? Build_Clean => GetEnum<BuildCleanOption>(Constants.Variables.Features.BuildDirectoryClean) ?? GetEnum<BuildCleanOption>(Constants.Variables.Build.Clean);

        public long? Build_ContainerId => GetLong(BuildWebApi.BuildVariables.ContainerId);

        public string Build_DefinitionName => Get(Constants.Variables.Build.DefinitionName);

        public bool? Build_GatedRunCI => GetBoolean(Constants.Variables.Build.GatedRunCI);

        public string Build_GatedShelvesetName => Get(Constants.Variables.Build.GatedShelvesetName);

        public string Build_Number => Get(Constants.Variables.Build.Number);

        public string Build_RepoTfvcWorkspace => Get(Constants.Variables.Build.RepoTfvcWorkspace);

        public string Build_RequestedFor => Get((BuildWebApi.BuildVariables.RequestedFor));

        public string Build_SourceBranch => Get(Constants.Variables.Build.SourceBranch);

        public string Build_SourceTfvcShelveset => Get(Constants.Variables.Build.SourceTfvcShelveset);

        public string Build_SourceVersion => Get(Constants.Variables.Build.SourceVersion);

        public bool? Build_SyncSources => GetBoolean(Constants.Variables.Build.SyncSources);

        public bool? Build_UseServerWorkspaces => GetBoolean(Constants.Variables.Build.UseServerWorkspaces);

        public string Release_ArtifactsDirectory => Get(Constants.Variables.Release.ArtifactsDirectory);

        public string Release_ReleaseEnvironmentUri => Get(Constants.Variables.Release.ReleaseEnvironmentUri);

        public string Release_ReleaseId => Get(Constants.Variables.Release.ReleaseId);

        public string Release_ReleaseName => Get(Constants.Variables.Release.ReleaseName);

        public string Release_ReleaseUri => Get(Constants.Variables.Release.ReleaseUri);

        public int? Release_Download_BufferSize => GetInt(Constants.Variables.Release.ReleaseDownloadBufferSize);

        public int? Release_Parallel_Download_Limit => GetInt(Constants.Variables.Release.ReleaseParallelDownloadLimit);

        public bool Retain_Default_Encoding
        {
            get
            {
                if (!PlatformUtil.RunningOnWindows)
                {
                    return true;
                }
                return GetBoolean(Constants.Variables.Agent.RetainDefaultEncoding) ?? true;
            }
        }

        public bool Read_Only_Variables => GetBoolean(Constants.Variables.Agent.ReadOnlyVariables) ?? false;

        public string System_CollectionId => Get(Constants.Variables.System.CollectionId);

        public bool? System_Debug => GetBoolean(Constants.Variables.System.Debug);

        public string System_DefinitionId => Get(Constants.Variables.System.DefinitionId);

        public bool? System_EnableAccessToken => GetBoolean(Constants.Variables.System.EnableAccessToken);

        public HostTypes System_HostType => GetEnum<HostTypes>(Constants.Variables.System.HostType) ?? HostTypes.None;
        public string System_JobId => Get(Constants.Variables.System.JobId);

        public string System_PhaseDisplayName => Get(Constants.Variables.System.PhaseDisplayName);

        public string System_PullRequest_TargetBranch => Get(Constants.Variables.System.PullRequestTargetBranchName);

        public string System_TaskDefinitionsUri => Get(WellKnownDistributedTaskVariables.TaskDefinitionsUrl);

        public string System_TeamProject => Get(BuildWebApi.BuildVariables.TeamProject);

        public Guid? System_TeamProjectId => GetGuid(BuildWebApi.BuildVariables.TeamProjectId);

        public string System_TFCollectionUrl => Get(WellKnownDistributedTaskVariables.TFCollectionUrl);

        public string System_StageName => Get(Constants.Variables.System.StageName);

        public int? System_StageAttempt => GetInt(Constants.Variables.System.StageAttempt);

        public string System_PhaseName => Get(Constants.Variables.System.PhaseName);

        public int? System_PhaseAttempt => GetInt(Constants.Variables.System.PhaseAttempt);

        public string System_JobName => Get(Constants.Variables.System.JobName);

        public int? System_JobAttempt => GetInt(Constants.Variables.System.JobAttempt);

        public static readonly HashSet<string> PiiVariables = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
        {
            "Build.AuthorizeAs",
            "Build.QueuedBy",
            "Build.RequestedFor",
            "Build.RequestedForEmail",
            "Build.SourceBranch",
            "Build.SourceBranchName",
            "Build.SourceTfvcShelveset",
            "Build.SourceVersion",
            "Build.SourceVersionAuthor",
            "Job.AuthorizeAs",
            "Release.Deployment.RequestedFor",
            "Release.Deployment.RequestedForEmail",
            "Release.RequestedFor",
            "Release.RequestedForEmail",
        };

        public static readonly string PiiArtifactVariablePrefix = "Release.Artifacts";

        public static readonly List<string> PiiArtifactVariableSuffixes = new List<string>()
        {
            "SourceBranch",
            "SourceBranchName",
            "SourceVersion",
            "RequestedFor"
        };

        public void ExpandValues(IDictionary<string, string> target)
        {
            ArgUtil.NotNull(target, nameof(target));
            _trace.Entering();
            var source = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (Variable variable in _expanded.Values)
            {
                var value = StringTranslator(variable.Value);
                source[variable.Name] = value;
            }

            VarUtil.ExpandValues(_hostContext, source, target);
        }

        public string ExpandValue(string name, string value)
        {
            _trace.Entering();
            var source = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (Variable variable in _expanded.Values)
            {
                source[variable.Name] = StringTranslator(variable.Value);
            }
            var target = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                [name] = value
            };
            VarUtil.ExpandValues(_hostContext, source, target);
            return target[name];
        }

        public JToken ExpandValues(JToken target)
        {
            _trace.Entering();
            var source = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (Variable variable in _expanded.Values)
            {
                source[variable.Name] = StringTranslator(variable.Value);
            }

            return VarUtil.ExpandValues(_hostContext, source, target);
        }

        public string Get(string name)
        {
            Variable variable;
            if (_expanded.TryGetValue(name, out variable))
            {
                var value = StringTranslator(variable.Value);
                _trace.Verbose($"Get '{name}': '{value}'");
                return value;
            }

            _trace.Verbose($"Get '{name}' (not found)");
            return null;
        }

        public bool? GetBoolean(string name)
        {
            bool val;
            if (bool.TryParse(Get(name), out val))
            {
                return val;
            }

            return null;
        }

        public T? GetEnum<T>(string name) where T : struct
        {
            return EnumUtil.TryParse<T>(Get(name));
        }

        public Guid? GetGuid(string name)
        {
            Guid val;
            if (Guid.TryParse(Get(name), out val))
            {
                return val;
            }

            return null;
        }

        public int? GetInt(string name)
        {
            int val;
            if (int.TryParse(Get(name), out val))
            {
                return val;
            }

            return null;
        }

        public long? GetLong(string name)
        {
            long val;
            if (long.TryParse(Get(name), out val))
            {
                return val;
            }

            return null;
        }

        public VariableScope CreateScope()
        {
            return new VariableScope(this);
        }

        public void Unset(string name)
        {
            // Validate the args.
            ArgUtil.NotNullOrEmpty(name, nameof(name));

            // Remove the variable.
            lock (_setLock)
            {
                Variable dummy;
                 _expanded.Remove(name, out dummy);
                _nonexpanded.Remove(name, out dummy);
                _trace.Verbose($"Unset '{name}'");
            }
        }

        public void Set(string name, string val, bool secret = false, bool readOnly = false)
        {
            // Validate the args.
            ArgUtil.NotNullOrEmpty(name, nameof(name));

            // Add or update the variable.
            lock (_setLock)
            {
                // Determine whether the value should be a secret. The approach taken here is somewhat
                // conservative. If the previous expanded variable is a secret, then assume the new
                // value should be a secret as well.
                //
                // Keep in mind, the two goals of flagging variables as secret:
                // 1) Mask secrets from the logs.
                // 2) Keep secrets out of environment variables for tasks. Secrets must be passed into
                //    tasks via inputs. It's better to take a conservative approach when determining
                //    whether a variable should be marked secret. Otherwise nested secret values may
                //    inadvertantly end up in public environment variables.
                secret = secret || (_expanded.ContainsKey(name) && _expanded[name].Secret);

                // Register the secret. Secret masker handles duplicates gracefully.
                if (secret && !string.IsNullOrEmpty(val))
                {
                    _secretMasker.AddValue(val);
                }

                // Also keep any variables that are already read only as read only.
                // This only really matters for server side system variables that get updated by something other than setVariable (e.g. updateBuildNumber).
                readOnly = readOnly || (_expanded.ContainsKey(name) && _expanded[name].ReadOnly);

                // Store the value as-is to the expanded dictionary and the non-expanded dictionary.
                // It is not expected that the caller needs to store an non-expanded value and then
                // retrieve the expanded value in the same context.
                var variable = new Variable(name, val, secret, readOnly);
                _expanded[name] = variable;
                _nonexpanded[name] = variable;
                _trace.Verbose($"Set '{name}' = '{val}'");
            }
        }

        public bool IsReadOnly(string name)
        {
            Variable existingVariable = null;
            if (!_expanded.TryGetValue(name, out existingVariable)) {
                _nonexpanded.TryGetValue(name, out existingVariable);
            }

            return (existingVariable != null && IsReadOnly(existingVariable));
        }

        public bool TryGetValue(string name, out string val)
        {
            Variable variable;
            if (_expanded.TryGetValue(name, out variable))
            {
                val = StringTranslator(variable.Value);
                _trace.Verbose($"Get '{name}': '{val}'");
                return true;
            }

            val = null;
            _trace.Verbose($"Get '{name}' (not found)");
            return false;
        }

        public void RecalculateExpanded(out List<string> warnings)
        {
            // TODO: A performance improvement could be made by short-circuiting if the non-expanded values are not dirty. It's unclear whether it would make a significant difference.

            // Take a lock to prevent the variables from changing while expansion is being processed.
            lock (_setLock)
            {
                const int MaxDepth = 50;
                // TODO: Validate max size? No limit on *nix. Max of 32k per env var on Windows https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653%28v=vs.85%29.aspx
                _trace.Entering();
                warnings = new List<string>();

                // Create a new expanded instance.
                var expanded = new ConcurrentDictionary<string, Variable>(_nonexpanded, StringComparer.OrdinalIgnoreCase);

                // Process each variable in the dictionary.
                foreach (string name in _nonexpanded.Keys)
                {
                    bool secret = _nonexpanded[name].Secret;
                    bool readOnly = _nonexpanded[name].ReadOnly;
                    _trace.Verbose($"Processing expansion for variable: '{name}'");

                    // This algorithm handles recursive replacement using a stack.
                    // 1) Max depth is enforced by leveraging the stack count.
                    // 2) Cyclical references are detected by walking the stack.
                    // 3) Additional call frames are avoided.
                    bool exceedsMaxDepth = false;
                    bool hasCycle = false;
                    var stack = new Stack<RecursionState>();
                    RecursionState state = new RecursionState(name: name, value: _nonexpanded[name].Value ?? string.Empty);

                    // The outer while loop is used to manage popping items from the stack (of state objects).
                    while (true)
                    {
                        // The inner while loop is used to manage replacement within the current state object.

                        // Find the next macro within the current value.
                        while (state.StartIndex < state.Value.Length &&
                            (state.PrefixIndex = state.Value.IndexOf(Constants.Variables.MacroPrefix, state.StartIndex, StringComparison.Ordinal)) >= 0 &&
                            (state.SuffixIndex = state.Value.IndexOf(Constants.Variables.MacroSuffix, state.PrefixIndex + Constants.Variables.MacroPrefix.Length, StringComparison.Ordinal)) >= 0)
                        {
                            // A candidate was found.
                            string nestedName = state.Value.Substring(
                                startIndex: state.PrefixIndex + Constants.Variables.MacroPrefix.Length,
                                length: state.SuffixIndex - state.PrefixIndex - Constants.Variables.MacroPrefix.Length);
                            if (!secret)
                            {
                                _trace.Verbose($"Found macro candidate: '{nestedName}'");
                            }

                            Variable nestedVariable;
                            if (!string.IsNullOrEmpty(nestedName) &&
                                _nonexpanded.TryGetValue(nestedName, out nestedVariable))
                            {
                                // A matching variable was found.

                                // Check for max depth.
                                int currentDepth = stack.Count + 1; // Add 1 since the current state isn't on the stack.
                                if (currentDepth == MaxDepth)
                                {
                                    // Warn and break out of the while loops.
                                    _trace.Warning("Exceeds max depth.");
                                    exceedsMaxDepth = true;
                                    warnings.Add(StringUtil.Loc("Variable0ExceedsMaxDepth1", name, MaxDepth));
                                    break;
                                }
                                // Check for a cyclical reference.
                                else if (string.Equals(state.Name, nestedName, StringComparison.OrdinalIgnoreCase) ||
                                    stack.Any(x => string.Equals(x.Name, nestedName, StringComparison.OrdinalIgnoreCase)))
                                {
                                    // Warn and break out of the while loops.
                                    _trace.Warning("Cyclical reference detected.");
                                    hasCycle = true;
                                    warnings.Add(StringUtil.Loc("Variable0ContainsCyclicalReference", name));
                                    break;
                                }
                                else
                                {
                                    // Push the current state and start a new state. There is no need to break out
                                    // of the inner while loop. It will continue processing the new current state.
                                    secret = secret || nestedVariable.Secret;
                                    if (!secret)
                                    {
                                        _trace.Verbose($"Processing expansion for nested variable: '{nestedName}'");
                                    }

                                    stack.Push(state);
                                    state = new RecursionState(name: nestedName, value: StringTranslator(nestedVariable.Value ?? string.Empty));
                                }
                            }
                            else
                            {
                                // A matching variable was not found.
                                if (!secret)
                                {
                                    _trace.Verbose("Macro not found.");
                                }

                                state.StartIndex = state.PrefixIndex + 1;
                            }
                        } // End of inner while loop for processing the variable.

                        // No replacement is performed if something went wrong.
                        if (exceedsMaxDepth || hasCycle)
                        {
                            break;
                        }

                        // Check if finished processing the stack.
                        if (stack.Count == 0)
                        {
                            // Store the final value and break out of the outer while loop.
                            if (!string.Equals(state.Value, _nonexpanded[name].Value, StringComparison.Ordinal))
                            {
                                // Register the secret.
                                if (secret && !string.IsNullOrEmpty(state.Value))
                                {
                                    _secretMasker.AddValue(state.Value);
                                }

                                // Set the expanded value.
                                expanded[state.Name] = new Variable(state.Name, state.Value, secret, readOnly);
                                _trace.Verbose($"Set '{state.Name}' = '{state.Value}'");
                            }

                            break;
                        }

                        // Adjust and pop the parent state.
                        if (!secret)
                        {
                            _trace.Verbose("Popping recursion state.");
                        }

                        RecursionState parent = stack.Pop();
                        parent.Value = string.Concat(
                            parent.Value.Substring(0, parent.PrefixIndex),
                            state.Value,
                            parent.Value.Substring(parent.SuffixIndex + Constants.Variables.MacroSuffix.Length));
                        parent.StartIndex = parent.PrefixIndex + (state.Value).Length;
                        state = parent;
                        if (!secret)
                        {
                            _trace.Verbose($"Intermediate state '{state.Name}': '{state.Value}'");
                        }
                    } // End of outer while loop for recursively processing the variable.
                } // End of foreach loop over each key in the dictionary.

                _expanded = expanded;
            } // End of critical section.

        }

        public void CopyInto(Dictionary<string, VariableValue> target, TranslationMethod translation)
        {
            ArgUtil.NotNull(target, nameof(target));
            ArgUtil.NotNull(translation, nameof(translation));

            foreach (var var in this.Public)
            {
                target[var.Key] = translation(var.Value);
            }
            foreach (var var in this.Private)
            {
                target[var.Key] = new VariableValue(translation(var.Value), true);
            }
        }

        private Boolean IsReadOnly(Variable variable)
        {
            if (variable.ReadOnly)
            {
                return true;
            }

            return Constants.Variables.ReadOnlyVariables.Contains(variable.Name, StringComparer.OrdinalIgnoreCase);
        }

        private sealed class RecursionState
        {
            public RecursionState(string name, string value)
            {
                Name = name;
                Value = value;
            }

            public string Name { get; private set; }
            public string Value { get; set; }
            public int StartIndex { get; set; }
            public int PrefixIndex { get; set; }
            public int SuffixIndex { get; set; }
        }
    }

    public sealed class Variable
    {
        public string Name { get; private set; }
        public bool Secret { get; private set; }
        public string Value { get; private set; }
        public bool ReadOnly { get; private set; }

        public Variable(string name, string value, bool secret, bool readOnly)
        {
            ArgUtil.NotNullOrEmpty(name, nameof(name));
            Name = name;
            Value = value ?? string.Empty;
            Secret = secret;
            ReadOnly = readOnly;
        }
    }
}


text:
<?php

namespace Opl\Template\Exception;
use LogicException;

class CompilationException extends LogicException
{

} // end CompilationException;


text:
from setuptools import find_packages
from setuptools import setup

package_name = 'ament_pclint'

setup(
    name=package_name,
    version='0.13.2',
    packages=find_packages(exclude=['test']),
    data_files=[
        ('share/' + package_name, ['package.xml']),
        ('share/ament_index/resource_index/packages',
            ['resource/' + package_name]),
    ],
    install_requires=['setuptools'],
    package_data={'': [
        'config/gcc/co-g++.h',
        'config/gcc/co-g++.lnt',
        'config/gcc/co-gcc.h',
        'config/gcc/co-gcc.lnt',
        'config/gcc/co-osx-g++.h',
        'config/gcc/co-osx-g++.lnt',
        'config/gcc/co-osx-gcc.h',
        'config/gcc/co-osx-gcc.lnt',
        'config/msvc/cl-include-path.lnt',
        'config/msvc/co-cl.lnt',
        'config/msvc/co-cl++.lnt',
        'config/msvc/co-cl.h',
        'config/au-misra3.lnt',
        'config/au-misra3-amd1.lnt',
        'config/au-misra-cpp.lnt',
        'config/c99.lnt',
        'config/c++.lnt',
        'config/deprecate.lnt',
        'config/env-xml.lnt'
    ]},
    zip_safe=False,
    author='Juan Pablo Samper',
    author_email='jp.samper@apex.ai',
    maintainer='Michael Jeronimo',
    maintainer_email='michael.jeronimo@openrobotics.org',
    url='https://github.com/ament/ament_lint',
    download_url='',
    keywords=['ament'],
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apex AI',
        'Programming Language :: Python',
        'Topic :: Software Development',
    ],
    description='Static code analysis on C/C++ code using PC-lint.',
    long_description="""\
The ability to perform static code analysis on C/C++ code using PC-lint
and generate xUnit test result files.""",
    license='Apache License, Version 2.0',
    tests_require=['pytest'],
    test_suite='test',
    entry_points={
        'console_scripts': [
            'ament_pclint = ament_pclint.main:main',
        ],
    },
)


text: package apipb


text:
<?php

namespace Tests\Unit\Policies;

use Coyote\Topic;
use Illuminate\Support\Facades\Gate;
use Tests\TestCase;

class TopicPolicyTest extends ForumPolicyTest
{
    /**
     * @var Topic
     */
    private $topic;

    public function setUp(): void
    {
        parent::setUp();

        $this->topic = factory(Topic::class)->make();
    }

    public function testWriteInLockedTopicIsNotAllowed()
    {
        $this->topic->is_locked = true;

        $this->assertFalse(Gate::allows('write', $this->topic));
        $this->assertFalse($this->user->can('write', $this->topic));
    }

    public function testWriteInLockedTopicAsAdminIsAllowed()
    {
        $this->topic->is_locked = true;

        Gate::define('forum-update', function () {
            return true;
        });

        $this->assertTrue($this->user->can('write', $this->topic));
    }
}


text:
import {
  Baggage,
  BaggageEntry,
  defaultTextMapGetter,
  defaultTextMapSetter,
  propagation,
  baggageEntryMetadataFromString
} from '@opentelemetry/api';
import { ROOT_CONTEXT } from '@opentelemetry/api';
import * as assert from 'assert';
import { W3CBaggagePropagator } from '../../src/baggage/propagation/W3CBaggagePropagator';
import { BAGGAGE_HEADER } from '../../src/baggage/constants';

describe('W3CBaggagePropagator', () => {
  const httpBaggagePropagator = new W3CBaggagePropagator();

  let carrier: { [key: string]: unknown };

  beforeEach(() => {
    carrier = {};
  });

  describe('.inject()', () => {
    it('should set baggage header', () => {
      const baggage = propagation.createBaggage({
        key1: { value: 'd4cda95b652f4a1592b449d5929fda1b' },
        'with/slash': { value: 'with spaces' },
        key3: { value: 'c88815a7-0fa9-4d95-a1f1-cdccce3c5c2a' },
        key4: { value: 'foo', metadata: baggageEntryMetadataFromString('key4prop1=value1;key4prop2=value2;key4prop3WithNoValue') }
      });

      httpBaggagePropagator.inject(
        propagation.setBaggage(ROOT_CONTEXT, baggage),
        carrier,
        defaultTextMapSetter
      );
      assert.deepStrictEqual(
        carrier[BAGGAGE_HEADER],
        'key1=d4cda95b652f4a1592b449d5929fda1b,with%2Fslash=with%20spaces,key3=c88815a7-0fa9-4d95-a1f1-cdccce3c5c2a,key4=foo;key4prop1=value1;key4prop2=value2;key4prop3WithNoValue'
      );
    });

    it('should skip long key-value pairs', () => {
      const baggage = propagation.createBaggage({
        key1: { value: 'd4cda95b' },
        key3: { value: 'c88815a7' },
      });

      httpBaggagePropagator.inject(
        propagation.setBaggage(ROOT_CONTEXT, baggage),
        carrier,
        defaultTextMapSetter
      );
      assert.deepStrictEqual(
        carrier[BAGGAGE_HEADER],
        'key1=d4cda95b,key3=c88815a7'
      );
    });

    it('should skip all entries whose length exceeds the W3C standard limit of 4096 bytes', () => {
      const longKey = Array(96).fill('k').join('');
      const shortKey = Array(95).fill('k').join('');
      const value = Array(4000).fill('v').join('');

      let baggage = propagation.createBaggage({
        aa: { value: 'shortvalue' },
        [shortKey]: { value: value },
      });

      httpBaggagePropagator.inject(
        propagation.setBaggage(ROOT_CONTEXT, baggage),
        carrier,
        defaultTextMapSetter
      );

      let header = carrier[BAGGAGE_HEADER];
      assert.ok(typeof header === 'string');
      assert.deepStrictEqual(header, `aa=shortvalue,${shortKey}=${value}`);

      baggage = propagation.createBaggage({
        aa: { value: 'shortvalue' },
        [longKey]: { value: value },
      });

      carrier = {};
      httpBaggagePropagator.inject(
        propagation.setBaggage(ROOT_CONTEXT, baggage),
        carrier,
        defaultTextMapSetter
      );

      header = carrier[BAGGAGE_HEADER];
      assert.ok(typeof header === 'string');
      assert.deepStrictEqual(header, 'aa=shortvalue');
    });

    it('should not exceed the W3C standard header length limit of 8192 bytes', () => {
      const longKey0 = Array(48).fill('0').join('');
      const longKey1 = Array(49).fill('1').join('');
      const longValue = Array(4000).fill('v').join('');

      let baggage = propagation.createBaggage({
        [longKey0]: { value: longValue },
        [longKey1]: { value: longValue },
        aa: { value: Array(88).fill('v').join('') },
      });

      httpBaggagePropagator.inject(
        propagation.setBaggage(ROOT_CONTEXT, baggage),
        carrier,
        defaultTextMapSetter
      );

      let header = carrier[BAGGAGE_HEADER];
      assert.ok(typeof header === 'string');
      assert.deepStrictEqual(header.length, 8192);
      assert.deepStrictEqual(header.split(',').length, 3);

      baggage = propagation.createBaggage({
        [longKey0]: { value: longValue },
        [longKey1]: { value: longValue },
        aa: { value: Array(89).fill('v').join('') },
      });

      carrier = {};
      httpBaggagePropagator.inject(
        propagation.setBaggage(ROOT_CONTEXT, baggage),
        carrier,
        defaultTextMapSetter
      );

      header = carrier[BAGGAGE_HEADER];
      assert.ok(typeof header === 'string');
      assert.deepStrictEqual(header.length, 8100);
      assert.deepStrictEqual(header.split(',').length, 2);
    });

    it('should not exceed the W3C standard header entry limit of 180 entries', () => {
      const entries: Record<string, BaggageEntry> = {};

      Array(200)
        .fill(0)
        .forEach((_, i) => {
          entries[`${i}`] = { value: 'v' };
        });

      const baggage = propagation.createBaggage(entries);

      httpBaggagePropagator.inject(
        propagation.setBaggage(ROOT_CONTEXT, baggage),
        carrier,
        defaultTextMapSetter
      );

      const header = carrier[BAGGAGE_HEADER];
      assert.ok(typeof header === 'string');
      assert.strictEqual(header.split(',').length, 180);
    });
  });

  describe('.extract()', () => {
    const baggageValue = 'key1=d4cda95b,key3=c88815a7, keyn   = valn, keym =valm';
    const expected = propagation.createBaggage({
      key1: { value: 'd4cda95b' },
      key3: { value: 'c88815a7' },
      keyn: { value: 'valn' },
      keym: { value: 'valm' },
    });

    it('should extract context of a sampled span from carrier', () => {
      carrier[BAGGAGE_HEADER] = baggageValue;
      const extractedBaggage = propagation.getBaggage(
        httpBaggagePropagator.extract(
          ROOT_CONTEXT,
          carrier,
          defaultTextMapGetter
        )
      );

      assert.deepStrictEqual(extractedBaggage, expected);
    });

    it('should extract context of a sampled span when the headerValue comes as array', () => {
      carrier[BAGGAGE_HEADER] = [baggageValue];
      const extractedBaggage = propagation.getBaggage(
        httpBaggagePropagator.extract(
          ROOT_CONTEXT,
          carrier,
          defaultTextMapGetter
        )
      );

      assert.deepStrictEqual(extractedBaggage, expected);
    });

    it('should extract context of a sampled span when the headerValue comes as array with multiple items', () => {
      carrier[BAGGAGE_HEADER] = ['key1=d4cda95b,key3=c88815a7, keyn   = valn', 'keym =valm'];
      const extractedBaggage = propagation.getBaggage(
        httpBaggagePropagator.extract(
          ROOT_CONTEXT,
          carrier,
          defaultTextMapGetter
        )
      );

      assert.deepStrictEqual(extractedBaggage, expected);
    });
  });

  describe('fields()', () => {
    it('returns the fields used by the baggage spec', () => {
      const propagator = new W3CBaggagePropagator();
      assert.deepStrictEqual(propagator.fields(), [BAGGAGE_HEADER]);
    });
  });

  it('returns undefined if header is missing', () => {
    assert.deepStrictEqual(
      propagation.getBaggage(
        httpBaggagePropagator.extract(
          ROOT_CONTEXT,
          carrier,
          defaultTextMapGetter
        )
      ),
      undefined
    );
  });

  it('returns keys with their properties', () => {
    carrier[BAGGAGE_HEADER] = 'key1=d4cda95b,key3=c88815a7;prop1=value1';
    const bag = propagation.getBaggage(
      httpBaggagePropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter)
    );

    assert.ok(bag);
    const entries = bag.getAllEntries();

    assert.strictEqual(entries.length, 2);
    assert.deepStrictEqual(bag.getEntry('key1')!.value, 'd4cda95b');
    assert.deepStrictEqual(bag.getEntry('key3')!.value, 'c88815a7');
    assert.deepStrictEqual(
      bag.getEntry('key3')!.metadata?.toString(),
      'prop1=value1'
    );
  });

  it('should gracefully handle an invalid header', () => {
    const testCases: Record<
      string,
      {
        header: string;
        baggage: Baggage | undefined;
      }
    > = {
      invalidNoKeyValuePair: {
        header: '289371298nekjh2939299283jbk2b',
        baggage: undefined,
      },
      invalidDoubleEqual: {
        header: 'key1==value;key2=value2',
        baggage: undefined,
      },
      invalidWrongKeyValueFormat: {
        header: 'key1:value;key2=value2',
        baggage: undefined,
      },
      invalidDoubleSemicolon: {
        header: 'key1:value;;key2=value2',
        baggage: undefined,
      },
      mixInvalidAndValidKeys: {
        header: 'key1==value,key2=value2',
        baggage: propagation.createBaggage({
          key2: {
            value: 'value2',
          },
        }),
      },
    };
    Object.getOwnPropertyNames(testCases).forEach(testCase => {
      carrier[BAGGAGE_HEADER] = testCases[testCase].header;

      const extractedSpanContext = propagation.getBaggage(
        httpBaggagePropagator.extract(
          ROOT_CONTEXT,
          carrier,
          defaultTextMapGetter
        )
      );
      assert.deepStrictEqual(
        extractedSpanContext,
        testCases[testCase].baggage,
        testCase
      );
    });
  });
});


text:
package prometheusexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/prometheusexporter"

import (
	"context"
	"errors"
	"net/http"
	"strings"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/pdata/pmetric"
)

type prometheusExporter struct {
	config       Config
	name         string
	endpoint     string
	shutdownFunc func() error
	handler      http.Handler
	collector    *collector
	registry     *prometheus.Registry
	settings     component.TelemetrySettings
}

var errBlankPrometheusAddress = errors.New("expecting a non-blank address to run the Prometheus metrics handler")

func newPrometheusExporter(config *Config, set component.ExporterCreateSettings) (*prometheusExporter, error) {
	addr := strings.TrimSpace(config.Endpoint)
	if strings.TrimSpace(config.Endpoint) == "" {
		return nil, errBlankPrometheusAddress
	}

	collector := newCollector(config, set.Logger)
	registry := prometheus.NewRegistry()
	_ = registry.Register(collector)
	return &prometheusExporter{
		config:       *config,
		name:         config.ID().String(),
		endpoint:     addr,
		collector:    collector,
		registry:     registry,
		shutdownFunc: func() error { return nil },
		handler: promhttp.HandlerFor(
			registry,
			promhttp.HandlerOpts{
				ErrorHandling:     promhttp.ContinueOnError,
				ErrorLog:          newPromLogger(set.Logger),
				EnableOpenMetrics: config.EnableOpenMetrics,
			},
		),
		settings: set.TelemetrySettings,
	}, nil
}

func (pe *prometheusExporter) Start(_ context.Context, host component.Host) error {
	ln, err := pe.config.ToListener()
	if err != nil {
		return err
	}

	pe.shutdownFunc = ln.Close

	mux := http.NewServeMux()
	mux.Handle("/metrics", pe.handler)
	srv, err := pe.config.ToServer(host, pe.settings, mux)
	if err != nil {
		return err
	}
	go func() {
		_ = srv.Serve(ln)
	}()

	return nil
}

func (pe *prometheusExporter) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {
	n := 0
	rmetrics := md.ResourceMetrics()
	for i := 0; i < rmetrics.Len(); i++ {
		n += pe.collector.processMetrics(rmetrics.At(i))
	}

	return nil
}

func (pe *prometheusExporter) Shutdown(context.Context) error {
	return pe.shutdownFunc()
}


text:
<?php
/*
 * @author Andreas Åkre Solberg <andreas.solberg@uninett.no>
 * @package SimpleSAMLphp
 */
class sspmod_statistics_Statistics_Rulesets_BaseRule {

	protected $statconfig;
	protected $ruleconfig;
	protected $ruleid;
	protected $available;

	/**
	 * Constructor
	 */
	public function __construct($statconfig, $ruleconfig, $ruleid, $available) {
		assert('$statconfig instanceof SimpleSAML_Configuration');
		assert('$ruleconfig instanceof SimpleSAML_Configuration');
		$this->statconfig = $statconfig;
		$this->ruleconfig = $ruleconfig;
		$this->ruleid = $ruleid;

		$this->available = NULL;
		if (array_key_exists($ruleid, $available)) $this->available = $available[$ruleid];
	}

	public function getRuleID() {
		return $this->ruleid;
	}

	public function init() {

	}

	public function availableTimeRes() {
		$timeresConfigs = $this->statconfig->getValue('timeres');
		$available_times = array();
		foreach ($timeresConfigs AS $tres => $tresconfig) {
			if (array_key_exists($tres, $this->available))
				$available_times[$tres] = $tresconfig['name'];
		}
		return $available_times;
	}

	public function availableFileSlots($timeres) {
		$timeresConfigs = $this->statconfig->getValue('timeres');
		$timeresConfig = $timeresConfigs[$timeres];

		if (isset($timeresConfig['customDateHandler']) && $timeresConfig['customDateHandler'] == 'month') {
			$datehandler = new sspmod_statistics_DateHandlerMonth(0);
		} else {
			$datehandler = new sspmod_statistics_DateHandler($this->statconfig->getValue('offset', 0));
		}

		/*
		 * Get list of avaiable times in current file (rule)
		 */
		$available_times = array();
		foreach ($this->available[$timeres] AS $slot) {
			$available_times[$slot] = $datehandler->prettyHeader($slot, $slot+1, $timeresConfig['fileslot'], $timeresConfig['dateformat-period']);
		}
		return $available_times;
	}

	protected function resolveTimeRes($preferTimeRes) {
		$timeresavailable = array_keys($this->available);
		$timeres = $timeresavailable[0];

		// Then check if the user have provided one that is valid
		if (in_array($preferTimeRes, $timeresavailable)) {
			$timeres = $preferTimeRes;
		}
		return $timeres;
	}

	protected function resolveFileSlot($timeres, $preferTime) {

		// Get which time (fileslot) to use.. First get a default, which is the most recent one.
		$fileslot = $this->available[$timeres][count($this->available[$timeres])-1];
		// Then check if the user have provided one.
		if (in_array($preferTime, $this->available[$timeres])) {
			$fileslot = $preferTime;
		}
		return $fileslot;
	}

	public function getTimeNavigation($timeres, $preferTime) {
		$fileslot = $this->resolveFileSlot($timeres, $preferTime);

		// Extract previous and next time slots...
		$available_times_prev = NULL; $available_times_next = NULL;

		$timeslots = array_values($this->available[$timeres]);
		sort($timeslots, SORT_NUMERIC);
		$timeslotindex = array_flip($timeslots);

		if ($timeslotindex[$fileslot] > 0)
			$available_times_prev = $timeslots[$timeslotindex[$fileslot]-1];
		if ($timeslotindex[$fileslot] < (count($timeslotindex)-1) )
			$available_times_next = $timeslots[$timeslotindex[$fileslot]+1];
		return array('prev' => $available_times_prev, 'next' => $available_times_next);
	}

	public function getDataSet($preferTimeRes, $preferTime) {
		$timeres = $this->resolveTimeRes($preferTimeRes);
		$fileslot = $this->resolveFileSlot($timeres, $preferTime);
		$dataset = new sspmod_statistics_StatDataset($this->statconfig, $this->ruleconfig, $this->ruleid, $timeres, $fileslot);
		return $dataset;
	}

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;
using System;

#nullable enable

namespace Azure.MixedReality.Authentication
{
    internal static class AuthenticationEndpoint
    {
        /// <summary>
        /// Constructs an authentication endpoint from a service domain.
        /// </summary>
        /// <param name="accountDomain">The account domain.</param>
        /// <returns><see cref="Uri"/>.</returns>
        public static Uri ConstructFromDomain(string accountDomain)
        {
            Argument.AssertNotNullOrWhiteSpace(accountDomain, nameof(accountDomain));

            if (!Uri.TryCreate($"https://sts.{accountDomain}", UriKind.Absolute, out Uri? result))
            {
                throw new ArgumentException("The value could not be used to construct a valid endpoint.", nameof(accountDomain));
            }

            return result;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.washingtonpost</groupId>
        <artifactId>wp-oss-parent-pom</artifactId>
        <version>0.0.8</version>
    </parent>

    <groupId>com.washingtonpost.dropwizard</groupId>
    <artifactId>dropwizard-mongo</artifactId>
    <version>4.0.8-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <version.assertj>2.2.0</version.assertj>
        <version.dropwizard.guice>0.8.4.0</version.dropwizard.guice>
        <version.junit>4.12</version.junit>
        <version.mongo.driver>3.12.10</version.mongo.driver>
        <version.wp.checkstyle>2.0</version.wp.checkstyle>
    </properties>

    <scm>
        <connection>scm:git:git@github.com:washingtonpost/dropwizard-mongo-module.git</connection>
        <developerConnection>scm:git:git@github.com:washingtonpost/dropwizard-mongo-module.git</developerConnection>
        <url>https://github.com/washingtonpost/dropwizard-mongo-module</url>
        <tag>4.0.6</tag>
    </scm>

    <dependencies>
        <dependency>
            <groupId>com.hubspot.dropwizard</groupId>
            <artifactId>dropwizard-guice</artifactId>
            <version>${version.dropwizard.guice}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>${version.mongo.driver}</version>
            <!-- Your DropWizard app should define the driver, or accept what comes in through a
            supporting library like mongojack -->
            <scope>provided</scope>
        </dependency>

        <!--
            TEST SCOPED dependencies
        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.junit}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${version.assertj}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-checkstyle-plugin</artifactId>
                    <version>${version.maven.checkstyle.plugin}</version>
                    <executions>
                        <execution>
                            <id>validate</id>
                            <phase>validate</phase>
                            <configuration>
                                <configLocation>checkstyle.xml</configLocation>
                                <encoding>${project.build.sourceEncoding}</encoding>
                                <consoleOutput>true</consoleOutput>
                                <failsOnError>true</failsOnError>
                                <linkXRef>false</linkXRef>
                            </configuration>
                            <goals>
                                <goal>check</goal>
                            </goals>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>com.washingtonpost</groupId>
                            <artifactId>wp-java-checkstyle</artifactId>
                            <version>${version.wp.checkstyle}</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

	<!-- 加载jdbc.properties配置文件 dl.dlutils.utils.security.EncryptablePropertyPlaceholderConfigurer-->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<!-- 使用多个PropertyPlaceholderConfigurer来分散配置,达到整合多工程下的多个分散的Properties文件,
		需要使用order属性区分多个PropertyPlaceholderConfigurer,order属性代表其加载顺序-->
		<property name="order" value="1" />
		<!-- 允许JVM参数覆盖 -->
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
		<!-- 忽略没有找到的资源文件
			 是否忽略不可解析的Placeholder,如配置了多个PropertyPlaceholderConfigurer,则需设置为true
		-->
		<property name="ignoreUnresolvablePlaceholders" value="true"/>
		<!-- 配置资源文件 -->
		<property name="locations">
			<list>
				<!-- 使用list属性可以配置多个value -->
				<value>classpath:spring_config/jdbc.properties</value>
			</list>
		</property>
	</bean>

	<!-- 定义druid数据源 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"  init-method="init">
		<property name="driverClassName" value="${jdbc.driverClass}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="1" />
		<property name="minIdle" value="1" />
		<property name="maxActive" value="10" />
		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="10000" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="testWhileIdle" value="true" />
		<!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
		<property name="testOnBorrow" value="true" />
		<property name="testOnReturn" value="false" />
		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
		<!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
		<property name="defaultAutoCommit" value="true" />
		<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
		<property name="validationQuery" value="select 1 " />
		<property name="filters" value="stat" />
		<property name="proxyFilters">
			<list>
			 <ref bean="logFilter" />
			</list>
		</property>
	</bean>
	<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
		<property name="statementExecutableSqlLogEnable" value="false" />
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory</prop>
				<prop key="hibernate.cache.use_second_level_cache">false</prop>
				<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
				<prop key="hibernate.cache.use_query_cache">false</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.default_schema">${jdbc.schema}</prop>
			</props>
		</property>
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="packagesToScan">
			<list>
				<value>com.usky</value>
			</list>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 事务控制 -->
	<tx:advice id="hibernateTxAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="do*" propagation="REQUIRED" />
            <tx:method name="*" read-only="false" />
		</tx:attributes>
	</tx:advice>

	<aop:aspectj-autoproxy />

	<aop:config proxy-target-class="true">
		<aop:advisor pointcut="execution(* dl..service.support..*ServiceImpl.*(..))) " advice-ref="hibernateTxAdvice"/>
	</aop:config>

</beans>


text:
<?xml version="1.0" encoding="utf-8"?>

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
          android:horizontalGap="@fraction/pin_code_keyboard_key_horizontal_gap"
          android:verticalGap="1dp"
          android:keyHeight="64dp"
          android:keyWidth="@fraction/pin_code_keyboard_key_width">
    <Row android:rowEdgeFlags="top">
        <Key
            android:codes="49"
            android:keyEdgeFlags="left"
            android:keyLabel="1"/>
        <Key
            android:codes="50"
            android:keyLabel="2"/>
        <Key
            android:codes="51"
            android:keyLabel="3"
            android:keyEdgeFlags="right"/>
    </Row>
    <Row>
        <Key
            android:keyEdgeFlags="left"
            android:codes="52"
            android:keyLabel="4"/>
        <Key
            android:codes="53"
            android:keyLabel="5"/>
        <Key
            android:codes="54"
            android:keyLabel="6"
            android:keyEdgeFlags="right"/>
    </Row>
    <Row>
        <Key
            android:keyEdgeFlags="left"
            android:codes="55"
            android:keyLabel="7"/>
        <Key
            android:codes="56"
            android:keyLabel="8"/>
        <Key
            android:codes="57"
            android:keyLabel="9"
            android:keyEdgeFlags="right"/>
    </Row>
    <Row>
        <Key
            android:keyEdgeFlags="left"
            android:codes="-3"
            android:keyLabel="C"/>
        <Key
            android:codes="48"
            android:keyLabel="0"/>
        <Key
            android:codes="-5"
            android:keyIcon="@drawable/sym_keyboard_delete_holo_dark"
            android:isRepeatable="true"
            android:keyEdgeFlags="right"/>
    </Row>
</Keyboard>


text:
package de.fuberlin.wiwiss.pubby;

import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.shared.PrefixMapping;

/**
 * Helper class that splits URIs into prefix and local name
 * according to a Jena PrefixMapping.
 */
public class URIPrefixer {
	private final Resource resource;
	private final String prefix;
	private final String localName;

	public URIPrefixer(String uri, PrefixMapping prefixes) {
		this(ResourceFactory.createResource(uri), prefixes);
	}

	public URIPrefixer(Resource resource, PrefixMapping prefixes) {
		this.resource = resource;
		String uri = resource.getURI();
		Iterator<String> it = prefixes.getNsPrefixMap().keySet().iterator();
		while (it.hasNext() && uri != null) {
			String entryPrefix = it.next();
			String entryURI = prefixes.getNsPrefixURI(entryPrefix);
			if (uri.startsWith(entryURI)) {
				prefix = entryPrefix;
				localName = uri.substring(entryURI.length());
				return;
			}
		}
		prefix = null;
		localName = null;
	}

	public boolean hasPrefix() {
		return prefix != null;
	}

	public String getPrefix() {
		return prefix;
	}

	public String getLocalName() {
		if (resource.isAnon()) return null;
		if (localName == null) {
			Matcher matcher = Pattern.compile("([^#/:?]+)[#/:?]*$").matcher(resource.getURI());
			if (matcher.find()) {
				return matcher.group(1);
			}
			return "";	// Only happens if the URI contains only excluded chars
		}
		return localName;
	}

	public String toTurtle() {
		if (resource.isAnon()) return "[]";
		if (hasPrefix()) {
			return getPrefix() + ":" + getLocalName();
		}
		return "<" + resource.getURI() + ">";
	}
}