text:
<config>
 <Rev2008>
  <translation>

   <i_windup value="0"/>
   <d value="0.4"/>
   <velMultiplier value="1.3"/>
   <accelMultiplier value="20"/>
   <minEffectiveVelocity value="0.3"/>
  </translation>
  <rotation>

   <i_windup value="0"/>
   <d value="0.05"/>
   <velMultiplier value="0.1"/>
   <minEffectiveAngularSpeed value="1.2"/>
  </rotation>
  <kicker>
   <maxKick value="200"/>
   <maxChip value="150"/>
  </kicker>
  <pivot>
   <velMultiplier value="0.3"/>
  </pivot>
  <dribbler>
   <multiplier value="1"/>
  </dribbler>
  <chipper>
   <calibSlope value="2.20227"/>
   <calibOffset value="70.0727"/>
  </chipper>
  <velocity>

   <i_windup value="0"/>
   <d value="0"/>
  </velocity>
 </Rev2008>
 <Rev2011>
  <translation>

   <i_windup value="0"/>
   <accelMultiplier value="16"/>
   <d value="0.2"/>
   <velMultiplier value="1.2"/>
   <minEffectiveVelocity value="0.35"/>
  </translation>
  <rotation>

   <i_windup value="0"/>
   <d value="0.05"/>
   <velMultiplier value="0.1"/>
   <minEffectiveAngularSpeed value="1.6"/>
  </rotation>
  <kicker>
   <maxKick value="255"/>
   <maxChip value="200"/>
  </kicker>
  <pivot>
   <velMultiplier value="0.01"/>
  </pivot>
  <dribbler>
   <multiplier value="1"/>
  </dribbler>
  <chipper>
   <calibSlope value="2.20227"/>
   <calibOffset value="70.0727"/>
  </chipper>
  <velocity>

   <i_windup value="0"/>
   <d value="0"/>
  </velocity>
 </Rev2011>
 <Robot_Statuses>
  <Robot_0>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_0>
  <Robot_1>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_1>
  <Robot_2>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_2>
  <Robot_3>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_3>
  <Robot_4>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_4>
  <Robot_5>
   <Chipper_Enabled value="false"/>
   <Kicker_Enabled value="false"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_5>
  <Robot_6>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_6>
  <Robot_7>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_7>
  <Robot_8>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_8>
  <Robot_9>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_9>
  <Robot_10>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_10>
  <Robot_11>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_11>
  <Robot_12>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_12>
  <Robot_13>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_13>
  <Robot_14>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_14>
  <Robot_15>
   <Chipper_Enabled value="true"/>
   <Kicker_Enabled value="true"/>
   <Ball_Sense_Enabled value="true"/>
   <Dribbler_Enabled value="true"/>
  </Robot_15>
 </Robot_Statuses>
 <ChipCalibration>
  <_a0 value="-3.90845"/>
  <_a1 value="0.0873787"/>
  <_a2 value="-0.000365537"/>
  <_a3 value="4.37278e-07"/>
  <Dribble_Speed value="40"/>
  <Max_Chip_Distance value="2.5"/>
  <Roll_Distance value="0.1"/>
 </ChipCalibration>
 <MotionControl>
  <Max_Acceleration value="2"/>
  <Max_Velocity value="2"/>
  <PathJitterCompensationFactor value="2"/>
  <PathChangeBoost value="50"/>
  <X_Multiplier value="1"/>
 </MotionControl>
 <PathPlanner>
  <Max_Acceleration value="1"/>
  <Max_Velocity value="2"/>
  <selfAvoidRadius value="0.09"/>
  <oppAvoidRadius value="0.08"/>
  <oppGoalieAvoidRadius value="0.14"/>
  <replanTimeout value="5"/>
  <goalChangeThreshold value="0.1"/>
  <Field_Edge_Obstacle value="0.33"/>
  <EscapeObstaclesPathPlanner>
   <stepSize value="0.1"/>
  </EscapeObstaclesPathPlanner>
  <RRT>
   <EnableDebugDrawing value="false"/>
   <StepSize value="0.15"/>
   <GoalBias value="0.3"/>
   <WayPointBias value="0.5"/>
  </RRT>
  <goalPosChangeThreshold value="0.025"/>
  <goalVelChangeThreshold value="0.025"/>
  <dribbleOutOfBoundsOffset value="0.05"/>
 </PathPlanner>
 <MotionConstraints>
  <Max_Acceleration value="1"/>
  <Max_Velocity value="1"/>
  <Max_Angle_Speed value="0.436"/>
  <Replan_Threshold value="0.3"/>
  <Replan_Lead_Time value="0"/>
  <Max_Centripetal_Acceleration value="0.5"/>
 </MotionConstraints>
 <Rev2015>
  <translation>

   <i_windup value="10"/>
   <accelMultiplier value="0"/>
   <d value="0.4"/>
   <velMultiplier value="1.2"/>
   <minEffectiveVelocity value="0.1"/>
  </translation>
  <rotation>

   <i_windup value="0"/>
   <d value="1"/>
   <velMultiplier value="1"/>
   <minEffectiveAngularSpeed value="0.5"/>
  </rotation>
  <kicker>
   <maxKick value="255"/>
   <maxChip value="200"/>
  </kicker>
  <pivot>
   <velMultiplier value="0.01"/>
  </pivot>
  <dribbler>
   <multiplier value="1"/>
  </dribbler>
  <chipper>
   <calibSlope value="2.20227"/>
   <calibOffset value="70.0727"/>
  </chipper>
  <velocity>

   <i_windup value="0"/>
   <d value="0"/>
  </velocity>
 </Rev2015>
 <WindowEvaluator>
  <angleScoreCoeff value="0.7"/>
  <distScoreCoeff value="0.3"/>
 </WindowEvaluator>
 <Joystick>
  <Max_Rotation_Speed value="12.5664"/>
  <Max_Damped_Rotation_Speed value="4"/>
  <Max_Translation_Speed value="3"/>
  <Max_Damped_Translation_Speed value="0.7"/>
 </Joystick>
 <SpaceNavJoystick>
  <Positive_Dribbler_Deadzone value="100"/>
  <Negative_Dribbler_Deadzone value="-150"/>
 </SpaceNavJoystick>
 <EscapeObstaclesPathPlanner>
  <stepSize value="0.1"/>
  <goalChangeThreshold value="0.09"/>
 </EscapeObstaclesPathPlanner>
 <RotationConstraints>
  <Max_Rotation_Speed value="4"/>
  <Max_Rotation_Acceleration value="4"/>
 </RotationConstraints>
 <Pivot>
  <radius value="1.1"/>
 </Pivot>
 <TargetVelPathPlanner>
  <velChangeReplanThreshold value="0.05"/>
 </TargetVelPathPlanner>
 <KickEvaluator>
  <kick_std_dev value="0.08"/>
  <kick_mean value="0"/>
  <robot_std_dev value="0.3"/>
  <start_x_offset value="0.1"/>
 </KickEvaluator>
 <RRTPlanner>
  <partialReplanLeadTime value="0.2"/>
 </RRTPlanner>
 <VisionFilter>
  <Bounce>
   <robot_body_lin_dampen value="0.9"/>
   <robot_mouth_lin_dampen value="0.3"/>
   <robot_body_angle_dampen value="0"/>
   <robot_mouth_angle_dampen value="0"/>
  </Bounce>
  <KalmanBall>
   <max_time_outside_vision value="0.2"/>
  </KalmanBall>
  <WorldBall>
   <ball_merger_power value="1.5"/>
  </WorldBall>
  <Camera>
   <MHKF_radius_cutoff value="0.5"/>
   <use_MHKF value="true"/>
   <max_num_kalman_balls value="10"/>
   <max_num_kalman_robots value="10"/>
  </Camera>
  <Kick>
   <Detector>
    <fast_kick_timeout value="1"/>
    <slow_kick_timeout value="0.5"/>
    <same_kick_timeout value="0.05"/>
    <fast_acceleration_trigger value="750"/>
    <slow_robot_dist_filter_cutoff value="3"/>
    <slow_one_robot_within_dist value="0.15"/>
    <slow_any_robot_past_dist value="0.16"/>
    <slow_min_ball_speed value="0.6"/>
    <slow_max_kick_angle value="0.34"/>
    <slow_hist_length value="5"/>
    <fast_hist_length value="3"/>
   </Detector>
  </Kick>
  <Ball>
   <init_covariance value="100"/>
   <process_noise value="0.1"/>
   <observation_noise value="2"/>
  </Ball>
  <Robot>
   <init_covariance value="100"/>
   <process_noise value="0.1"/>
   <observation_noise value="2"/>
   <orientation_scale value="1"/>
  </Robot>
  <KalmanRobot>
   <max_time_outside_vision value="0.5"/>
  </KalmanRobot>
  <WorldRobot>
   <robot_merger_power value="1.5"/>
  </WorldRobot>
  <loop_dt value="0.01"/>
  <max_num_cameras value="12"/>
  <Health>
   <init value="2"/>
   <increment value="2"/>
   <decrement value="1"/>
   <max value="20"/>
   <min value="1"/>
  </Health>
 </VisionFilter>
 <Capture>
  <Settle>
   <ballSpeedPercentForDampen value="0"/>
   <searchStartTime value="0.1"/>
   <searchEndtime value="10"/>
   <searchIncTime value="0.2"/>
   <interceptBufferTime value="1"/>
   <targetPointGain value="0.5"/>
   <ballVelGain value="0.9"/>
   <maxAnglePathTargetChange value="20"/>
   <maxBallVelForPathReset value="2"/>
   <maxBallAngleForReset value="20"/>
   <maxNumInvalidPaths value="50"/>
   <ballAvoidDistance value="0.3"/>
   <searchStartDist value="0"/>
   <searchEndDist value="7"/>
   <searchIncDist value="0.2"/>
   <shortcutDist value="0.09"/>
   <maxBounceAngle value="45"/>
  </Settle>
  <Collect>
   <ballSpeedApproachDirectionCutoff value="0.1"/>
   <approachAccelScalePercent value="0.6"/>
   <controlAccelScalePercent value="0.8"/>
   <approachDistTarget value="0.1"/>
   <touchDeltaSpeed value="0.2"/>
   <distCutoffToControl value="0.05"/>
   <velCutoffToControl value="2"/>
   <stopDistScale value="0.5"/>
   <targetPointAveragingGain value="0.8"/>
   <distCutoffToApproach value="0.15"/>
   <velocityControlScale value="0"/>
  </Collect>
 </Capture>
</config>


text:
require 'spec_helper'

describe Ascetic::Config do
  let(:base_hash) do
    { 'first_level' => { 'second_level' => true },
      'array_key' => ['array_value'] }
  end

  let(:symbolized_hash) { symbolize base_hash }
  let(:config) { Ascetic::Config.new file }

  describe 'with JSON' do
    let(:file) { 'config.json' }

    describe '#strategy' do
      subject { config.strategy }
      it { File.stub(:read, '') { subject.must_equal JSON }}
    end

    describe '#message' do
      subject { config.message }
      it { File.stub(:read, '') { subject.must_equal :parse } }
    end

    describe '#parse' do
      let(:json) { base_hash.to_json }
      subject { File.stub(:read, json) { config.parse } }
      it { subject.must_be_instance_of Hash }
      it { subject.must_equal symbolized_hash }
    end

  end

  describe 'with YAML' do
    let(:file) { 'config.yml' }

    describe '#strategy' do
      subject { config.strategy }
      it { File.stub(:read, '') { subject.must_equal YAML }}
    end

    describe '#message' do
      subject { config.message }
      it { File.stub(:read, '') { subject.must_equal :load } }
    end

    describe '#parse' do
      let(:yaml) { base_hash.to_yaml }
      subject { File.stub(:read, yaml) { config.parse } }
      it { subject.must_be_instance_of Hash }
      it { subject.must_equal symbolized_hash }
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
"""
Copyright 2013 OpERA

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""

## @package ssf

from gnuradio import gr
from gnuradio import fft
from gnuradio import blocks

# OpERA imports
from device import UHDSSArch
from sensing import *
from gr_blocks.utils import GroupInN

import time
import threading
import numpy as np

#::TODO:: descricao de metodos e seus parametros
class QLearningWorker(gr.sync_block):
    """
     QLearning worker block.
    Input: vector of vec_size elements.
    Output: (decision, energy), where:
      - decision: 1 or 0
      - energy  : energy calculated
    """

    def __init__(self, vec_size, algorithm):
        """
        CTOR
        @param vec_size Size of each input.
        @param algorithm Detection algorithm. An AbstractAlgorithm implementation.
        """

        # input: array of floats
        # output: a tuple of (energy, decision)
        gr.sync_block.__init__(self,
                               name="qlearning_worker",
                               in_sig = [np.dtype((np.float32, vec_size))],
                               out_sig= [np.float32, np.float32]
                               )
        self._algorithm = algorithm

    def work(self, input_items, output_items):
        """
        GNU Radio main function.
        @param input_items
        @param output_items
        @return
        """
        for idx in range(len(input_items[0])):
            output_items[1][idx], output_items[0][idx] = self._algorithm.decision( input_items[0][idx] )

        return len(output_items)

class SimpleRankingDetector(gr.hier_block2):
    """
    QLearning hierarchical block.
    Builds flow graph from source to sync.
    """

    def __init__(self, fft_size, mavg_size, ed_threshold):
        """
        CTOR
        @param fft_size FFT Size
        @param mavg_size Energy Detector mavg size.
        """

        gr.hier_block2.__init__(self,
                                name="simple_ranking_detector",
                                input_signature=gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                output_signature=gr.io_signature(2, 2, gr.sizeof_float)
                                )

        # Blocks
        # Convert the output of a FFT
        self.s2v_0 = blocks.stream_to_vector(gr.sizeof_gr_complex, fft_size)
        self.fft_0 = fft.fft_vcc(fft_size, True, [])
        self.c2mag_0 = blocks.complex_to_mag_squared(fft_size)

        # Instantiate the energy calculator
        from sensing import EnergyDecision
        self.ql = QLearningWorker(fft_size, algorithm=EnergyDecision(ed_threshold))

        #::TODO:: parece que nao tem mais o metodo connect
        # Flow graph
        self.connect(self, self.s2v_0, self.fft_0, self.c2mag_0, self.ql)

        self.connect((self.ql, 0), (self, 0))
        self.connect((self.ql, 1), (self, 1))

class RankingArch( UHDSSArch ):
    """
    Ranking architecture.
    Construct the ranking architecture.
    """

    def __init__(self, max_items_group):
        """
        CTOR.
        @param device     RadioDevice instance.
        @param detector   A SS detector.
        @param max_items_group Number of ouputs to group.
        @return A tuple with 3 elements: (final decision, energy, avg energy)
        """

        #
        self._detector = SimpleRankingDetector(512, 5, 0.3)

        # Group items
        self._grouper  = GroupInN(
                max_items_group = max_items_group,
                callback = None,
                n_inputs = 2
            )

        UHDSSArch.__init__(
                self,
                name = "ranking_arch",
                input_signature  = gr.io_signature(1, 1, gr.sizeof_gr_complex),
                output_signature = gr.io_signature(0, 0, 0)
         )

    def _build(self, input_signature, output_signature):
        """
        """

        self._add_connections([(self._detector, 0), (self._grouper, 0)])
        self._add_connections([(self._detector, 1), (self._grouper, 1)])

        return self._detector

        # no outputs

    def _get_sensing_data(self, the_channel, sensing_time):
        """
        Configure the device to sense the given frequency.
        @param the_channel Channel object instance. Channel to sense.
        @param sensing_time Duration of sensing.
        @return SS information of channel.
        """

        # Configure device center frequency
        # ::TRICK:: self._device  can be a DeviceChannelModel object
        #           If is the case, then check the DeviceChannelModel::center_freq method
        self.radio.set_center_freq( the_channel )

        self._grouper.set_enable( True )
        time.sleep( sensing_time )
        self._grouper.set_enable( False )

        return self._grouper.get_items()

    def sense_channel(self, the_channel, sensing_time):
        """
        ## SS on a single channel
        # Reimplement from UHDSSArch::sense_channel
        # @param the_channel Channel to be sensed.
        # @param sensing_time Sensing duration on channel.
        """
        return self._get_sensing_data( the_channel, sensing_time )

    def sense_channel_list(self, the_list, sensing_time):
        """
        @param the_list
        @param sensing_time
        """
        res = []

        for channel in the_list:
            x = self.sense_channel(channel, sensing_time)

            res.append( (channel.get_channel() , x) )

        return res


text:
#import "TWTRTweetUserMentionEntity.h"

#import "TWTRDictUtil.h"
#import "TWTRAPIConstantsStatus.h"

@implementation TWTRTweetUserMentionEntity

#pragma mark - Init

- (instancetype)initWithJSONDictionary:(NSDictionary *)dict
{
    self = [super initWithJSONDictionary:dict];

    if (self) {
        _userID = [[TWTRDictUtil twtr_stringFromNumberForKey:TWTRAPIConstantsStatusFieldUserMentionEntityUserID inDict:dict] copy];
        _name = [[TWTRDictUtil twtr_stringForKey:TWTRAPIConstantsStatusFieldUserMentionEntityName inDict:dict] copy];
        _screenName = [[TWTRDictUtil twtr_stringForKey:TWTRAPIConstantsStatusFieldUserMentionEntityScreenName inDict:dict] copy];
    }

    return self;
}

#pragma mark - NSCoding

- (instancetype)initWithCoder:(NSCoder *)decoder
{
    self = [super initWithCoder:decoder];

    if (self) {
        _userID = [[decoder decodeObjectForKey:TWTRAPIConstantsStatusFieldUserMentionEntityUserID] copy];
        _name = [[decoder decodeObjectForKey:TWTRAPIConstantsStatusFieldUserMentionEntityName] copy];
        _screenName = [[decoder decodeObjectForKey:TWTRAPIConstantsStatusFieldUserMentionEntityScreenName] copy];
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [super encodeWithCoder:encoder];

    [encoder encodeObject:self.userID forKey:TWTRAPIConstantsStatusFieldUserMentionEntityUserID];
    [encoder encodeObject:self.name forKey:TWTRAPIConstantsStatusFieldUserMentionEntityName];
    [encoder encodeObject:self.screenName forKey:TWTRAPIConstantsStatusFieldUserMentionEntityScreenName];
}

- (NSString *)accessibilityValue
{
    return self.screenName;
}

@end


text:
use std::{
    cell::UnsafeCell,
    hint::spin_loop,
    sync::atomic::{
        AtomicU64,
        Ordering::{Acquire, Release},
    },
};

const LOCKED: u64 = 1 << 63;

#[derive(Default, Debug)]
pub struct OptimisticAccessCell<T: Send + 'static> {
    version_lock: AtomicU64,
    item: UnsafeCell<T>,
}

unsafe impl<T: Send> Send for OptimisticAccessCell<T> {}

unsafe impl<T: Send> Sync for OptimisticAccessCell<T> {}

struct DeferUnlock<'a, T: Send + 'static> {
    oac: &'a OptimisticAccessCell<T>,
}

impl<'a, T: Send + 'static> Drop for DeferUnlock<'a, T> {
    fn drop(&mut self) {
        // unlock
        assert_eq!(
            self.oac.version_lock.fetch_xor(LOCKED, Release) & LOCKED,
            LOCKED
        );
    }
}

impl<T: Send + 'static> OptimisticAccessCell<T> {
    pub fn mutate<R, F: FnOnce(&mut T) -> R>(&self, f: F) -> R {
        // acquire lock
        while self.version_lock.fetch_or(LOCKED, Acquire) & LOCKED == 0 {
            spin_loop()
        }

        // Use this dropper struct to unlock because it
        // will be dropped even if a panic happens in the
        // passed-in function.
        let unlock_on_drop = DeferUnlock { oac: &self };

        // mutate
        let ret = f(unsafe { &mut *self.item.get() });

        drop(unlock_on_drop);

        ret
    }

    pub fn access<R: Copy, F: Fn(&T) -> R>(&self, f: F) -> R {
        let mut vsn = self.version_lock.load(Acquire);

        loop {
            // spin if locked
            while vsn & LOCKED == LOCKED {
                spin_loop();
                vsn = self.version_lock.load(Acquire);
            }

            // access
            let ret = f(unsafe { &*self.item.get() });

            // vaidate, spin if changed
            let vsn2 = self.version_lock.load(Acquire);
            if vsn == vsn2 {
                return ret;
            } else {
                vsn = vsn2;
            }
        }
    }
}


text:
BEGIN;

ALTER TABLE AuthorizedApp RENAME TO APIConfig;
ALTER INDEX authorized_app_pkey RENAME TO apiconfig_pkey;
ALTER INDEX authorized_app_app_package_name_idx RENAME TO apiconfig_app_package_name_idx;

END;


text:
"""The file defines global variables."""

PROJECT_ID = "apache-beam-testing"
# Subscription for PubSub Topic
SUBSCRIPTION_ID = f"projects/{PROJECT_ID}/subscriptions/newsgroup-dataset-subscription"
JOB_NAME = "online-clustering-birch"
NUM_WORKERS = 1
MODEL_NAME = "sentence-transformers-stsb-distilbert-base"
TOKENIZER_NAME = "sentence-transformers/stsb-distilbert-base"
MODEL_STATE_DICT_PATH = f"gs://{PROJECT_ID}-ml-examples/{MODEL_NAME}/pytorch_model.bin"
MODEL_CONFIG_PATH = TOKENIZER_NAME


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

    DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

    Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.

    The contents of this file are subject to the terms of either the GNU
    General Public License Version 2 only ("GPL") or the Common Development
    and Distribution License("CDDL") (collectively, the "License").  You
    may not use this file except in compliance with the License.  You can
    obtain a copy of the License at
    https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
    or packager/legal/LICENSE.txt.  See the License for the specific
    language governing permissions and limitations under the License.

    When distributing the software, include this License Header Notice in each
    file and include the License file at packager/legal/LICENSE.txt.

    GPL Classpath Exception:
    Oracle designates this particular file as subject to the "Classpath"
    exception as provided by Oracle in the GPL Version 2 section of the License
    file that accompanied this code.

    Modifications:
    If applicable, add the following below the License Header, with the fields
    enclosed by brackets [] replaced by your own identifying information:
    "Portions Copyright [year] [name of copyright owner]"

    Contributor(s):
    If you wish your version of this file to be governed by only the CDDL or
    only the GPL Version 2, indicate your decision by adding "[Contributor]
    elects to include this software in this distribution under the [CDDL or GPL
    Version 2] license."  If you don't indicate a single choice of license, a
    recipient has the option to distribute your version of this file under
    either the CDDL, the GPL Version 2 or to extend the choice of license to
    its licensees as provided above.  However, if you add GPL Version 2 code
    and therefore, elected the GPL Version 2 license, then the option applies
    only if the new code is made subject to such option by the copyright
    holder.

-->

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.glassfish.test.admingui</groupId>
    <artifactId>console-auto-tests</artifactId>
    <version>4.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Admin Console Auto Tests</name>
    <description>This module contains the dev tests for the admin console</description>

    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.32.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.7.1</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>2.7.1</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <forkMode>never</forkMode>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <version>2.4.1</version>
                <executions>
                    <execution>
                        <id>auto-clean</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>clean</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.1</version>
                <executions>
                    <execution>
                        <id>package-tests</id>
                        <phase>package</phase>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');

const mongod = new MongoMemoryServer({instance: {port: 27017, dbName:'test'}});

module.exports.connect = async () => {
    const uri = await mongod.getConnectionString();

    const mongooseOpts = {
        useNewUrlParser: true,
        useUnifiedTopology: true
    };

    await mongoose.connect(uri, mongooseOpts);
}

module.exports.closeDatabase = async () => {
    await mongoose.connection.dropDatabase();
    await mongoose.connection.close();
    await mongod.stop();
}

module.exports.clearDatabase = async () => {
    const collections = mongoose.connection.collections;

    for (const key in collections) {
        const collection = collections[key];
        await collection.deleteMany();
    }
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;

namespace Codex.Utilities
{
    /// <summary>
    /// Utility methods for paths and Uris (including relativizing and derelativizing)
    /// </summary>
    public static partial class PathUtilities
    {
        /// <summary>
        /// Indicates that a relative path is same as the base path
        /// </summary>
        public const string CurrentDirectoryRelativePath = @"./";

        public static string GetRelativePath(string directory, string path)
        {
            string result = null;
            if (!string.IsNullOrEmpty(directory) && path.StartsWith(directory, StringComparison.OrdinalIgnoreCase))
            {
                result = path.Substring(directory.Length).TrimStart('/', '\\');
            }

            return result;
        }

        public static string GetExtension(string path)
        {
            for (int i = path.Length - 1; i >= 0; i--)
            {
                if (path[i] == '\\')
                {
                    return string.Empty;
                }

                if (path[i] == '.')
                {
                    return path.Substring(i);
                }
            }

            return string.Empty;
        }

        public static string GetDirectoryName(string path)
        {
            var index = path.LastIndexOf('\\');
            return path.Substring(0, index > 0 ? index : 0);
        }

        /// <summary>
        /// Ensures that the path has a trailing slash at the end
        /// </summary>
        /// <param name="path">the path</param>
        /// <returns>the path ending with a trailing slash</returns>
        public static string EnsureTrailingSlash(string path)
        {
            return PathUtilities.EnsureTrailingSlash(path, Path.DirectorySeparatorChar);
        }

        /// <summary>
        /// Ensures that the path has a trailing slash at the end
        /// </summary>
        /// <param name="path">the path</param>
        /// <param name="separatorChar">the trailing separator char</param>
        /// <returns>the path ending with a trailing slash</returns>
        public static string EnsureTrailingSlash(string path, char separatorChar)
        {
            if (path[path.Length - 1] != separatorChar)
            {
                return path + separatorChar;
            }

            return path;
        }
    }
}


text:
namespace InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers
{

using System;
using FlatBuffers;

public struct Material : IFlatbufferObject
{
  private Table __p;
  public ByteBuffer ByteBuffer { get { return __p.bb; } }
  public static Material GetRootAsMaterial(ByteBuffer _bb) { return GetRootAsMaterial(_bb, new Material()); }
  public static Material GetRootAsMaterial(ByteBuffer _bb, Material obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
  public void __init(int _i, ByteBuffer _bb) { __p.bb_pos = _i; __p.bb = _bb; }
  public Material __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }

  public string Id { get { int o = __p.__offset(4); return o != 0 ? __p.__string(o + __p.bb_pos) : null; } }
  public ArraySegment<byte>? GetIdBytes() { return __p.__vector_as_arraysegment(4); }
  public string Name { get { int o = __p.__offset(6); return o != 0 ? __p.__string(o + __p.bb_pos) : null; } }
  public ArraySegment<byte>? GetNameBytes() { return __p.__vector_as_arraysegment(6); }
  public float Color(int j) { int o = __p.__offset(8); return o != 0 ? __p.bb.GetFloat(__p.__vector(o) + j * 4) : (float)0; }
  public int ColorLength { get { int o = __p.__offset(8); return o != 0 ? __p.__vector_len(o) : 0; } }
  public ArraySegment<byte>? GetColorBytes() { return __p.__vector_as_arraysegment(8); }
  public float ShinyPercent { get { int o = __p.__offset(10); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)0.0f; } }
  public float Alpha { get { int o = __p.__offset(12); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)0.0f; } }
  public InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Texture? DiffuseTexture { get { int o = __p.__offset(14); return o != 0 ? (InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Texture?)(new InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Texture()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } }

  public static Offset<Material> CreateMaterial(FlatBufferBuilder builder,
      StringOffset idOffset = default(StringOffset),
      StringOffset nameOffset = default(StringOffset),
      VectorOffset colorOffset = default(VectorOffset),
      float shinyPercent = 0.0f,
      float alpha = 0.0f,
      Offset<InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Texture> diffuseTextureOffset = default(Offset<InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Texture>)) {
    builder.StartObject(6);
    Material.AddDiffuseTexture(builder, diffuseTextureOffset);
    Material.AddAlpha(builder, alpha);
    Material.AddShinyPercent(builder, shinyPercent);
    Material.AddColor(builder, colorOffset);
    Material.AddName(builder, nameOffset);
    Material.AddId(builder, idOffset);
    return Material.EndMaterial(builder);
  }

  public static void StartMaterial(FlatBufferBuilder builder) { builder.StartObject(6); }
  public static void AddId(FlatBufferBuilder builder, StringOffset idOffset) { builder.AddOffset(0, idOffset.Value, 0); }
  public static void AddName(FlatBufferBuilder builder, StringOffset nameOffset) { builder.AddOffset(1, nameOffset.Value, 0); }
  public static void AddColor(FlatBufferBuilder builder, VectorOffset colorOffset) { builder.AddOffset(2, colorOffset.Value, 0); }
  public static VectorOffset CreateColorVector(FlatBufferBuilder builder, float[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddFloat(data[i]); return builder.EndVector(); }
  public static void StartColorVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
  public static void AddShinyPercent(FlatBufferBuilder builder, float shinyPercent) { builder.AddFloat(3, shinyPercent, 0.0f); }
  public static void AddAlpha(FlatBufferBuilder builder, float alpha) { builder.AddFloat(4, alpha, 0.0f); }
  public static void AddDiffuseTexture(FlatBufferBuilder builder, Offset<InWorldz.PrimExporter.ExpLib.ImportExport.BabylonFlatBuffers.Texture> diffuseTextureOffset) { builder.AddOffset(5, diffuseTextureOffset.Value, 0); }
  public static Offset<Material> EndMaterial(FlatBufferBuilder builder) {
    int o = builder.EndObject();
    return new Offset<Material>(o);
  }
};

}


text:
<?php

class Google_Service_IdentityToolkit_IdentitytoolkitRelyingpartySignOutUserRequest extends Google_Model
{
  public $instanceId;
  public $localId;

  public function setInstanceId($instanceId)
  {
    $this->instanceId = $instanceId;
  }
  public function getInstanceId()
  {
    return $this->instanceId;
  }
  public function setLocalId($localId)
  {
    $this->localId = $localId;
  }
  public function getLocalId()
  {
    return $this->localId;
  }
}


text:
namespace glm
{
	namespace test{
		void main_gtx_color_space_YCoCg();
	}//namespace test

    namespace gtx{
	//! GLM_GTX_color_space_YCoCg extension: RGB to YCoCg conversions and operations
    namespace color_space_YCoCg
    {
		/// \addtogroup gtx_color_space_YCoCg
		///@{

        //! Convert a color from RGB color space to YCoCg color space.
		//! From GLM_GTX_color_space_YCoCg extension.
		template <typename valType>
		detail::tvec3<valType> rgb2YCoCg(
			detail::tvec3<valType> const & rgbColor);

        //! Convert a color from YCoCg color space to RGB color space.
		//! From GLM_GTX_color_space_YCoCg extension.
        template <typename valType>
		detail::tvec3<valType> YCoCg2rgb(
			detail::tvec3<valType> const & YCoCgColor);

        //! Convert a color from RGB color space to YCoCgR color space.
		//! \see "YCoCg-R: A Color Space with RGB Reversibility and Low Dynamic Range"
		//! From GLM_GTX_color_space_YCoCg extension.
		template <typename valType>
		detail::tvec3<valType> rgb2YCoCgR(
			detail::tvec3<valType> const & rgbColor);

        //! Convert a color from YCoCgR color space to RGB color space.
		//! \see "YCoCg-R: A Color Space with RGB Reversibility and Low Dynamic Range"
		//! From GLM_GTX_color_space_YCoCg extension.
        template <typename valType>
		detail::tvec3<valType> YCoCgR2rgb(
			detail::tvec3<valType> const & YCoCgColor);

		///@}
	}//namespace color_space_YCoCg
	}//namespace gtx
}//namespace glm

#include "color_space_YCoCg.inl"

namespace glm{using namespace gtx::color_space_YCoCg;}

#endif//glm_gtx_color_space_YCoCg


text:
/* TODO:
 * Level 1: no administrative or security support
 *	(e.g., static BSSID to IP address mapping in each AP)
 * Level 2: support for dynamic mapping of BSSID to IP address
 * Level 3: support for encryption and authentication of IAPP messages
 * - add support for MOVE-notify and MOVE-response (this requires support for
 *   finding out IP address for previous AP using RADIUS)
 * - add support for Send- and ACK-Security-Block to speedup IEEE 802.1X during
 *   reassociation to another AP
 * - implement counters etc. for IAPP MIB
 * - verify endianness of fields in IAPP messages; are they big-endian as
 *   used here?
 * - RADIUS connection for AP registration and BSSID to IP address mapping
 * - TCP connection for IAPP MOVE, CACHE
 * - broadcast ESP for IAPP ADD-notify
 * - ESP for IAPP MOVE messages
 * - security block sending/processing
 * - IEEE 802.11 context transfer
 */

#include "utils/includes.h"
#include <net/if.h>
#include <sys/ioctl.h>
#ifdef USE_KERNEL_HEADERS
#include <linux/if_packet.h>
#else /* USE_KERNEL_HEADERS */
#include <netpacket/packet.h>
#endif /* USE_KERNEL_HEADERS */

#include "utils/common.h"
#include "utils/eloop.h"
#include "common/ieee802_11_defs.h"
#include "hostapd.h"
#include "ap_config.h"
#include "ieee802_11.h"
#include "sta_info.h"
#include "iapp.h"

#define IAPP_MULTICAST "224.0.1.178"
#define IAPP_UDP_PORT 3517
#define IAPP_TCP_PORT 3517

struct iapp_hdr {
	u8 version;
	u8 command;
	be16 identifier;
	be16 length;
	/* followed by length-6 octets of data */
} __attribute__ ((packed));

#define IAPP_VERSION 0

enum IAPP_COMMAND {
	IAPP_CMD_ADD_notify = 0,
	IAPP_CMD_MOVE_notify = 1,
	IAPP_CMD_MOVE_response = 2,
	IAPP_CMD_Send_Security_Block = 3,
	IAPP_CMD_ACK_Security_Block = 4,
	IAPP_CMD_CACHE_notify = 5,
	IAPP_CMD_CACHE_response = 6,
};

/* ADD-notify - multicast UDP on the local LAN */
struct iapp_add_notify {
	u8 addr_len; /* ETH_ALEN */
	u8 reserved;
	u8 mac_addr[ETH_ALEN];
	be16 seq_num;
} __attribute__ ((packed));

/* Layer 2 Update frame (802.2 Type 1 LLC XID Update response) */
struct iapp_layer2_update {
	u8 da[ETH_ALEN]; /* broadcast */
	u8 sa[ETH_ALEN]; /* STA addr */
	be16 len; /* 6 */
	u8 dsap; /* null DSAP address */
	u8 ssap; /* null SSAP address, CR=Response */
	u8 control;
	u8 xid_info[3];
} __attribute__ ((packed));

/* MOVE-notify - unicast TCP */
struct iapp_move_notify {
	u8 addr_len; /* ETH_ALEN */
	u8 reserved;
	u8 mac_addr[ETH_ALEN];
	u16 seq_num;
	u16 ctx_block_len;
	/* followed by ctx_block_len bytes */
} __attribute__ ((packed));

/* MOVE-response - unicast TCP */
struct iapp_move_response {
	u8 addr_len; /* ETH_ALEN */
	u8 status;
	u8 mac_addr[ETH_ALEN];
	u16 seq_num;
	u16 ctx_block_len;
	/* followed by ctx_block_len bytes */
} __attribute__ ((packed));

enum {
	IAPP_MOVE_SUCCESSFUL = 0,
	IAPP_MOVE_DENIED = 1,
	IAPP_MOVE_STALE_MOVE = 2,
};

/* CACHE-notify */
struct iapp_cache_notify {
	u8 addr_len; /* ETH_ALEN */
	u8 reserved;
	u8 mac_addr[ETH_ALEN];
	u16 seq_num;
	u8 current_ap[ETH_ALEN];
	u16 ctx_block_len;
	/* ctx_block_len bytes of context block followed by 16-bit context
	 * timeout */
} __attribute__ ((packed));

/* CACHE-response - unicast TCP */
struct iapp_cache_response {
	u8 addr_len; /* ETH_ALEN */
	u8 status;
	u8 mac_addr[ETH_ALEN];
	u16 seq_num;
} __attribute__ ((packed));

enum {
	IAPP_CACHE_SUCCESSFUL = 0,
	IAPP_CACHE_STALE_CACHE = 1,
};

/* Send-Security-Block - unicast TCP */
struct iapp_send_security_block {
	u8 iv[8];
	u16 sec_block_len;
	/* followed by sec_block_len bytes of security block */
} __attribute__ ((packed));

/* ACK-Security-Block - unicast TCP */
struct iapp_ack_security_block {
	u8 iv[8];
	u8 new_ap_ack_authenticator[48];
} __attribute__ ((packed));

struct iapp_data {
	struct hostapd_data *hapd;
	u16 identifier; /* next IAPP identifier */
	struct in_addr own, multicast;
	int udp_sock;
	int packet_sock;
};

static void iapp_send_add(struct iapp_data *iapp, u8 *mac_addr, u16 seq_num)
{
	char buf[128];
	struct iapp_hdr *hdr;
	struct iapp_add_notify *add;
	struct sockaddr_in addr;

	/* Send IAPP ADD-notify to remove possible association from other APs
	 */

	hdr = (struct iapp_hdr *) buf;
	hdr->version = IAPP_VERSION;
	hdr->command = IAPP_CMD_ADD_notify;
	hdr->identifier = host_to_be16(iapp->identifier++);
	hdr->length = host_to_be16(sizeof(*hdr) + sizeof(*add));

	add = (struct iapp_add_notify *) (hdr + 1);
	add->addr_len = ETH_ALEN;
	add->reserved = 0;
	os_memcpy(add->mac_addr, mac_addr, ETH_ALEN);

	add->seq_num = host_to_be16(seq_num);

	os_memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = iapp->multicast.s_addr;
	addr.sin_port = htons(IAPP_UDP_PORT);
	if (sendto(iapp->udp_sock, buf, (char *) (add + 1) - buf, 0,
		   (struct sockaddr *) &addr, sizeof(addr)) < 0)
		perror("sendto[IAPP-ADD]");
}

static void iapp_send_layer2_update(struct iapp_data *iapp, u8 *addr)
{
	struct iapp_layer2_update msg;

	/* Send Level 2 Update Frame to update forwarding tables in layer 2
	 * bridge devices */

	/* 802.2 Type 1 Logical Link Control (LLC) Exchange Identifier (XID)
	 * Update response frame; IEEE Std 802.2-1998, 5.4.1.2.1 */

	os_memset(msg.da, 0xff, ETH_ALEN);
	os_memcpy(msg.sa, addr, ETH_ALEN);
	msg.len = host_to_be16(6);
	msg.dsap = 0; /* NULL DSAP address */
	msg.ssap = 0x01; /* NULL SSAP address, CR Bit: Response */
	msg.control = 0xaf; /* XID response lsb.1111F101.
			     * F=0 (no poll command; unsolicited frame) */
	msg.xid_info[0] = 0x81; /* XID format identifier */
	msg.xid_info[1] = 1; /* LLC types/classes: Type 1 LLC */
	msg.xid_info[2] = 1 << 1; /* XID sender's receive window size (RW)
				   * FIX: what is correct RW with 802.11? */

	if (send(iapp->packet_sock, &msg, sizeof(msg), 0) < 0)
		perror("send[L2 Update]");
}

/**
 * iapp_new_station - IAPP processing for a new STA
 * @iapp: IAPP data
 * @sta: The associated station
 */
void iapp_new_station(struct iapp_data *iapp, struct sta_info *sta)
{
	struct ieee80211_mgmt *assoc;
	u16 seq;

	if (iapp == NULL)
		return;

	assoc = sta->last_assoc_req;
	seq = assoc ? WLAN_GET_SEQ_SEQ(le_to_host16(assoc->seq_ctrl)) : 0;

	/* IAPP-ADD.request(MAC Address, Sequence Number, Timeout) */
	hostapd_logger(iapp->hapd, sta->addr, HOSTAPD_MODULE_IAPP,
		       HOSTAPD_LEVEL_DEBUG, "IAPP-ADD.request(seq=%d)", seq);
	iapp_send_layer2_update(iapp, sta->addr);
	iapp_send_add(iapp, sta->addr, seq);

	if (assoc && WLAN_FC_GET_STYPE(le_to_host16(assoc->frame_control)) ==
	    WLAN_FC_STYPE_REASSOC_REQ) {
		/* IAPP-MOVE.request(MAC Address, Sequence Number, Old AP,
		 *                   Context Block, Timeout)
		 */
		/* TODO: Send IAPP-MOVE to the old AP; Map Old AP BSSID to
		 * IP address */
	}
}

static void iapp_process_add_notify(struct iapp_data *iapp,
				    struct sockaddr_in *from,
				    struct iapp_hdr *hdr, int len)
{
	struct iapp_add_notify *add = (struct iapp_add_notify *) (hdr + 1);
	struct sta_info *sta;

	if (len != sizeof(*add)) {
		printf("Invalid IAPP-ADD packet length %d (expected %lu)\n",
		       len, (unsigned long) sizeof(*add));
		return;
	}

	sta = ap_get_sta(iapp->hapd, add->mac_addr);

	/* IAPP-ADD.indication(MAC Address, Sequence Number) */
	hostapd_logger(iapp->hapd, add->mac_addr, HOSTAPD_MODULE_IAPP,
		       HOSTAPD_LEVEL_INFO,
		       "Received IAPP ADD-notify (seq# %d) from %s:%d%s",
		       be_to_host16(add->seq_num),
		       inet_ntoa(from->sin_addr), ntohs(from->sin_port),
		       sta ? "" : " (STA not found)");

	if (!sta)
		return;

	/* TODO: could use seq_num to try to determine whether last association
	 * to this AP is newer than the one advertised in IAPP-ADD. Although,
	 * this is not really a reliable verification. */

	hostapd_logger(iapp->hapd, add->mac_addr, HOSTAPD_MODULE_IAPP,
		       HOSTAPD_LEVEL_DEBUG,
		       "Removing STA due to IAPP ADD-notify");
	ap_sta_disconnect(iapp->hapd, sta, NULL, 0);
}

/**
 * iapp_receive_udp - Process IAPP UDP frames
 * @sock: File descriptor for the socket
 * @eloop_ctx: IAPP data (struct iapp_data *)
 * @sock_ctx: Not used
 */
static void iapp_receive_udp(int sock, void *eloop_ctx, void *sock_ctx)
{
	struct iapp_data *iapp = eloop_ctx;
	int len, hlen;
	unsigned char buf[128];
	struct sockaddr_in from;
	socklen_t fromlen;
	struct iapp_hdr *hdr;

	/* Handle incoming IAPP frames (over UDP/IP) */

	fromlen = sizeof(from);
	len = recvfrom(iapp->udp_sock, buf, sizeof(buf), 0,
		       (struct sockaddr *) &from, &fromlen);
	if (len < 0) {
		perror("recvfrom");
		return;
	}

	if (from.sin_addr.s_addr == iapp->own.s_addr)
		return; /* ignore own IAPP messages */

	hostapd_logger(iapp->hapd, NULL, HOSTAPD_MODULE_IAPP,
		       HOSTAPD_LEVEL_DEBUG,
		       "Received %d byte IAPP frame from %s%s\n",
		       len, inet_ntoa(from.sin_addr),
		       len < (int) sizeof(*hdr) ? " (too short)" : "");

	if (len < (int) sizeof(*hdr))
		return;

	hdr = (struct iapp_hdr *) buf;
	hlen = be_to_host16(hdr->length);
	hostapd_logger(iapp->hapd, NULL, HOSTAPD_MODULE_IAPP,
		       HOSTAPD_LEVEL_DEBUG,
		       "RX: version=%d command=%d id=%d len=%d\n",
		       hdr->version, hdr->command,
		       be_to_host16(hdr->identifier), hlen);
	if (hdr->version != IAPP_VERSION) {
		printf("Dropping IAPP frame with unknown version %d\n",
		       hdr->version);
		return;
	}
	if (hlen > len) {
		printf("Underflow IAPP frame (hlen=%d len=%d)\n", hlen, len);
		return;
	}
	if (hlen < len) {
		printf("Ignoring %d extra bytes from IAPP frame\n",
		       len - hlen);
		len = hlen;
	}

	switch (hdr->command) {
	case IAPP_CMD_ADD_notify:
		iapp_process_add_notify(iapp, &from, hdr, hlen - sizeof(*hdr));
		break;
	case IAPP_CMD_MOVE_notify:
		/* TODO: MOVE is using TCP; so move this to TCP handler once it
		 * is implemented.. */
		/* IAPP-MOVE.indication(MAC Address, New BSSID,
		 * Sequence Number, AP Address, Context Block) */
		/* TODO: process */
		break;
	default:
		printf("Unknown IAPP command %d\n", hdr->command);
		break;
	}
}

struct iapp_data * iapp_init(struct hostapd_data *hapd, const char *iface)
{
	struct ifreq ifr;
	struct sockaddr_ll addr;
	int ifindex;
	struct sockaddr_in *paddr, uaddr;
	struct iapp_data *iapp;
	struct ip_mreqn mreq;

	iapp = os_zalloc(sizeof(*iapp));
	if (iapp == NULL)
		return NULL;
	iapp->hapd = hapd;
	iapp->udp_sock = iapp->packet_sock = -1;

	/* TODO:
	 * open socket for sending and receiving IAPP frames over TCP
	 */

	iapp->udp_sock = socket(PF_INET, SOCK_DGRAM, 0);
	if (iapp->udp_sock < 0) {
		perror("socket[PF_INET,SOCK_DGRAM]");
		iapp_deinit(iapp);
		return NULL;
	}

	os_memset(&ifr, 0, sizeof(ifr));
	os_strlcpy(ifr.ifr_name, iface, sizeof(ifr.ifr_name));
	if (ioctl(iapp->udp_sock, SIOCGIFINDEX, &ifr) != 0) {
		perror("ioctl(SIOCGIFINDEX)");
		iapp_deinit(iapp);
		return NULL;
	}
	ifindex = ifr.ifr_ifindex;

	if (ioctl(iapp->udp_sock, SIOCGIFADDR, &ifr) != 0) {
		perror("ioctl(SIOCGIFADDR)");
		iapp_deinit(iapp);
		return NULL;
	}
	paddr = (struct sockaddr_in *) &ifr.ifr_addr;
	if (paddr->sin_family != AF_INET) {
		printf("Invalid address family %i (SIOCGIFADDR)\n",
		       paddr->sin_family);
		iapp_deinit(iapp);
		return NULL;
	}
	iapp->own.s_addr = paddr->sin_addr.s_addr;

	if (ioctl(iapp->udp_sock, SIOCGIFBRDADDR, &ifr) != 0) {
		perror("ioctl(SIOCGIFBRDADDR)");
		iapp_deinit(iapp);
		return NULL;
	}
	paddr = (struct sockaddr_in *) &ifr.ifr_addr;
	if (paddr->sin_family != AF_INET) {
		printf("Invalid address family %i (SIOCGIFBRDADDR)\n",
		       paddr->sin_family);
		iapp_deinit(iapp);
		return NULL;
	}
	inet_aton(IAPP_MULTICAST, &iapp->multicast);

	os_memset(&uaddr, 0, sizeof(uaddr));
	uaddr.sin_family = AF_INET;
	uaddr.sin_port = htons(IAPP_UDP_PORT);
	if (bind(iapp->udp_sock, (struct sockaddr *) &uaddr,
		 sizeof(uaddr)) < 0) {
		perror("bind[UDP]");
		iapp_deinit(iapp);
		return NULL;
	}

	os_memset(&mreq, 0, sizeof(mreq));
	mreq.imr_multiaddr = iapp->multicast;
	mreq.imr_address.s_addr = INADDR_ANY;
	mreq.imr_ifindex = 0;
	if (setsockopt(iapp->udp_sock, SOL_IP, IP_ADD_MEMBERSHIP, &mreq,
		       sizeof(mreq)) < 0) {
		perror("setsockopt[UDP,IP_ADD_MEMBERSHIP]");
		iapp_deinit(iapp);
		return NULL;
	}

	iapp->packet_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if (iapp->packet_sock < 0) {
		perror("socket[PF_PACKET,SOCK_RAW]");
		iapp_deinit(iapp);
		return NULL;
	}

	os_memset(&addr, 0, sizeof(addr));
	addr.sll_family = AF_PACKET;
	addr.sll_ifindex = ifindex;
	if (bind(iapp->packet_sock, (struct sockaddr *) &addr,
		 sizeof(addr)) < 0) {
		perror("bind[PACKET]");
		iapp_deinit(iapp);
		return NULL;
	}

	if (eloop_register_read_sock(iapp->udp_sock, iapp_receive_udp,
				     iapp, NULL)) {
		printf("Could not register read socket for IAPP.\n");
		iapp_deinit(iapp);
		return NULL;
	}

	printf("IEEE 802.11F (IAPP) using interface %s\n", iface);

	/* TODO: For levels 2 and 3: send RADIUS Initiate-Request, receive
	 * RADIUS Initiate-Accept or Initiate-Reject. IAPP port should actually
	 * be openned only after receiving Initiate-Accept. If Initiate-Reject
	 * is received, IAPP is not started. */

	return iapp;
}

void iapp_deinit(struct iapp_data *iapp)
{
	struct ip_mreqn mreq;

	if (iapp == NULL)
		return;

	if (iapp->udp_sock >= 0) {
		os_memset(&mreq, 0, sizeof(mreq));
		mreq.imr_multiaddr = iapp->multicast;
		mreq.imr_address.s_addr = INADDR_ANY;
		mreq.imr_ifindex = 0;
		if (setsockopt(iapp->udp_sock, SOL_IP, IP_DROP_MEMBERSHIP,
			       &mreq, sizeof(mreq)) < 0) {
			perror("setsockopt[UDP,IP_DEL_MEMBERSHIP]");
		}

		eloop_unregister_read_sock(iapp->udp_sock);
		close(iapp->udp_sock);
	}
	if (iapp->packet_sock >= 0) {
		eloop_unregister_read_sock(iapp->packet_sock);
		close(iapp->packet_sock);
	}
	os_free(iapp);
}


text:
#
# Authors: Shogo Ichinose http://twitter.com/shogo82148
# Description:
#
# Syntax {% oembed URL %}
#
# Examples:
# {% oembed http://www.youtube.com/watch?v=rrsxEGgQDkM %}
#
# Output:
#
#

require 'open-uri'
require 'digest/sha1'
require 'oembed'

module Jekyll

  class OEmbedTag < Liquid::Tag
    def initialize(tag_name, text, token)
      super
      @text = text
      @cache_disabled = false
      @cache_folder   = File.expand_path "../.oembed-cache", File.dirname(__FILE__)
      FileUtils.mkdir_p @cache_folder
    end

    def render(context)
      if @text =~ /(https?:\/\/\S+)/
        uri = $1
        get_cache_for(uri) || get_from_web(uri)
      else
        ""
      end
    end

    def get_cache_for(uri)
      return nil if @cache_disabled
      cache_file = get_cache_file_for uri
      File.read(cache_file) if File.exist? cache_file
    end

    def get_cache_file_for(uri)
      bad_chars = /[^a-zA-Z0-9\-_.]/
      uri      = uri.gsub bad_chars, ''
      File.join @cache_folder, "#{uri}.cache"
    end

    def get_from_web(uri)
      data ||= OEmbed::Providers.get(uri).html rescue nil
      data ||= OEmbed::ProviderDiscovery.discover_provider(uri).get(uri).html rescue nil
      data ||= "#{uri}"
      cache uri, data unless @cache_disabled
      data
    end

    def cache(uri, data)
      cache_file = get_cache_file_for uri
      File.open(cache_file, "w") do |io|
        io.write(data)
      end
    end

    Twitter = OEmbed::Provider.new("https://api.twitter.com/1/statuses/oembed.{format}")
    Twitter << "https://twitter.com/*/status/*"
    Twitter << "https://twitter.com/*/statuses/*"
    Twitter << "http://twitter.com/*/status/*"
    Twitter << "http://twitter.com/*/statuses/*"
    OEmbed::Providers.register(Twitter)

    OEmbed::Providers.register_all

  end

  class OEmbedNoCache < OEmbedTag
    def initialize(tag_name, text, token)
      super
      @cache_disabled = true
    end
  end

end

Liquid::Template.register_tag('oembed', Jekyll::OEmbedTag)
Liquid::Template.register_tag('oembednocache', Jekyll::OEmbedNoCache)


text:
using System;
using Org.Apache.Etch.Bindings.Csharp.Support;
using Org.Apache.Etch.Bindings.Csharp.Util;
using NUnit.Framework;
using org.apache.etch.examples.chat.types.Chat;

namespace org.apache.etch.examples.chat
{
    [TestFixture]
    public class TestRemoteChatServer
    {
        private const String _fred = "Fred";

        private static RemoteChatServer fred_server;

        private static ServerFactory listener;

        [TestFixtureSetUp]
        public  void SetupListener()
        {
            String uri = "tcp://localhost:4010";

            MainChatListener implFactory = new MainChatListener();
            listener = ChatHelper.NewListener(uri, null, implFactory);

            listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000);

            Console.WriteLine("Listener Started");
        }

        [SetUp]
        public void AssignNullToConnections()
        {
            fred_server = null;

        }

        [Test]
        public void TestLogin1()
        {
            fred_server = SetupUserAndConnection(_fred);
            fred_server.login( _fred, _fred );
        }

        [Test]
        [ExpectedException( typeof( Failure ) )]
        public void TestLogin2()
        {
            fred_server =  SetupUserAndConnection(_fred );
            fred_server.login( _fred, _fred );
            fred_server.login(_fred, _fred);
        }

        [Test]
        [ExpectedException(typeof(Failure))]
        public void TestLogin3()
        {
            fred_server = SetupUserAndConnection(null);
            fred_server.login(null, null);
        }

        [Test]
        [ExpectedException(typeof(Failure))]
        public void TestLogin4()
        {
            fred_server = SetupUserAndConnection("fred");
            fred_server.login("fred", "badPass");
        }

        [Test]
        [ExpectedException(typeof(Failure))]
        public void TestLogin()
        {
            fred_server = SetupUserAndConnection("badUser");
            fred_server.login("badUser", "badPass");

        }

        [TearDown]
        public void ShutDownOpenConnections()
        {
            if (fred_server != null)
            {
                fred_server.logout();
                fred_server._Stop();
            }
        }

        [TestFixtureTearDown]
        public void StopListener()
        {
            if (listener != null)
            {
                listener.TransportControl(TransportConsts.STOP_AND_WAIT_DOWN, 4000);
                listener = null;
            }
        }

        /// <summary>
        /// Setup the connection and server specific information for this user.
        /// </summary>
        /// <param name="username"></param>
        /// <returns>The ChatServer instance to play with</returns>
        ///
        public static RemoteChatServer SetupUserAndConnection( String username)
        {

            String uri = "tcp://localhost:4010";

            MyChatClientImpl client = new MyChatClientImpl( username);
            RemoteChatServer server = ChatHelper.NewServer( uri,null, client );

            server._StartAndWaitUp( 4000 );

            return server;
        }

        /// <summary>
        /// Create your own ChatClientImpl so as to verify messages.
        /// </summary>
        public class MyChatClientImpl : ChatHelper.ChatClientFactory
        {

            public String user;

            /// <summary>
            /// Constructs the ChatClientImpl
            /// </summary>

            public MyChatClientImpl(string user )
            {

                this.user = user;
            }

            #region ChatClientFactory Members

            public ChatClient NewChatClient(RemoteChatServer server)
            {
                return new ImplChatClient(server, user, false);
            }

            #endregion
        }

    }
}


text:
class ApiKey < ActiveRecord::Base
  validates_presence_of :access_token, :expire_at
  validates_uniqueness_of :access_token

  before_validation :generate_access_token, on: :create
  before_validation :calculate_expiration_date, on: :create

  attr_accessible :application

  # Reimplement this method in your application
  def self.applications
    [nil]
  end

  validates :application, inclusion: { in: proc { ApiKey.applications } }

  private

  def generate_access_token
    begin
      self.access_token = SecureRandom.hex
    end while ApiKey.where(access_token: access_token).exists?
  end

  def calculate_expiration_date
    self.expire_at = Time.now.since(30.days)
  end
end


text:
package org.apereo.cas.config;

import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.authentication.AuthenticationEventExecutionPlanConfigurer;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.CassandraAuthenticationHandler;
import org.apereo.cas.authentication.CassandraRepository;
import org.apereo.cas.authentication.DefaultCassandraRepository;
import org.apereo.cas.authentication.principal.DefaultPrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalNameTransformerUtils;
import org.apereo.cas.authentication.principal.PrincipalResolver;
import org.apereo.cas.authentication.support.password.PasswordEncoderUtils;
import org.apereo.cas.cassandra.CassandraSessionFactory;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.cassandra.authentication.CassandraAuthenticationProperties;
import org.apereo.cas.services.ServicesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link CassandraAuthenticationConfiguration}.
 *
 * @author Misagh Moayyed
 * @author Dmitriy Kopylenko
 * @since 5.2.0
 */
@Configuration("cassandraAuthenticationConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Slf4j
public class CassandraAuthenticationConfiguration {

    @Autowired
    @Qualifier("cassandraSessionFactory")
    private CassandraSessionFactory cassandraSessionFactory;

    @Autowired
    @Qualifier("servicesManager")
    private ServicesManager servicesManager;

    @Autowired
    @Qualifier("personDirectoryPrincipalResolver")
    private PrincipalResolver personDirectoryPrincipalResolver;

    @Autowired
    private CasConfigurationProperties casProperties;

    @Bean
    public PrincipalFactory cassandraPrincipalFactory() {
        return new DefaultPrincipalFactory();
    }

    @Bean
    @RefreshScope
    public CassandraRepository cassandraRepository() {
        final CassandraAuthenticationProperties cassandra = casProperties.getAuthn().getCassandra();
        return new DefaultCassandraRepository(cassandra, cassandraSessionFactory);
    }

    @Bean
    @RefreshScope
    public AuthenticationHandler cassandraAuthenticationHandler() {
        final CassandraAuthenticationProperties cassandra = casProperties.getAuthn().getCassandra();
        final CassandraAuthenticationHandler handler = new CassandraAuthenticationHandler(cassandra.getName(), servicesManager,
                cassandraPrincipalFactory(),
                cassandra.getOrder(), cassandra, cassandraRepository());
        handler.setPrincipalNameTransformer(PrincipalNameTransformerUtils.newPrincipalNameTransformer(cassandra.getPrincipalTransformation()));
        handler.setPasswordEncoder(PasswordEncoderUtils.newPasswordEncoder(cassandra.getPasswordEncoder()));
        return handler;
    }

    @ConditionalOnMissingBean(name = "cassandraAuthenticationEventExecutionPlanConfigurer")
    @Bean
    public AuthenticationEventExecutionPlanConfigurer cassandraAuthenticationEventExecutionPlanConfigurer() {
        return plan -> plan.registerAuthenticationHandlerWithPrincipalResolver(cassandraAuthenticationHandler(), personDirectoryPrincipalResolver);
    }
}


text:
package com.bucketfiller

import akka.actor.{Actor, ActorRef, Props}
import scala.collection._
import scala.concurrent.duration._
import scala.concurrent.Await
import akka.pattern.ask
import akka.util.Timeout

class Simulation(player: ActorRef) extends Actor {
    import Simulation._

    val graphManager = context.actorOf(Props(new GraphManager(self)))
    val moveMaker = context.actorOf(Props(new MoveMaker(graphManager)))
    val levelManager = context.actorOf(Props(new LevelManager(moveMaker)))
    var isStarted = false
    var endValue = -1
    var initState = State(Bucket(-1, -1), Bucket(-1, -1))

    def receive = {
        case Start(capacityA, capacityB, goal) => start(capacityA, capacityB, goal)
        case Frontier(source, states) => process(source, states)
        case BeginLevel(level) => player ! BeginLevel(level)
        case Exhausted =>
          player ! Result(List[State]())
          die()
    }

    def start(capacityA: Int, capacityB: Int, goal: Int) = {
        if (!isStarted) {
            initState = State(Bucket(0, capacityA), Bucket(0, capacityB))
            isStarted = true
            endValue = goal
            levelManager ! LevelManager.Init(Set(initState))
        }
    }

    def process(source: State, states: Set[State]): Unit = {

        if (!isStarted) {
            return ()
        }

        states.find({
            case State(Bucket(valueA, _), Bucket(valueB, _)) =>
                valueA == endValue || valueB == endValue
        }) match {
            case Some(endState) =>
                implicit val timeout = Timeout(30.seconds)
                val future = graphManager ? GraphManager.FindPath(initState, endState)
                val GraphManager.Path(path) = Await.result(future, 30.seconds).asInstanceOf[GraphManager.Path]
                player ! LevelManager.Next(source, states)
                player ! Result(path)
                die()
            case _ =>
             val msg = LevelManager.Next(source, states)
             player ! msg
              levelManager ! msg
        }

        return ()
    }

    def die() {
      context.stop(self)
    }
}

object Simulation {
    case class Bucket(value: Int, capacity: Int)
    case class State(a: Bucket, b: Bucket)
    case class Frontier(source: State, states: Set[State])
    case class Start(capacityA: Int, capacityB: Int, goal: Int)
    case class Result(path: List[State])
    case class BeginLevel(level: Set[State])
    case object Exhausted
}


text:
package org.powermock.tests.utils.impl;

import org.powermock.core.MockRepository;
import org.powermock.core.spi.PowerMockTestListener;
import org.powermock.core.spi.testresult.Result;
import org.powermock.core.spi.testresult.TestMethodResult;
import org.powermock.core.spi.testresult.TestSuiteResult;
import org.powermock.core.spi.testresult.impl.TestMethodResultImpl;
import org.powermock.tests.utils.Keys;
import org.powermock.tests.utils.PowerMockTestNotifier;

import java.lang.reflect.Method;

/**
 * Utility class that may be used by PowerMock test runners to notify listeners.
 * Uses the {@link MockRepository} to set and get state.
 */
public class PowerMockTestNotifierImpl implements PowerMockTestNotifier {

	private static final String ERROR_MESSAGE_TEMPLATE = "Invoking the %s method on PowerMock test listener %s failed.";

	private final PowerMockTestListener[] powerMockTestListeners;

	/**
	 * Create a new instance with the following parameters.
	 *
	 * @param powerMockTestListeners
	 *            The PowerMock listeners that will be notified.
	 */
	public PowerMockTestNotifierImpl(PowerMockTestListener[] powerMockTestListeners) {
		if (powerMockTestListeners == null) {
			this.powerMockTestListeners = new PowerMockTestListener[0];
		} else {
			this.powerMockTestListeners = powerMockTestListeners;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void notifyAfterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) {
		for (int i = 0; i < powerMockTestListeners.length; i++) {
			final PowerMockTestListener testListener = powerMockTestListeners[i];
			try {
				testListener.afterTestMethod(testInstance, method, arguments, testResult);
			} catch (Exception e) {
				throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "afterTestMethod", testListener), e);
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void notifyAfterTestSuiteEnded(Class<?> testClass, Method[] methods, TestSuiteResult testResult) {
		for (PowerMockTestListener powerMockTestListener : powerMockTestListeners) {
			try {
				powerMockTestListener.afterTestSuiteEnded(testClass, methods, testResult);
			} catch (Exception e) {
				throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "afterTestSuiteEnded", powerMockTestListener), e);
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void notifyBeforeTestMethod(Object testInstance, Method testMethod, Object[] arguments) {
		MockRepository.putAdditionalState(Keys.CURRENT_TEST_INSTANCE, testInstance);
		MockRepository.putAdditionalState(Keys.CURRENT_TEST_METHOD, testMethod);
		MockRepository.putAdditionalState(Keys.CURRENT_TEST_METHOD_ARGUMENTS, arguments);
		for (int i = 0; i < powerMockTestListeners.length; i++) {
			final PowerMockTestListener testListener = powerMockTestListeners[i];
			try {
				testListener.beforeTestMethod(testInstance, testMethod, arguments);
			} catch (Exception e) {
				throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "beforeTestMethod", testListener), e);
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void notifyBeforeTestSuiteStarted(Class<?> testClass, Method[] testMethods) {
		for (PowerMockTestListener powerMockTestListener : powerMockTestListeners) {
			try {
				powerMockTestListener.beforeTestSuiteStarted(testClass, testMethods);
			} catch (Exception e) {
				throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "beforeTestSuiteStarted", powerMockTestListener), e);
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void notifyAfterTestMethod(boolean successful) {
		final Object test = MockRepository.getAdditionalState(Keys.CURRENT_TEST_INSTANCE);
		final Method testMethod = (Method) MockRepository.getAdditionalState(Keys.CURRENT_TEST_METHOD);
		final Object[] testArguments = (Object[]) MockRepository.getAdditionalState(Keys.CURRENT_TEST_METHOD_ARGUMENTS);
		final TestMethodResult testResult = new TestMethodResultImpl((successful ? Result.SUCCESSFUL : Result.FAILED));
		notifyAfterTestMethod(test, testMethod, testArguments, testResult);
	}
}


text:
#ifndef _PAPI_PERFMON_H
#define _PAPI_PERFMON_H
/*
* File:    perfmon.h
* Author:  Philip Mucci
*          mucci@cs.utk.edu
*
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <time.h>
#include <fcntl.h>
#include <ctype.h>
#include <inttypes.h>
#include <libgen.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/ucontext.h>
#include <sys/ptrace.h>
#include "perfmon/pfmlib.h"
#include "perfmon/perfmon_dfl_smpl.h"
#include "papi_lock.h"

#include "linux-context.h"

#if defined(DEBUG)
#define DEBUGCALL(a,b) { if (ISLEVEL(a)) { b; } }
#else
#define DEBUGCALL(a,b)
#endif

typedef pfmlib_event_t pfm_register_t;
typedef int pfm_register_map_t;
typedef int pfm_reg_alloc_t;

#define MAX_COUNTERS PFMLIB_MAX_PMCS
#define MAX_COUNTER_TERMS PFMLIB_MAX_PMCS

typedef struct
{
	/* Context structure to kernel, different for attached */
	int ctx_fd;
	pfarg_ctx_t *ctx;
	/* Load structure to kernel, different for attached */
	pfarg_load_t *load;
	/* Which counters to use? Bits encode counters to use, may be duplicates */
	pfm_register_map_t bits;
	/* Buffer to pass to library to control the counters */
	pfmlib_input_param_t in;
	/* Buffer to pass from the library to control the counters */
	pfmlib_output_param_t out;
	/* Is this eventset multiplexed? Actually it holds the microseconds of the switching interval, 0 if not mpx. */
	int multiplexed;
	/* Arguments to kernel for multiplexing, first number of sets */
	int num_sets;
	/* Arguments to kernel to set up the sets */
	pfarg_setdesc_t set[PFMLIB_MAX_PMDS];
	/* Buffer to get information out of the sets when reading */
	pfarg_setinfo_t setinfo[PFMLIB_MAX_PMDS];
	/* Arguments to the kernel */
	pfarg_pmc_t pc[PFMLIB_MAX_PMCS];
	/* Arguments to the kernel */
	pfarg_pmd_t pd[PFMLIB_MAX_PMDS];
	/* Buffer to gather counters */
	long long counts[PFMLIB_MAX_PMDS];
} pfm_control_state_t;

typedef struct
{
#if defined(USE_PROC_PTTIMER)
	int stat_fd;
#endif
	/* Main context structure to kernel */
	int ctx_fd;
	pfarg_ctx_t ctx;
	/* Main load structure to kernel */
	pfarg_load_t load;
	/* Structure to inform the kernel about sampling */
	pfm_dfl_smpl_arg_t smpl;
	/* Address of mmap()'ed sample buffer */
	void *smpl_buf;
} pfm_context_t;

/* typedefs to conform to PAPI component layer code. */
/* these are void * in the PAPI framework layer code. */
typedef pfm_reg_alloc_t cmp_reg_alloc_t;
typedef pfm_register_t cmp_register_t;
typedef pfm_control_state_t cmp_control_state_t;
typedef pfm_context_t cmp_context_t;

#endif


text:
import json
import subprocess
import time
import uuid

import backoff
import pytest
import requests

@backoff.on_exception(backoff.expo, Exception, max_tries=3)
def gcloud_cli(command):
    """
    Runs the gcloud CLI with given options, parses the json formatted output
    and returns the resulting Python object.

    Usage: gcloud_cli(options)
        options: command line options

    Example:
        result = gcloud_cli("app deploy --no-promote")
        print(f"Deployed version {result['versions'][0]['id']}")

    Raises Exception with the stderr output of the last attempt on failure.
    """
    output = subprocess.run(
        f"gcloud {command} --quiet --format=json",
        capture_output=True,
        shell=True,
        check=True,
    )
    try:
        entries = json.loads(output.stdout)
        return entries
    except Exception:
        print("Failed to read log")
        print(f"gcloud stderr was {output.stderr}")

    raise Exception(output.stderr)

@pytest.fixture
def version():
    """Launch a new version of the app for testing, and yield the
    project and version number so tests can invoke it, then delete it.
    """

    result = gcloud_cli(f"app deploy --no-promote --version={uuid.uuid4().hex}")
    version_id = result["versions"][0]["id"]
    project_id = result["versions"][0]["project"]

    yield project_id, version_id

    gcloud_cli(f"app versions delete {version_id}")

def test_upload_and_view(version):
    project_id, version_id = version
    version_hostname = f"{version_id}-dot-{project_id}.appspot.com"

    # Initial value of counter should be 0
    response = requests.get(f"https://{version_hostname}/counter/get")
    assert response.status_code == 200
    assert response.text == "0"

    # Request counter be incremented
    response = requests.get(f"https://{version_hostname}/counter/increment")
    assert response.status_code == 200

    # counter should be 10 almost immediately
    time.sleep(10)
    response = requests.get(f"https://{version_hostname}/counter/get")
    assert response.status_code == 200
    assert response.text == "10"

    # After 20 seconds, counter should be 20
    time.sleep(20)
    response = requests.get(f"https://{version_hostname}/counter/get")
    assert response.status_code == 200
    assert response.text == "20"

    # After 40 seconds, counter should be 30
    time.sleep(20)
    response = requests.get(f"https://{version_hostname}/counter/get")
    assert response.status_code == 200
    assert response.text == "30"

    # counter should stay at 30 unless another request to increment it is set
    time.sleep(10)
    response = requests.get(f"https://{version_hostname}/counter/get")
    assert response.status_code == 200
    assert response.text == "30"


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC  "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
      <meta name="description" content="W3C SVG 1.1 2nd Edition Object Test Suite"/>
      <title>
	<d:testDescription href='http://www.w3.org/TR/SVG11/painting.html#Markers' xmlns='http://www.w3.org/1999/xhtml'>

          Test all the 'overflow' property values except 'inherit' on the 'marker' element.

          Each column tests a value of the 'overflow' property.
          The first row uses the 'marker' property to set the same marker on start-, mid- and end-points on the path.
          The second row uses 'marker-start', 'marker-mid' and 'marker-end' to give each point its own marker.
          The third row uses the 'marker' property like the first row, but here the marker has orient="auto" set.

    </d:testDescription>
      </title>

            SVG Image - The test

            PNG Image - The reference

            <object id="test" data="http://t/core/standards/SVG/Testsuites/W3C-1_1F2/harness/htmlObjectMini/modified/svg/test/painting-marker-05-f.svg" width="480" height="360" type="image/svg+xml"> </object>

			    Test Description

				<d:testDescription href='http://www.w3.org/TR/SVG11/painting.html#Markers' xmlns='http://www.w3.org/1999/xhtml'>

          Test all the 'overflow' property values except 'inherit' on the 'marker' element.

          Each column tests a value of the 'overflow' property.
          The first row uses the 'marker' property to set the same marker on start-, mid- and end-points on the path.
          The second row uses 'marker-start', 'marker-mid' and 'marker-end' to give each point its own marker.
          The third row uses the 'marker' property like the first row, but here the marker has orient="auto" set.

    </d:testDescription>

			      Operator Script

<d:operatorScript xmlns='http://www.w3.org/1999/xhtml'>

        Run the test. No interaction required.

    </d:operatorScript>

			    Pass Criteria

			<d:passCriteria xmlns='http://www.w3.org/1999/xhtml'>

        The test has passed if:

        The columns labeled 'visible' and 'auto' show markers without clipping them.
        All other columns show clipped markers.
        The rendered picture matches the reference image, except for possible
        variations in the labelling text (per CSS2 rules).

    </d:passCriteria>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lignydium quercinum Fr.

### Remarks
null


text:
namespace aura {
class Window;
}

namespace extensions {
class AppWindow;
}

namespace gfx {
class Image;
}

class ChromeLauncherController;

// This is a LauncherItemController for app windows. There is one instance per
// app, per launcher id. For apps with multiple windows, each item controller
// keeps track of all windows associated with the app and their activation
// order. Instances are owned by ash::ShelfItemDelegateManager.
//
// Tests are in chrome_launcher_controller_browsertest.cc
class AppWindowLauncherItemController : public LauncherItemController,
                                        public aura::WindowObserver {
 public:
  AppWindowLauncherItemController(Type type,
                                  const std::string& app_shelf_id,
                                  const std::string& app_id,
                                  ChromeLauncherController* controller);

  ~AppWindowLauncherItemController() override;

  void AddAppWindow(extensions::AppWindow* app_window,
                    ash::ShelfItemStatus status);

  void RemoveAppWindowForWindow(aura::Window* window);

  void SetActiveWindow(aura::Window* window);

  const std::string& app_shelf_id() const { return app_shelf_id_; }

  // LauncherItemController overrides:
  bool IsOpen() const override;
  bool IsVisible() const override;
  void Launch(ash::LaunchSource source, int event_flags) override;
  ash::ShelfItemDelegate::PerformedAction Activate(
      ash::LaunchSource source) override;
  ChromeLauncherAppMenuItems GetApplicationList(int event_flags) override;
  ash::ShelfItemDelegate::PerformedAction ItemSelected(
      const ui::Event& eent) override;
  base::string16 GetTitle() override;
  ui::MenuModel* CreateContextMenu(aura::Window* root_window) override;
  ash::ShelfMenuModel* CreateApplicationMenu(int event_flags) override;
  bool IsDraggable() override;
  bool ShouldShowTooltip() override;
  void Close() override;

  // aura::WindowObserver overrides:
  void OnWindowPropertyChanged(aura::Window* window,
                               const void* key,
                               intptr_t old) override;

  // Get the number of running applications/incarnations of this.
  size_t app_window_count() const { return app_windows_.size(); }

  // Activates the window at position |index|.
  void ActivateIndexedApp(size_t index);

  // Install the app. Only valid for ephemeral apps, which can be promoted to
  // regular installed apps.
  void InstallApp();

 private:
  typedef std::list<extensions::AppWindow*> AppWindowList;

  // Returns the action performed. Should be one of kNoAction,
  // kExistingWindowActivated, or kExistingWindowMinimized.
  ash::ShelfItemDelegate::PerformedAction ShowAndActivateOrMinimize(
      extensions::AppWindow* app_window);

  // Activate the given |window_to_show|, or - if already selected - advance to
  // the next window of similar type.
  // Returns the action performed. Should be one of kNoAction,
  // kExistingWindowActivated, or kExistingWindowMinimized.
  ash::ShelfItemDelegate::PerformedAction ActivateOrAdvanceToNextAppWindow(
      extensions::AppWindow* window_to_show);

  // List of associated app windows
  AppWindowList app_windows_;

  // Pointer to the most recently active app window
  extensions::AppWindow* last_active_app_window_;

  // The launcher id associated with this set of windows. There is one
  // AppLauncherItemController for each |app_shelf_id_|.
  const std::string app_shelf_id_;

  // Scoped list of observed windows (for removal on destruction)
  ScopedObserver<aura::Window, aura::WindowObserver> observed_windows_;

  DISALLOW_COPY_AND_ASSIGN(AppWindowLauncherItemController);
};

#endif  // CHROME_BROWSER_UI_ASH_LAUNCHER_APP_WINDOW_LAUNCHER_ITEM_CONTROLLER_H_


text:
/**
 *
 */
package weibo4j.examples.user;

import java.io.UnsupportedEncodingException;

import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;

/**
 * @author sina
 *
 */
public class GetUserInfo {

	/**
	 * 根据用户ID获取用户资料(授权用户)
	 * @param args
	 * @throws UnsupportedEncodingException
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		try {
			String screen_name="李开复";
			String s=java.net.URLEncoder.encode(screen_name, "utf-8");
			User user = getWeibo(false,args).showUser(s);
			System.out.println(user.toString());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	private static Weibo getWeibo(boolean isOauth,String[] args) {
		Weibo weibo = new Weibo();
		if(isOauth) {//oauth验证方式 args[0]:访问的token;args[1]:访问的密匙
			weibo.setToken(args[0], args[1]);
		}else {//用户登录方式
    		weibo.setUserId(args[0]);//用户名/ID
    		weibo.setPassword(args[1]);//密码
		}
		return weibo;
	}

}


text:
import calendar, datetime, Tkinter

class Calendar(Tkinter.Frame): # class calendarTk
    """ Calendar, the current date is exposed today, or transferred to date"""
    def __init__(self,master=None,date=None,dateformat="%d/%m/%Y",command=lambda i:None):
        Tkinter.Frame.__init__(self, master)
        self.dt=datetime.datetime.now() if date is None else datetime.datetime.strptime(date, dateformat)
        self.showmonth()
        self.command=command
        self.dateformat=dateformat
    def showmonth(self): # Show the calendar for a month
        sc = calendar.month(self.dt.year, self.dt.month).split('\n')
        for t,c in [('<<',0),('<',1),('>',5),('>>',6)]: # The buttons to the left to the right year and month
            Tkinter.Button(self,text=t,relief='flat',command=lambda i=t:self.callback(i)).grid(row=0,column=c)
        Tkinter.Label(self,text=sc[0]).grid(row=0,column=2,columnspan=3) # year and month
        for line,lineT in [(i,sc[i+1]) for i in range(1,len(sc)-1)]: # The calendar
            for col,colT in [(i,lineT[i*3:(i+1)*3-1]) for i in range(7)]: # For each element
                obj=Tkinter.Button if colT.strip().isdigit() else Tkinter.Label # If this number is a button, or Label
                args={'command':lambda i=colT:self.callback(i)} if obj==Tkinter.Button else {} # If this button, then fasten it to the command
                bg='green' if colT.strip()==str(self.dt.day) else 'Gray' # If the date coincides with the day of date - make him a green background
                fg='red' if col>=5 else 'Black' # For the past two days, the color red
                obj(self,text="%s"% colT,relief=Tkinter.FLAT,bg=bg,fg=fg,**args).grid(row=line, column=col, ipadx=2, sticky=Tkinter.NW + Tkinter.SE) # Draw Button or Label
    def callback(self,but): # Event on the button
        if but.strip().isdigit():  self.dt=self.dt.replace(day=int(but)) # If you clicked on a date - the date change
        elif but in ['<','>','<<','>>']:
            day=self.dt.day
            if but in['<','>']: self.dt=self.dt+datetime.timedelta(days=30 if but=='>' else -30) # Move a month in advance / rewind
            if but in['<<','>>']: self.dt=self.dt+datetime.timedelta(days=365 if but=='>>' else -365) #  Year forward / backward
            try: self.dt=self.dt.replace(day=day) # We are trying to put the date on which stood
            except: pass                          # It is not always possible
        self.showmonth() # Then always show calendar again
        if but.strip().isdigit(): self.command(self.dt.strftime(self.dateformat)) # If it was a date, then call the command

if __name__ == '__main__':
    def com(f): print f
    root = Tkinter.Tk()
    root.title("Monthly Calendar")
    c=Calendar(root,date="21/11/2006",dateformat="%d/%m/%Y",command=com)
    c.pack()

    root.mainloop()


text:
namespace wtf {

// On this platform, use the standard-library versions of atomics and mutexes.
namespace platform {
using mutex = std::mutex;

template <typename T>
using lock_guard = std::lock_guard<T>;

template <typename T>
using atomic = std::atomic<T>;

// Since memory_order is an old-school enum, it needs to be imported
// individually.
using std::memory_order;
using std::memory_order_relaxed;
using std::memory_order_consume;
using std::memory_order_acquire;
using std::memory_order_release;
using std::memory_order_acq_rel;
using std::memory_order_seq_cst;

using once_flag = struct {
    pthread_once_t flag {PTHREAD_ONCE_INIT};
};

template <class T>
inline void call_once(once_flag& once, T func) {
    pthread_once(&once.flag, func);
}

}  // namespace platform

namespace internal {
extern pthread_key_t event_buffer_key;
extern pthread_once_t initialize_threading_once;

void InitializeThreadingOnce();

}  // namespace internal

inline EventBuffer* PlatformGetThreadLocalEventBuffer() {
  pthread_once(&internal::initialize_threading_once,
               internal::InitializeThreadingOnce);
  return static_cast<EventBuffer*>(
      pthread_getspecific(internal::event_buffer_key));
}

}  // namespace wtf

#endif  // TRACING_FRAMEWORK_BINDINGS_CPP_INCLUDE_WTF_PLATFORM_AUX_PTHREADS_THREADED_INL_H_


text:
<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * Description of User_fav_deals_model
 * @author user
 */

class User_fav_deals_model extends MY_Model {

    //put your code here
    public $table_name,$joiningArray,$joinTables;

    public function __construct() {
        parent::__construct();
        $this->table_name = 'user_fav_deals';
       // $this->joiningArray[0]['table'] = 'cd_user';
       // $this->joiningArray[0]['condition'] = 'user_deals.i_user_id = cd_user.i_id';
        $this->joiningArray[1]['table'] = 'cd_coupon';
        $this->joiningArray[1]['condition'] = 'user_fav_deals.i_deal_id = cd_coupon.i_id';

        $this->joiningArray[2]['table'] = 'cd_store';
        $this->joiningArray[2]['condition'] = 'cd_store.i_id = cd_coupon.i_store_id';

		$this->joinTables[1]['table'] = 'cd_deals';
        $this->joinTables[1]['condition'] = 'user_fav_deals.i_deal_id = cd_deals.i_id';

        $this->joinTables[2]['table'] = 'cd_store';
        $this->joinTables[2]['condition'] = 'cd_store.i_id = cd_deals.i_store_id';

    }

    public function get_favourite_product_list($s_where=null,$i_start=null,$i_limit=null)
    {
        $ret_=array();
        $s_qry="SELECT n.i_type,n.i_user_id AS userID,n.txt_extra,n.i_deal_id,p.*,
            s.s_store_title,s.s_store_logo,s.s_store_url FROM ".$this->table_name." AS n ".
            "LEFT JOIN cd_coupon AS p ON p.i_id = n.i_deal_id ".
            "LEFT JOIN cd_store AS s ON s.i_id = p.i_store_id ".
        ($s_where!=""?$s_where:"" )." ORDER BY n.i_id DESC ".(is_numeric($i_start) && is_numeric($i_limit)?" Limit ".intval($i_start).",".intval($i_limit):"" );

        $rs=$this->db->query($s_qry);
        //echo $this->db->last_query();
        //echo '</br>';
        $ret_ = $rs->result_array();
        return $ret_;
    }

    public function count_favourite_product_list($s_where=null)
    {
        $ret_=0;
        $s_qry="SELECT COUNT(n.i_id) as i_total "
            ."FROM ".$this->table_name." n "
            ."LEFT JOIN cd_coupon AS p ON p.i_id = n.i_deal_id "
            ."LEFT JOIN cd_store AS s ON s.i_id = p.i_store_id "
            .($s_where!=""?$s_where:"" );
        $rs=$this->db->query($s_qry);
        $i_cnt=0;
        if($rs->num_rows()>0)
        {
          foreach($rs->result() as $row)
          {
              $ret_=intval($row->i_total);
          }
          $rs->free_result();
        }
        unset($s_qry,$rs,$row,$i_cnt,$s_where,$i_start,$i_limit);
        return $ret_;
    }

    /**
     * get the count of all favorite deals data in cd_fav_deals
     */

    public function count_total_fav_deals($condition = NULL, $column = NULL, $limit = NULL, $start = 0,$orderby = NULL,$ordertype='desc', $likeCondition = NULL) {

        $this->db->start_cache();
        $this->db->select('COUNT(*) AS total');
        if ($condition)
            $this->db->where($condition);

        if ($likeCondition) {
            if (is_array($likeCondition))
                $this->db->like($likeCondition);

            if (is_string($likeCondition)) {
                $likeData = explode('|', $likeCondition);
                $this->db->like($likeData[0], $likeData[1], $likeData[2]);
            }

        }

        if ($this->joinTables)
		{
            foreach ($this->joinTables as $joinMeta)
			{
                $this->db->join($joinMeta['table'], $joinMeta['condition'], isset($joinMeta['type']) ? $joinMeta['type'] : 'left');
            }
		}

        $this->db->stop_cache();
        $query = $this->db->get($this->table_name, $limit, $start);
        $this->db->flush_cache();
        $data = $query->result_array();
        $this->db->flush_cache();
        return $data[0]['total'];

    }

	 public function get_fav_deals_list($condition = NULL, $column = NULL, $limit = NULL, $start = 0,$orderby = NULL,$ordertype='desc', $likeCondition = NULL) {

        $this->db->start_cache();
        if ($column)
            $this->db->select($column);

        if ($condition)
            $this->db->where($condition);

        if ($likeCondition) {
            if (is_array($likeCondition))
                $this->db->like($likeCondition);
            if (is_string($likeCondition)) {
                $likeData = explode('|', $likeCondition);
                $this->db->like($likeData[0], $likeData[1], $likeData[2]);
            }
        }

        if ($this->joinTables)
            foreach ($this->joinTables as $joinMeta) {
                $this->db->join($joinMeta['table'], $joinMeta['condition'], isset($joinMeta['type']) ? $joinMeta['type'] : 'left');
            }
             if($orderby)
            $this->db->order_by($orderby, $ordertype);

        $this->db->stop_cache();
        $query = $this->db->get($this->table_name, $limit, $start);
        $this->db->flush_cache();
        return $query->result_array();

    }

}
?>