text:
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;

namespace System.Diagnostics
{
    /// Base class used for all tests that need to spawn a remote process.
    public abstract partial class RemoteExecutorTestBase : FileCleanupTestBase
    {
        /// A timeout (milliseconds) after which a wait on a remote operation should be considered a failure.
        public const int FailWaitTimeoutMilliseconds = 60 * 1000;
        /// The exit code returned when the test process exits successfully.
        public const int SuccessExitCode = 42;

        /// The name of the test console app.
        protected static readonly string TestConsoleApp = Path.GetFullPath("RemoteExecutorConsoleApp.exe");

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Action method,
            RemoteInvokeOptions options = null)
        {
            // There's no exit code to check
            options = options ?? new RemoteInvokeOptions();
            options.CheckExitCode = false;

            return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Action<string> method,
            string arg,
            RemoteInvokeOptions options = null)
        {
            // There's no exit code to check
            options = options ?? new RemoteInvokeOptions();
            options.CheckExitCode = false;

            return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Action<string, string> method,
            string arg1,
            string arg2,
            RemoteInvokeOptions options = null)
        {
            // There's no exit code to check
            options = options ?? new RemoteInvokeOptions();
            options.CheckExitCode = false;

            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Action<string, string, string> method,
            string arg1,
            string arg2,
            string arg3,
            RemoteInvokeOptions options = null)
        {
            // There's no exit code to check
            options = options ?? new RemoteInvokeOptions();
            options.CheckExitCode = false;

            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Action<string, string, string, string> method,
            string arg1,
            string arg2,
            string arg3,
            string arg4,
            RemoteInvokeOptions options = null)
        {
            // There's no exit code to check
            options = options ?? new RemoteInvokeOptions();
            options.CheckExitCode = false;

            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<int> method,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<Task<int>> method,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="arg">The argument to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<string, Task<int>> method,
            string arg,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="arg1">The first argument to pass to the method.</param>
        /// <param name="arg2">The second argument to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<string, string, Task<int>> method,
            string arg1, string arg2,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="arg">The argument to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<string, int> method,
            string arg,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="arg1">The first argument to pass to the method.</param>
        /// <param name="arg2">The second argument to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<string, string, int> method,
            string arg1, string arg2,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="arg1">The first argument to pass to the method.</param>
        /// <param name="arg2">The second argument to pass to the method.</param>
        /// <param name="arg3">The third argument to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<string, string, string, int> method,
            string arg1, string arg2, string arg3,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="arg1">The first argument to pass to the method.</param>
        /// <param name="arg2">The second argument to pass to the method.</param>
        /// <param name="arg3">The third argument to pass to the method.</param>
        /// <param name="arg4">The fourth argument to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<string, string, string, string, int> method,
            string arg1, string arg2, string arg3, string arg4,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="arg1">The first argument to pass to the method.</param>
        /// <param name="arg2">The second argument to pass to the method.</param>
        /// <param name="arg3">The third argument to pass to the method.</param>
        /// <param name="arg4">The fourth argument to pass to the method.</param>
        /// <param name="arg5">The fifth argument to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvoke(
            Func<string, string, string, string, string, int> method,
            string arg1, string arg2, string arg3, string arg4, string arg5,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4, arg5 }, options);
        }

        /// Invokes the method from this assembly in another process using the specified arguments without performing any modifications to the arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="args">The arguments to pass to the method.</param>
        /// <param name="options">Options to use for the invocation.</param>
        public static RemoteInvokeHandle RemoteInvokeRaw(Delegate method, string unparsedArg,
            RemoteInvokeOptions options = null)
        {
            return RemoteInvoke(GetMethodInfo(method), new[] { unparsedArg }, options, pasteArguments: false);
        }

        /// Invokes the method from this assembly in another process using the specified arguments.
        /// <param name="method">The method to invoke.</param>
        /// <param name="args">The arguments to pass to the method.</param>
        /// <param name="start">true if this function should Start the Process; false if that responsibility is left up to the caller.</param>
        /// <param name="psi">The ProcessStartInfo to use, or null for a default.</param>
        /// <param name="pasteArguments">true if this function should paste the arguments (e.g. surrounding with quotes); false if that responsibility is left up to the caller.</param>
        private static RemoteInvokeHandle RemoteInvoke(MethodInfo method, string[] args, RemoteInvokeOptions options, bool pasteArguments = true)
        {
            options = options ?? new RemoteInvokeOptions();

            // Verify the specified method returns an int (the exit code) or nothing,
            // and that if it accepts any arguments, they're all strings.
            Assert.True(method.ReturnType == typeof(void) || method.ReturnType == typeof(int) || method.ReturnType == typeof(Task<int>));
            Assert.All(method.GetParameters(), pi => Assert.Equal(typeof(string), pi.ParameterType));

            // And make sure it's in this assembly.  This isn't critical, but it helps with deployment to know
            // that the method to invoke is available because we're already running in this assembly.
            Type t = method.DeclaringType;
            Assembly a = t.GetTypeInfo().Assembly;

            // Start the other process and return a wrapper for it to handle its lifetime and exit checking.
            ProcessStartInfo psi = options.StartInfo;
            psi.UseShellExecute = false;

            if (!options.EnableProfiling)
            {
                // Profilers / code coverage tools doing coverage of the test process set environment
                // variables to tell the targeted process what profiler to load.  We don't want the child process
                // to be profiled / have code coverage, so we remove these environment variables for that process
                // before it's started.
                psi.Environment.Remove("Cor_Profiler");
                psi.Environment.Remove("Cor_Enable_Profiling");
                psi.Environment.Remove("CoreClr_Profiler");
                psi.Environment.Remove("CoreClr_Enable_Profiling");
            }

            // If we need the host (if it exists), use it, otherwise target the console app directly.
            string metadataArgs = PasteArguments.Paste(new string[] { a.FullName, t.FullName, method.Name, options.ExceptionFile }, pasteFirstArgumentUsingArgV0Rules: false);
            string passedArgs = pasteArguments ? PasteArguments.Paste(args, pasteFirstArgumentUsingArgV0Rules: false) : string.Join(" ", args);
            string testConsoleAppArgs = ExtraParameter + " " + metadataArgs + " " + passedArgs;

            // Uap console app is globally registered.
            if (!File.Exists(HostRunner) && !PlatformDetection.IsUap)
                throw new IOException($"{HostRunner} test app isn't present in the test runtime directory.");

            if (options.RunAsSudo)
            {
                psi.FileName = "sudo";
                psi.Arguments = HostRunner + " " + testConsoleAppArgs;
            }
            else
            {
                psi.FileName = HostRunner;
                psi.Arguments = testConsoleAppArgs;
            }

            // Return the handle to the process, which may or not be started
            return new RemoteInvokeHandle(options.Start ?
                Process.Start(psi) :
                new Process() { StartInfo = psi }, options,
                a.FullName, t.FullName, method.Name
                );
        }

        private static MethodInfo GetMethodInfo(Delegate d)
        {
            // RemoteInvoke doesn't support marshaling state on classes associated with
            // the delegate supplied (often a display class of a lambda).  If such fields
            // are used, odd errors result, e.g. NullReferenceExceptions during the remote
            // execution.  Try to ward off the common cases by proactively failing early
            // if it looks like such fields are needed.
            if (d.Target != null)
            {
                // The only fields on the type should be compiler-defined (any fields of the compiler's own
                // making generally include '<' and '>', as those are invalid in C# source).  Note that this logic
                // may need to be revised in the future as the compiler changes, as this relies on the specifics of
                // actually how the compiler handles lifted fields for lambdas.
                Type targetType = d.Target.GetType();
                Assert.All(
                    targetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
                    fi => Assert.True(fi.Name.IndexOf('<') != -1, $"Field marshaling is not supported by {nameof(RemoteInvoke)}: {fi.Name}"));
            }

            return d.GetMethodInfo();
        }

        /// A cleanup handle to the Process created for the remote invocation.
        public sealed class RemoteInvokeHandle : IDisposable
        {
            public RemoteInvokeHandle(Process process, RemoteInvokeOptions options, string assemblyName = null, string className = null, string methodName = null)
            {
                Process = process;
                Options = options;
                AssemblyName = assemblyName;
                ClassName = className;
                MethodName = methodName;
            }

            public int ExitCode
            {
                get
                {
                    Process.WaitForExit();
                    return Process.ExitCode;
                }
            }
            public Process Process { get; set; }
            public RemoteInvokeOptions Options { get; private set; }
            public string AssemblyName { get; private set; }
            public string ClassName { get; private set; }
            public string MethodName { get; private set; }

            public void Dispose()
            {
                GC.SuppressFinalize(this); // before Dispose(true) in case the Dispose call throws
                Dispose(disposing: true);
            }

            private void Dispose(bool disposing)
            {
                Assert.True(disposing, $"A test {AssemblyName}!{ClassName}.{MethodName} forgot to Dispose() the result of RemoteInvoke()");

                if (Process != null)
                {
                    // A bit unorthodox to do throwing operations in a Dispose, but by doing it here we avoid
                    // needing to do this in every derived test and keep each test much simpler.
                    try
                    {
                        Assert.True(Process.WaitForExit(Options.TimeOut),
                            $"Timed out after {Options.TimeOut}ms waiting for remote process {Process.Id}");

                        if (File.Exists(Options.ExceptionFile))
                        {
                            throw new RemoteExecutionException(File.ReadAllText(Options.ExceptionFile));
                        }

                        if (Options.CheckExitCode)
                        {
                            int expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Options.ExpectedExitCode : unchecked((sbyte)Options.ExpectedExitCode);
                            int actual = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Process.ExitCode : unchecked((sbyte)Process.ExitCode);

                            Assert.True(expected == actual, $"Exit code was {Process.ExitCode} but it should have been {Options.ExpectedExitCode}");
                        }
                    }
                    finally
                    {
                        if (File.Exists(Options.ExceptionFile))
                        {
                            File.Delete(Options.ExceptionFile);
                        }

                        // Cleanup
                        try { Process.Kill(); }
                        catch { } // ignore all cleanup errors

                        Process.Dispose();
                        Process = null;
                    }
                }
            }

            ~RemoteInvokeHandle()
            {
                // Finalizer flags tests that omitted the explicit Dispose() call; they must have it, or they aren't
                // waiting on the remote execution
                Dispose(disposing: false);
            }

            private sealed class RemoteExecutionException : XunitException
            {
                internal RemoteExecutionException(string stackTrace) : base("Remote process failed with an unhandled exception.", stackTrace) { }
            }
        }
    }

    /// Options used with RemoteInvoke.
    public sealed class RemoteInvokeOptions
    {
        private bool _runAsSudo;

        public bool Start { get; set; } = true;
        public ProcessStartInfo StartInfo { get; set; } = new ProcessStartInfo();
        public bool EnableProfiling { get; set; } = true;
        public bool CheckExitCode { get; set; } = true;

        public int TimeOut {get; set; } = RemoteExecutorTestBase.FailWaitTimeoutMilliseconds;
        public int ExpectedExitCode { get; set; } = RemoteExecutorTestBase.SuccessExitCode;
        public string ExceptionFile { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

        public bool RunAsSudo
        {
            get
            {
                return _runAsSudo;
            }
            set
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    throw new PlatformNotSupportedException();
                }

                _runAsSudo = value;
            }
        }
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRpSystemsStatsTable extends Migration
{
  /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    Schema::create('rp_systems_stats', function (Blueprint $table) {
      $table->increments('id');
      $table->text('rp_systems_stat_json')->nullable();
      $table->integer('rp_systems_idrp_systems')->unsigned();
      $table->integer('user_id')->unsigned()->default(1);

      $table->foreign('rp_systems_idrp_systems')->references('id')->on('rp_systems');
      $table->foreign('user_id')->references('id')->on('users');
      $table->timestamps();
    });
  }

  /**
  * Reverse the migrations.
  *
  * @return void
  */
  public function down()
  {
    Schema::drop('rp_systems_stats');
  }
}

redpajama_set_name: RedPajamaGithub


text:
package fm.garsue.ぁっぉ;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext;

/**
 * Created by kuenishi on 4/27/16.
 */
public class ぁっぉ鯖初期化 extends ChannelInitializer<SocketChannel> {
    private final SslContext sslCtx;

    public ぁっぉ鯖初期化(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        if (sslCtx != null) {
            p.addLast(sslCtx.newHandler(ch.alloc()));
        }
        p.addLast(new HttpRequestDecoder());
        // Uncomment the following line if you don't want to handle HttpChunks.
        //p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpResponseEncoder());
        // Remove the following line if you don't want automatic content compression.
        //p.addLast(new HttpContentCompressor());
        p.addLast(new ぁっぉサーバーハンドラ());
    }
}


text:
//
//  PNChannelInformationHelper.m
//  pubnub
//
//  Created by Sergey Mamontov on 3/22/14.
//  Copyright (c) 2014 PubNub Inc. All rights reserved.
//

#import "PNChannelInformationHelper.h"
#import "PNChannelInformationHelperDelegate.h"
#import "NSDictionary+PNDemoAddition.h"

#pragma mark Private interface declaration

@interface PNChannelInformationHelper () <UITextViewDelegate, UITextFieldDelegate>

#pragma mark - Property

/**
 Stores reference on delegate which will handle all events which is related to channel information change and input.
 */
@property (nonatomic, pn_desired_weak) IBOutlet id<PNChannelInformationHelperDelegate> delegate;

/**
 Stores reference on field which will hold channel name and allow to change it (in case if channel not subscribed on it).
 */
@property (nonatomic, pn_desired_weak) IBOutlet UITextField *objectNameField;

/**
 @brief Reference on field which will hold channel namespace name and allow to change it (in case if not subscribed on it).

 @since 3.7.0
 */
@property (nonatomic, pn_desired_weak) IBOutlet UITextField *objectNamespaceField;

/**
 Stores reference on original state (assigned at the moment when state set for first time).
 */
@property (nonatomic, strong) NSDictionary *originalState;

/**
 Stores whether malformed client state has been provided or not.
 */
@property (nonatomic, assign, getter = isValidObjectStateProvided) BOOL validObjectStateProvided;

#pragma mark - Instance methods

#pragma mark - Handler methods

- (IBAction)handlePresenceObservationStateChange:(id)sender;

#pragma mark -

@end

#pragma mark - Public interface implementation

@implementation PNChannelInformationHelper

#pragma mark - Instance methods

- (void)awakeFromNib {

    // Forward method call to the super class
    [super awakeFromNib];

    self.validObjectStateProvided = YES;
}

- (void)setState:(NSDictionary *)state {

    _state = state;
    if (self.originalState == nil && state != nil) {

        self.originalState = state;
    }
}

- (id<PNChannelProtocol>)object {

    id <PNChannelProtocol> object = nil;
    if (_object) {

        object = _object;
    }
    else {

        if ([self canCreateObject]) {

            BOOL hasVaildName = self.objectName && ![self.objectName pn_isEmpty];
            BOOL hasVaildNamespace = self.objectNamespace && ![self.objectNamespace pn_isEmpty];
            if (self.objectNamespaceField) {

                if (hasVaildName || hasVaildNamespace) {

                    object = [PNChannelGroup channelGroupWithName:self.objectName inNamespace:self.objectNamespace
                                            shouldObservePresence:self.observePresence];
                }
            }
            else if(hasVaildName) {

                object = [PNChannel channelWithName:self.objectName shouldObservePresence:self.shouldObservePresence];
            }
        }
    }

    return object;
}

- (BOOL)canCreateObject {

    BOOL canCreateObject = (self.objectName ? ![self.objectName pn_isEmpty] : NO);
    if (self.objectNamespaceField) {

        canCreateObject = (!canCreateObject ? (self.objectNamespace ? ![self.objectNamespace pn_isEmpty] : NO) : canCreateObject);
    }
    if (canCreateObject && self.state != nil) {

        canCreateObject = [self.state isKindOfClass:[NSDictionary class]];
    }

    return canCreateObject;
}

- (BOOL)shouldChangePresenceObservationState {

    BOOL shouldChangePresenceObservationState = NO;
    id <PNChannelProtocol> object = _object;
    if (object && [PubNub isSubscribedOn:object]) {

        shouldChangePresenceObservationState = self.shouldObservePresence != [PubNub isPresenceObservationEnabledFor:object];
    }

    return shouldChangePresenceObservationState;
}

- (BOOL)shouldChangeObjectState {

    BOOL shouldChangeChannelState = NO;
    id <PNChannelProtocol> object = _object;
    if (object && [PubNub isSubscribedOn:object]) {

        shouldChangeChannelState = [self.state isEqualToDictionary:self.originalState];
    }

    return shouldChangeChannelState;
}

- (BOOL)isObjectStateValid {

    BOOL isObjectStateValid = YES;
    if ([self canCreateObject]) {

        // Checking whether user provided suitable object state data or not.
        if (self.isValidObjectStateProvided) {

            // Checking whether user provided some data or not
            if (self.state) {

                isObjectStateValid = [@{@"" : self.state} pn_isValidState];
            }
        }
        else {

            isObjectStateValid = NO;
        }
    }

    return isObjectStateValid;
}

- (BOOL)isObjectInformationChanged {

    BOOL isChannelInformationChanged = [self shouldChangePresenceObservationState];
    if (!isChannelInformationChanged) {

        isChannelInformationChanged = [self.state isEqualToDictionary:self.originalState];
    }

    return isChannelInformationChanged;
}

- (void)resetWarnings {

    self.validObjectStateProvided = YES;
}

#pragma mark - Handler methods

- (IBAction)handlePresenceObservationStateChange:(id)sender {

    self.observePresence = ((UISwitch *)sender).isOn;
    [self.delegate channelInformationDidChange];
}

#pragma mark - UITextField delegate methods

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if ([textField isEqual:self.objectNameField]) {

        self.objectName = [textField.text stringByReplacingCharactersInRange:range withString:string];
    }
    else {

        self.objectNamespace = [textField.text stringByReplacingCharactersInRange:range withString:string];
    }

    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];
    [self.delegate channelNameDidChange];

    return YES;
}

#pragma mark - UITextView delegate methods

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    BOOL shouldHandleByDefault = YES;
    if ([text length] == 1) {

        if ([text isEqualToString:@"{"] || [text isEqualToString:@"\""]) {

            NSRange caretPosition = NSMakeRange(range.location, 0);
            NSMutableString *finalString = [NSMutableString stringWithString:text];

            shouldHandleByDefault = NO;
            caretPosition.location = caretPosition.location + 1;
            [finalString appendString:([text isEqualToString:@"{"] ? @"}" : @"\"")];
            textView.text = [textView.text stringByReplacingCharactersInRange:range withString:finalString];
            textView.selectedRange = caretPosition;
        }
    }

    return shouldHandleByDefault;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {

    [textView resignFirstResponder];

    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView {

    if (textView.text.length > 0) {

        NSError *serializationError;
        NSDictionary *state = [NSJSONSerialization JSONObjectWithData:[textView.text dataUsingEncoding:NSUTF8StringEncoding]
                                                              options:(NSJSONReadingOptions)0 error:&serializationError];
        if (!serializationError && state) {

            self.validObjectStateProvided = YES;
            self.state = [state count] ? state : nil;
        }
        else {

            self.validObjectStateProvided = NO;
        }
    }
    else {

        self.state = nil;
        self.validObjectStateProvided = YES;
    }

    [self.delegate channelInformationDidChange];
}

#pragma mark -

@end


text:
package com.bitmotif.coursetracking.course.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class CourseDatabaseTestUtils {

	public static void insertCourse(Connection connection, Integer id, String courseName) throws SQLException {
		PreparedStatement statement = connection.prepareStatement("INSERT INTO courses SET id = ?, name = ?");
		statement.setInt(1, id);
		statement.setString(2, courseName);
		statement.execute();
	}

	public static void deleteCourse(Connection connection, Integer id) throws SQLException {
		PreparedStatement statement = connection.prepareStatement("DELETE FROM courses WHERE id = ?");
		statement.setInt(1, id);
		statement.executeUpdate();
	}
}


text:
<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\Security\User;

use Lexik\Bundle\JWTAuthenticationBundle\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
 * @method UserInterface loadUserByIdentifierAndPayload(string $identifier, array $payload) Loads a user from an identifier and JWT token payload.
 */
interface PayloadAwareUserProviderInterface extends UserProviderInterface
{
    /**
     * Load a user by its username, including the JWT token payload.
     *
     * @throws UsernameNotFoundException|UserNotFoundException if the user is not found
     *
     * @deprecated since 2.12, implement loadUserByIdentifierAndPayload() instead.
     */
    public function loadUserByUsernameAndPayload(string $username, array $payload)/*: UserInterface*/;
}


text:
from __future__ import with_statement

import os
import sys
import logging
log = logging.getLogger(__name__)

try:
    import gevent
except ImportError:
    raise RuntimeError("You need gevent installed to use this worker.")

from gevent.pool import Pool
from gevent.server import StreamServer

from pistil import util
from pistil.tcp.sync_worker import TcpSyncWorker

# workaround on osx, disable kqueue
if sys.platform == "darwin":
    os.environ['EVENT_NOKQUEUE'] = "1"

class PStreamServer(StreamServer):
    def __init__(self, listener, handle, spawn='default', worker=None):
        StreamServer.__init__(self, listener, spawn=spawn)
        self.handle_func = handle
        self.worker = worker

    def stop(self, timeout=None):
        super(PStreamServer, self).stop(timeout=timeout)

    def handle(self, sock, addr):
        self.handle_func(sock, addr)

class TcpGeventWorker(TcpSyncWorker):

    def on_init(self, conf):
        self.worker_connections = conf.get("worker_connections",
                10000)
        self.pool = Pool(self.worker_connections)

    def run(self):
        self.socket.setblocking(1)

        # start gevent stream server
        server = PStreamServer(self.socket, self.handle, spawn=self.pool,
                worker=self)
        server.start()

        try:
            while self.alive:
                self.notify()
                if self.ppid != os.getppid():
                    log.info("Parent changed, shutting down: %s", self)
                    break

                gevent.sleep(1.0)

        except KeyboardInterrupt:
            pass

        try:
            # Try to stop connections until timeout
            self.notify()
            server.stop(timeout=self.timeout)
        except:
            pass

    if hasattr(gevent.core, 'dns_shutdown'):

        def init_process(self):
            #gevent 0.13 and older doesn't reinitialize dns for us after forking
            #here's the workaround
            gevent.core.dns_shutdown(fail_requests=1)
            gevent.core.dns_init()
            super(TcpGeventWorker, self).init_process()


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Data transaksi <?php echo $this->session->userdata('username'); ?></title>

        <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

        <link rel="stylesheet" href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css'); ?>">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

        <link rel="stylesheet" href="<?php echo base_url('assets/dist/css/AdminLTE.min.css'); ?>">

                            <img src="<?php echo base_url('assets/logo/logo.png'); ?>" style="width: 25px; height: 25px;"> Data Pengeluaran <?php echo $this->session->userdata('username'); ?>
                            Date: <?php echo date('Y-m-d'); ?>

                <?php foreach ($transaksi as $data_head): ?>

                <?php endforeach ?>

                        Data  Pengeluaran
 <?php echo $this->session->userdata('username'); ?>
                        <address>
                            Id user

                            USER000<?php echo $this->session->userdata('idUser'); ?>

                        </address>

                                    Nama Project
                                    Anggaran Project
                                    Setting Anggaran
                                    Total Pengeluaran

                    <?php foreach ($transaksi as $row): ?>

                            <?php echo $row['namaProject']; ?>
                            <?php echo $row['anggaran']; ?>
                            <?php echo $row['settingAnggaran']; ?>
                            <?php echo $row['total_pengeluaran']; ?>

                    <?php endforeach ?>


text:
layout: default
draft: true
---
New book
=========
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor libero
sed faucibus blandit. Sed tempor porttitor convallis. Cras condimentum vestibulum
tellus, id vulputate est porttitor at. Sed ultricies, dui et pharetra eleifend,
sem tellus bibendum magna, at commodo diam mauris sit amet turpis. Etiam non
quam vitae tellus porta fringilla non ut orci. Aliquam vestibulum eu velit in
viverra. Duis iaculis, velit in vehicula lobortis, ante nisi dapibus enim, a
lacinia libero dolor in odio. Quisque id interdum massa, in congue augue. Etiam
rhoncus erat sit amet nunc rutrum, in rutrum ligula sollicitudin. Mauris tortor
urna, iaculis condimentum nisi sit amet, fermentum rhoncus nibh. Donec quis
tristique urna. Aliquam rhoncus velit eros. Vivamus aliquam iaculis massa, in
auctor arcu. Class aptent taciti sociosqu ad litora torquent per conubia nostra,
per inceptos himenaeos. Cras cursus, sapien ac rutrum viverra, ipsum nisl
malesuada risus, sed faucibus mauris elit vel lacus. Nulla pulvinar nisi sed dui
venenatis, eget ullamcorper nibh porta.


text:
cask 'reeddit' do
  version '1.9.6'
  sha256 'b3e6af1576994b199642d832142cff3fb49713006ab9e0f87e1cbf9ded32cca9'

  # github.com/berbaquero/Reeddit-app was verified as official when first introduced to the cask
  url "https://github.com/berbaquero/Reeddit-app/releases/download/v#{version}/Reeddit.app.zip"
  appcast 'https://github.com/berbaquero/Reeddit-app/releases.atom'
  name 'Reeddit'
  homepage 'https://mac.reedditapp.com/'

  app 'Reeddit.app'
end


text:
namespace {
const int kTrayIconHeight = 29;
const int kTrayIconWidth = 29;
const int kTrayItemAnimationDurationMS = 200;

// Animations can be disabled for testing.
bool animations_enabled = true;
}

namespace ash {

TrayItemView::TrayItemView(SystemTrayItem* owner)
    : owner_(owner),
      label_(NULL),
      image_view_(NULL) {
  SetPaintToLayer(true);
  layer()->SetFillsBoundsOpaquely(false);
  SetLayoutManager(
      new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0));
}

TrayItemView::~TrayItemView() {}

// static
void TrayItemView::DisableAnimationsForTest() {
  animations_enabled = false;
}

void TrayItemView::CreateLabel() {
  label_ = new views::Label;
  AddChildView(label_);
}

void TrayItemView::CreateImageView() {
  image_view_ = new views::ImageView;
  AddChildView(image_view_);
}

void TrayItemView::SetVisible(bool set_visible) {
  if (!GetWidget() || !animations_enabled) {
    views::View::SetVisible(set_visible);
    return;
  }

  if (!animation_) {
    animation_.reset(new gfx::SlideAnimation(this));
    animation_->SetSlideDuration(GetAnimationDurationMS());
    animation_->SetTweenType(gfx::Tween::LINEAR);
    animation_->Reset(visible() ? 1.0 : 0.0);
  }

  if (!set_visible) {
    animation_->Hide();
    AnimationProgressed(animation_.get());
  } else {
    animation_->Show();
    AnimationProgressed(animation_.get());
    views::View::SetVisible(true);
  }
}

gfx::Size TrayItemView::DesiredSize() const {
  return views::View::GetPreferredSize();
}

int TrayItemView::GetAnimationDurationMS() {
  return kTrayItemAnimationDurationMS;
}

gfx::Size TrayItemView::GetPreferredSize() const {
  gfx::Size size = DesiredSize();
  if (wm::IsHorizontalAlignment(owner()->system_tray()->shelf_alignment()))
    size.set_height(kTrayIconHeight);
  else
    size.set_width(kTrayIconWidth);
  if (!animation_.get() || !animation_->is_animating())
    return size;
  if (wm::IsHorizontalAlignment(owner()->system_tray()->shelf_alignment())) {
    size.set_width(std::max(1,
        static_cast<int>(size.width() * animation_->GetCurrentValue())));
  } else {
    size.set_height(std::max(1,
        static_cast<int>(size.height() * animation_->GetCurrentValue())));
  }
  return size;
}

int TrayItemView::GetHeightForWidth(int width) const {
  return GetPreferredSize().height();
}

void TrayItemView::ChildPreferredSizeChanged(views::View* child) {
  PreferredSizeChanged();
}

void TrayItemView::AnimationProgressed(const gfx::Animation* animation) {
  gfx::Transform transform;
  if (wm::IsHorizontalAlignment(owner()->system_tray()->shelf_alignment())) {
    transform.Translate(0, animation->CurrentValueBetween(
        static_cast<double>(height()) / 2, 0.));
  } else {
    transform.Translate(animation->CurrentValueBetween(
        static_cast<double>(width() / 2), 0.), 0);
  }
  transform.Scale(animation->GetCurrentValue(),
                  animation->GetCurrentValue());
  layer()->SetTransform(transform);
  PreferredSizeChanged();
}

void TrayItemView::AnimationEnded(const gfx::Animation* animation) {
  if (animation->GetCurrentValue() < 0.1)
    views::View::SetVisible(false);
}

void TrayItemView::AnimationCanceled(const gfx::Animation* animation) {
  AnimationEnded(animation);
}

}  // namespace ash


text:
'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')();

var wiredep = require('wiredep');

var paths = gulp.paths;

function runTests (singleRun, done) {
  var bowerDeps = wiredep({
    directory: 'bower_components',
    exclude: ['bootstrap-sass-official'],
    dependencies: true,
    devDependencies: true
  });

  var testFiles = bowerDeps.js.concat([
    paths.src + '/{app,components,services}/**/*.js'
  ]);

  gulp.src(testFiles)
    .pipe($.karma({
      configFile: 'karma.conf.js',
      action: (singleRun)? 'run': 'watch'
    }))
    .on('error', function (err) {
      // Make sure failed tests cause gulp to exit non-zero
      throw err;
    });
}

gulp.task('test', function (done) { runTests(true /* singleRun */, done) });
gulp.task('test:auto', function (done) { runTests(false /* singleRun */, done) });


text:
title: Snakes
date: 2014-04-05
---

![Snake](http://images.nationalgeographic.com/wpf/media-live/photos/000/641/overrides/2013-year-of-the-snake-list_64139_600x450.jpg)

Snakes are elongated, legless, carnivorous reptiles of the suborder Serpentes
that can be distinguished from legless lizards by their lack of eyelids and
external ears. Like all squamates, snakes are ectothermic, amniote vertebrates
covered in overlapping scales. Many species of snakes have skulls with many more
joints than their lizard ancestors, enabling them to swallow prey much larger
than their heads with their highly mobile jaws. To accommodate their narrow
bodies, snakes' paired organs (such as kidneys) appear one in front of the other
instead of side by side, and most have only one functional lung. Some species
retain a pelvic girdle with a pair of vestigial claws on either side of the
cloaca.

Living snakes are found on every continent except Antarctica, in the Pacific and
Indian Oceans, and on most smaller land masses — exceptions include some large
islands, such as Ireland and New Zealand, and many small islands of the Atlantic
and central Pacific.

```python

class Point:
    """ Create a new Point, at coordinates x, y """

    def __init__(self, x=0, y=0):
        """ Create a new point at x, y """
        self.x = x
        self.y = y

    def distance_from_origin(self):
        """ Compute my distance from the origin """
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5

```

Snakes are thought to have evolved from either burrowing
or aquatic lizards during the mid-Cretaceous period, and the earliest known
fossils date to around 112 Ma ago. The diversity of modern snakes appeared
during the Paleocene period (c 66 to 56 Ma ago). The oldest preserved
descriptions of snakes can be found in the Brooklyn Papyrus.

Most species are nonvenomous and those that have venom use it primarily to kill
and subdue prey rather than for self-defense. Some possess venom potent enough
to cause painful injury or death to humans. Nonvenomous snakes either swallow
prey alive or kill by constriction.


text:
package pl.dagger.testing;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.TextView;

import javax.inject.Inject;

import pl.dagger.testing.app.App;

public class MainActivity extends ActionBarActivity {

    @Inject
    StringHolder mStringHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((App) getApplication()).component().inject(this);
    }

    public void onGetStringClick(View view) {
        ((TextView) findViewById(R.id.main_string)).setText(mStringHolder.getString());
    }
}


text:
package org.hibersap.execution.jca.cci;

import javax.resource.cci.ConnectionSpec;
import org.hibersap.InternalHiberSapException;
import org.hibersap.session.Credentials;

/**
 * Factory for creating instances of ConnectionSpec implementations. Decouples Hibersap from the
 * ConnectionSpec implementation and thus from the actually used JCA implementation.
 *
 * @author Carsten Erker
 */
public interface ConnectionSpecFactory {

    /**
     * Creates an instance of the ConnectionSpec implementation using the specified credentials.
     *
     * @param credentials The credentials to populate to the ConnectionSpec object.
     * @return The ConnectionSpec object, initialized with the credential properties.
     * @throws InternalHiberSapException In case of an error
     */
    ConnectionSpec createConnectionSpec(Credentials credentials);
}


text:
class RenameBlogIdColumnInComments < ActiveRecord::Migration
  def change
    rename_column :blogasaurus_comments, :blog_id, :post_id
  end
end


text:
App.Model.Share = Backbone.RelationalModel.extend({
    defaults: {
        name: null
    }
});


text:
[![Build Status](https://travis-ci.org/Schibsted-Tech-Polska/php-sndapi.svg)](https://travis-ci.org/Schibsted-Tech-Polska/php-sndapi)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/Schibsted-Tech-Polska/php-sndapi/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/Schibsted-Tech-Polska/php-sndapi/?branch=master)

This is a packagist-friendly SND API client built by Stavanger Aftenblad's team. The API uses application/json content type with UTF-8 charset. Each method returns result of `json_decode` run on result. This is not configurable yet, however we plan to introduce entity hydrators (along with entities) in near future.

Client provides console access to the API:

```sh
bin/sndapi-console
```

Console usage requires three parameters:

```sh
Options:
 --key (-s)            SND API key
 --secret (-s)         SND API secret
 --publicationId (-p)  SND API publication id (common, sa, fvn, bt, ap)
```

## Requirements

- php >= 5.5
- composer
- node & npm

## Installation

In order to add the library to your project just run:

```sh
composer require "Schibsted-Tech-Polska/php-sndapi"
```

## Development

Feel free to develop new parts of the library, but have in mind that it's fully tested with PHP Unit and you should use pull requests in order to merge your code.

## News

The library uses v2 snd news api described [here](http://developers.snd.no/doc/news/).
Authentication requires valid API secret, every API method also requires publicationId.
Publication ID is one of the following:

- common
- ap
- bt
- fvn
- sa

### Usage

Initialize the library with

```php
<?php

use Stp\SndApi\News\Client as NewsClient;

const API_KEY = 'mnbvcxzlkjhgfdsapoiuytrew';
const API_SECRET = 'qwertyuiopasdfghjklzxcvbn';
const PUBLICATION_ID = 'sa';

$newsClient = new NewsClient(API_KEY, API_SECRET, PUBLICATION_ID);
```

### Methods

#### getServiceDocument

Returns service document.

[http://developers.snd.no/doc/news/documentation/publication](http://developers.snd.no/doc/news/documentation/publication).

```php
<?php

$newsClient->getServiceDocument();
```

Console:

```sh
bin/sndapi-console news:servicedocument [-s|--secret="..."] [-p|--publicationId="..."]
```

#### getImageVersions

$newsClient->getImageVersions();
```

Console:

```sh
bin/sndapi-console news:image:versions [-s|--secret="..."] [-p|--publicationId="..."]

#### getSectionsList

Returns sections list.

[http://developers.snd.no/doc/news/documentation/section#listsections](http://developers.snd.no/doc/news/documentation/section#listsections)

```php
<?php

$newsClient->getSectionsList();
```

Console:

```sh
bin/sndapi-console news:sections:list [-s|--secret="..."] [-p|--publicationId="..."]
```

#### getSubsectionsList

Returns subsections list.

[http://developers.snd.no/doc/news/documentation/section#listsections](http://developers.snd.no/doc/news/documentation/section#listsections)

```php
<?php

$newsClient->getSubsectionsList(217);
```

#### getSectionByUniqueName

Finds a section using its unique name.

[http://developers.snd.no/doc/news/documentation/section#getsection](http://developers.snd.no/doc/news/documentation/section#getsection)

```php
<?php

$newsClient->getSectionByUniqueName('nyheter');
```

Console:

```sh
bin/sndapi-console news:section:uniquename [-s|--secret="..."] [-p|--publicationId="..."] name
```

#### getSectionById

Similar to previous one, but finds a section using its id.

[http://developers.snd.no/doc/news/documentation/section#getsection](http://developers.snd.no/doc/news/documentation/section#getsection)

```php
<?php

$newsClient->getSectionById(217);
```

Console:

```sh
bin/sndapi-console news:section:id [-s|--secret="..."] [-p|--publicationId="..."] id
```

#### getArticlesBySectionId

Finds a list of articles using section id or section's unique name.

[http://developers.snd.no/doc/news/documentation/article#listarticles](http://developers.snd.no/doc/news/documentation/article#listarticles)

### Parameters

Numeric parameters
  * areaLimit
  * offset
  * limit

Boolean values
  * includeSubsections
  * homeSectionOnly

```php
<?php

$newsClient->getArticlesBySectionId(
	217,
	'desked',
	[
		'limit' => 50
	]
);
```

Console:

```sh
bin/sndapi-console news:section:articles [-s|--secret="..."] [-p|--publicationId="..."] id method [parameters1] ... [parametersN]
```

#### getArticle

Retrieves one article, alias to searchByInstance but with *article* provided as contentType.

[http://developers.snd.no/doc/news/documentation/article#getarticle](http://developers.snd.no/doc/news/documentation/article#getarticle)

```php
<?php

$newsClient->getArticle(3687148);
```

Console:

```sh
bin/sndapi-console news:article:id [-s|--secret="..."] [-p|--publicationId="..."] id
```

#### searchByInstance

Returns search result of a specified contentId and contentType.

[http://developers.snd.no/doc/news/documentation/search#byinstance](http://developers.snd.no/doc/news/documentation/search#byinstance)

```php
<?php

$newsClient->searchByInstance(3687148, 'article');
```

Console:

```sh
bin/sndapi-console news:search:instance [-s|--secret="..."] [-p|--publicationId="..."] id contentType
```

#### searchByCollection

Returns search results of provided content ids.

[http://developers.snd.no/doc/news/documentation/search#bycollection](http://developers.snd.no/doc/news/documentation/search#bycollection)

```php
<?php

$newsClient->searchByInstance([123456, 789012]);
```

Console:

```sh
bin/sndapi-console news:search:collection [-s|--secret="..."] [-p|--publicationId="..."] ids1 ... [idsN]
```

### Not implemented yet:

#### searchResource

[http://developers.snd.no/doc/news/documentation/search#searchres](http://developers.snd.no/doc/news/documentation/search#searchres)

#### searchByTags

[http://developers.snd.no/doc/news/documentation/search#bytags](http://developers.snd.no/doc/news/documentation/search#bytags)

#### searchByQuery

[http://developers.snd.no/doc/news/documentation/search#byquery](http://developers.snd.no/doc/news/documentation/search#byquery)


text:
var o = new Object();
assert(o.toLocaleString() === o.toString());


text:
import { Editor } from "@ckeditor/ckeditor5-core";

export default function injectUnsafeKeystrokesHandling(editor: Editor): void;


text:
CinetPay Seamless Integration permet d'intégrer facilement CinetPay de façon transparente à son service en ligne, c'est à dire que le client effectue le paiement sans quitter le site
du marchand.

## Compatibilité Application Hybride

CinetPay Seamless Integration a été testé et fonctionne sur :

* Cordova
* phoneGap
* Ionic
* jQuery Mobile
L'integration de ce SDK se fait en trois etapes :

## Etape 1 : Préparer la page de notification

Pour ceux qui possèdent des services qui ne neccessitent pas un traitement des notifications de paiement de CinetPay, vous pouvez passer directement à l'etape 2, par exemple les services de don.

A chaque paiement, CinetPay vous notifie via un lien de notification, nous vous conseillons de toujours le traiter côté serveur. Nous allons utiliser PHP dans ce cas de figure :
Script index.php dans http://mondomaine.com/notify/ (le script doit se trouver dans le repertoire de votre url notify_url) ;
```php
<?php
if (isset($_POST['cpm_trans_id'])) {
    // SDK PHP de CinetPay
    require_once __DIR__ . '/cinetPay.php';
    require_once __DIR__ . '/commande.php';

    //La classe commande correspond à votre colonne qui gère les transactions dans votre base de données
    $commande = new Commande();
    try {
        // Initialisation de CinetPay et Identification du paiement
        $id_transaction = $_POST['cpm_trans_id'];
        $apiKey = _VOTRE_APIKEY_;
        $site_id = _VOTRE_SITEID_;
        $plateform = "TEST"; // Valorisé à PROD si vous êtes en production
        $CinetPay = new CinetPay($site_id, $apiKey, $plateform);
        // Reprise exacte des bonnes données chez CinetPay
        $CinetPay->setTransId($id_transaction)->getPayStatus();
        $cpm_site_id = $CinetPay->_cpm_site_id;
        $signature = $CinetPay->_signature;
        $cpm_amount = $CinetPay->_cpm_amount;
        $cpm_trans_id = $CinetPay->_cpm_trans_id;
        $cpm_custom = $CinetPay->_cpm_custom;
        $cpm_currency = $CinetPay->_cpm_currency;
        $cpm_payid = $CinetPay->_cpm_payid;
        $cpm_payment_date = $CinetPay->_cpm_payment_date;
        $cpm_payment_time = $CinetPay->_cpm_payment_time;
        $cpm_error_message = $CinetPay->_cpm_error_message;
        $payment_method = $CinetPay->_payment_method;
        $cpm_phone_prefixe = $CinetPay->_cpm_phone_prefixe;
        $cel_phone_num = $CinetPay->_cel_phone_num;
        $cpm_ipn_ack = $CinetPay->_cpm_ipn_ack;
        $created_at = $CinetPay->_created_at;
        $updated_at = $CinetPay->_updated_at;
        $cpm_result = $CinetPay->_cpm_result;
        $cpm_trans_status = $CinetPay->_cpm_trans_status;
        $cpm_designation = $CinetPay->_cpm_designation;
        $buyer_name = $CinetPay->_buyer_name;

        // Recuperation de la ligne de la transaction dans votre base de données
        $commande->setTransId($id_transaction);
        $commande->getCommandeByTransId();
        // Verification de l'etat du traitement de la commande
        if ($commande->getStatut() == '00') {
            // La commande a été déjà traité
            // Arret du script
            die();
        }
        // Dans le cas contrait, on remplit notre ligne des nouvelles données acquise en cas de tentative de paiement sur CinetPay
        $commande->setMethode($payment_method);
        $commande->setPayId($cpm_payid);
        $commande->setBuyerName($buyer_name);
        $commande->setSignature($signature);
        $commande->setPhone($cel_phone_num);
        $commande->setDatePaiement($cpm_payment_date . ' ' . $cpm_payment_time);

        // On verifie que le montant payé chez CinetPay correspond à notre montant en base de données pour cette transaction
        if ($commande->getMontant() == $cpm_amount) {
            // C'est OK : On continue le remplissage des nouvelles données
            $commande->setErrorMessage($cpm_error_message);
            $commande->setStatut($cpm_result);
            $commande->setTransStatus($cpm_trans_status);
            if($cpm_result == '00'){
                //Le paiement est bon
                // Traitez et delivrez le service au client
            }else{
                //Le paiement a échoué
            }
        } else {
            //Fraude : montant payé ' . $cpm_amount . ' ne correspond pas au montant de la commande
            $commande->setStatut('-1');
            $commande->setTransStatus('REFUSED');
        }
        // On met à jour notre ligne
        $commande->update();
    } catch (Exception $e) {
        echo "Erreur :" . $e->getMessage();
        // Une erreur s'est produite
    }
} else {
    // Tentative d'accès direct au lien IPN
}
?>
```
## Etape 2 : Préparation du formulaire de paiement

Avant de commencer cette etape, il faut lier le seamless SDK à votre page :

* `https://www.cinetpay.com/cdn/seamless_sdk/latest/cinetpay.prod.min.js`    : si vous êtes en production

Cela se fait dans la balise head de votre page web

Exemple (en PROD) :
```html
   <head>
       ...
       <script charset="utf-8"
               src="https://www.cinetpay.com/cdn/seamless_sdk/latest/cinetpay.prod.min.js"
               type="text/javascript">
       </script>
   </head>
```

#### Creation du formulaire CinetPay

Le formulaire de paiement CinetPay est constitué de :
* `amount`      : Montant du paiement
* `currency`    : Devise du paiement, toujours en CFA pour le moment
* `trans_id`    : L'identifiant de la transaction, elle est unique
* `designation` : La designation de votre paiement
* `notify_url`  : le lien de notification silencieuse (IPN) après paiement

Vous pouvez ajouter en option ces deux elements :
* `cel_phone_num`      : Numéro de téléphone sur lequel l'utilisateur effectuera le paiement
* `cpm_phone_prefixe`    : Code Pays du numéro de téléphone (exemple 225)

Exemple :

```html
<p id="payment_result"></p>
<form id="info_paiement">
    <input type="hidden"  id="amount" value="10">

    <input type="hidden" id="currency" value="CFA">

    <input type="hidden" id="trans_id" value="">

    <input type="hidden" id="cpm_custom" value="">

    <input type="hidden" id="designation" value="Achat de chaussure noir">

    <button type="submit" id="process_payment">Proceder au Paiement</button>
</form>
```
NB : _Avant l'affichage de ce formulaire, vous devez enregistrer les informations concernant cette transaction dans votre base de données afin de les verifier après paiement du client_

#### Lier le formulaire au SDK Javascript

Sur clic du bouton "Proceder au Paiement", Nous allons recuperer le montant de la transaction, l'identifiant de la transaction, la devise, la désignation et l'url de notification pour debuter le processus de paiement transparent sur CinetPay
Exemple (fichier payment.js) :
```html
<script >
    CinetPay.setConfig({
            apikey: '174323661757617531bf99c9.80613927',
            site_id: 393509,
            notify_url: 'http://mondomaine.com/notify/'
        });
    var process_payment = document.getElementById('process_payment');
        process_payment.addEventListener('click', function () {
            CinetPay.setSignatureData({
                amount: parseInt(document.getElementById('amount').value),
                trans_id: document.getElementById('trans_id').value,
                currency: document.getElementById('currency').value,
                designation: document.getElementById('designation').value,
                custom: document.getElementById('cpm_custom').value
            });
            CinetPay.getSignature();
        });
</script>
```

## Etape 3 : Observer  le paiement transparent

Lorsque le client se trouve sur le guichet de CinetPay, Vous pouvez suivre l'etat d'avancement du client sur CinetPay grace à ces evènements :

* `error`              : Une erreur s'est produite, les requëtes ajax ou le paiement ont echoué,
* `paymentPending`     : Le paiement est en cours
* `paymentSuccessfull` : Le paiement est terminé, Le paiement est valide ou est annulé

Exemple (suite du fichier payment.js):

```html
<script >
   var result_div = document.getElementById('payment_result');
   CinetPay.on('error', function (e) {
        result_div.innerHTML = '';
        result_div.innerHTML += '<b>Error code:</b>' + e.code + '<br><b>Message:</b>:' + e.message;
   });
   CinetPay.on('paymentPending', function (e) {
       result_div.innerHTML = '';
        result_div.innerHTML = 'Paiement en cours <br>';
        result_div.innerHTML += '<b>code:</b>' + e.code + '<br><b>Message:</b>:' + e.message;
   });
   CinetPay.on('signatureCreated', function () {})
   CinetPay.on('paymentSuccessfull', function (paymentInfo) {
           if(typeof paymentInfo.lastTime != 'undefined'){
               result_div.innerHTML = '';
               if(paymentInfo.cpm_result == '00'){
                   result_div.innerHTML = 'Votre paiement a été validé avec succès : <br> Montant payé :'+paymentInfo.cpm_amount+'<br>';
               }else{
                   result_div.innerHTML = 'Une erreur est survenue :'+paymentInfo.cpm_error_message;
               }
           }
   });
</script>
```

## Compatibilité Navigateurs Web

CinetPay Seamless Integration a été testé et fonctionne sur tous les navigateurs modernes y compris :

* Chrome
* Safari
* Firefox
* Opera
* Internet Explorer 8+.

## Votre Api Key et Site ID

Ces informations sont disponibles dans votre BackOffice CinetPay.

## Exemple Intégration

Vous trouverez un exemple d'intégration complet dans le dossier exemple/html/


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.dhge.ar.arnavigator">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ui.CameraActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ui.NavigationActivity" />
        <activity
            android:name=".ui.ScanResultListActivity"
            android:label="@string/title_scanresult_list"
            android:parentActivityName=".ui.CameraActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="de.dhge.ar.arnavigator.ui.CameraActivity" />
        </activity>
        <activity
            android:name=".ui.ScanResultDetailActivity"
            android:label="@string/title_scanresult_detail"
            android:parentActivityName=".ui.ScanResultListActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="de.dhge.ar.arnavigator.ui.ScanResultListActivity" />
        </activity>
    </application>

</manifest>


text:
package com.sandersdenardi.tweetreader;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity
    implements TweetsFragment.OnTweetSelectedListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
            .replace(R.id.container, new TweetsFragment())
            .commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(R.string.app_name);
        return true;
    }

    @Override
    public void onTweetSelected(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">

<meta http-equiv="Content-Language" content="en-us">
<title>IupSubmenu</title>
<link rel="stylesheet" type="text/css" href="../../style.css">

Creation

Attributes

Callbacks

Notes

Examples

See Also

IupSubmenu

  Creates a menu item that, when selected, opens another menu.

Creation

Ihandle* IupSubmenu(const char *title, Ihandle *menu); [in C]
iup.submenu{menu: ihandle[; title = title: string]} -> (ih: ihandle) [in Lua]
submenu(title, menu) [in LED]

  title: String containing the text to be shown on the item. It can be NULL
  (nil in Lua), not optional in LED.
	It will set the TITLE attribute.

  menu: optional child menu identifier. It can be NULL (nil in Lua), not
  optional in LED.

  Returns: the identifier of the
  created element, or NULL if an error occurs.

Attributes

IMAGE [Windows and GTK Only] (non inheritable): Image name of the submenu
image.
  In Windows, an item in a menu bar cannot have a
	check mark. Ignored if submenu in a menu bar. A recommended size would be
16x16 to fit the image in the menu item. In Windows, if larger than the check
mark area it will be cropped. (since 3.0)

KEY (non inheritable): Underlines a key character in the submenu
title. It
is updated only when TITLE is updated.  Deprecated, use the
mnemonic support directly in the TITLE attribute.

TITLE (non inheritable): Submenu Text. The "&"
	character can be used to define a mnemonic, the next character will be used
	as key. Use "&&" to show the "&" character instead on defining a mnemonic.

 WID (non inheritable): In Windows, returns the HMENU of
the parent menu and it is actually created only when its child menu is mapped.

ACTIVE: also accepted.

Callbacks

HIGHLIGHT_CB:
  Action generated when the submenu is
  highlighted.

MAP_CB,
UNMAP_CB,
DESTROY_CB: common callbacks are
supported.

Notes

In Motif and GTK, the text font will be affected by the dialog font when the menu is
mapped.

Examples

Browse for Example Files

See the IupMenu element for more screenshots.

See Also

IupItem, IupSeparator,
  IupMenu.


text:
import { Routes, RouterModule }  from '@angular/router';

import { UsersTable } from './users.component';

// noinspection TypeScriptValidateTypes
const routes: Routes = [
  {
    path: '',
    component: UsersTable,
    children: [
      //{ path: 'treeview', component: TreeViewComponent }
    ]
  }
];

export const routing = RouterModule.forChild(routes);


text:
package api

// IoSuffix represents map of service to shape names that
// are suffixed with `Input`, `Output` string and are not
// Input or Output shapes used by any operation within
// the service enclosure.
type IoSuffix map[string]map[string]struct{}

// LegacyIoSuffix returns if the shape names are legacy
// names that contain "Input" and "Output" name as suffix.
func (i IoSuffix) LegacyIOSuffix(a *API, shapeName string) bool {
	names, ok := i[a.name]
	if !ok {
		return false
	}

	_, ok = names[shapeName]
	return ok
}

// legacyIOSuffixed is the list of known shapes that have "Input" and "Output"
// as suffix in shape name, but are not the actual input, output shape
// for a corresponding service operation.
var legacyIOSuffixed = IoSuffix{
	"TranscribeService": {
		"RedactionOutput": struct{}{},
	},
	"Textract": {"HumanLoopActivationOutput": struct{}{}},
	"Synthetics": {
		"CanaryRunConfigInput":  struct{}{},
		"CanaryScheduleOutput":  struct{}{},
		"VpcConfigInput":        struct{}{},
		"VpcConfigOutput":       struct{}{},
		"CanaryCodeOutput":      struct{}{},
		"CanaryCodeInput":       struct{}{},
		"CanaryRunConfigOutput": struct{}{},
		"CanaryScheduleInput":   struct{}{},
	},
	"SWF": {"FunctionInput": struct{}{}},
	"SFN": {
		"InvalidOutput":         struct{}{},
		"InvalidExecutionInput": struct{}{},
		"SensitiveDataJobInput": struct{}{},
	},
	"SSM": {
		"CommandPluginOutput":                 struct{}{},
		"MaintenanceWindowStepFunctionsInput": struct{}{},
		"InvocationTraceOutput":               struct{}{},
	},
	"SSMIncidents": {"RegionMapInput": struct{}{}},

	"SMS": {
		"AppValidationOutput":    struct{}{},
		"ServerValidationOutput": struct{}{},
		"ValidationOutput":       struct{}{},
		"SSMOutput":              struct{}{},
	},
	"ServiceDiscovery": {"InvalidInput": struct{}{}},
	"ServiceCatalog": {
		"RecordOutput":               struct{}{},
		"ProvisioningArtifactOutput": struct{}{},
	},
	"Schemas": {
		"GetDiscoveredSchemaVersionItemInput":         struct{}{},
		"__listOfGetDiscoveredSchemaVersionItemInput": struct{}{},
	},

	"SageMaker": {
		"ProcessingOutput":             struct{}{},
		"TaskInput":                    struct{}{},
		"TransformOutput":              struct{}{},
		"ModelBiasJobInput":            struct{}{},
		"TransformInput":               struct{}{},
		"LabelingJobOutput":            struct{}{},
		"DataQualityJobInput":          struct{}{},
		"MonitoringOutput":             struct{}{},
		"MonitoringS3Output":           struct{}{},
		"MonitoringInput":              struct{}{},
		"ProcessingS3Output":           struct{}{},
		"ModelQualityJobInput":         struct{}{},
		"ProcessingInput":              struct{}{},
		"ProcessingFeatureStoreOutput": struct{}{},
		"ModelExplainabilityJobInput":  struct{}{},
		"ProcessingS3Input":            struct{}{},
		"MonitoringGroundTruthS3Input": struct{}{},
		"EdgePresetDeploymentOutput":   struct{}{},
		"EndpointInput":                struct{}{},
	},

	"AugmentedAIRuntime": {"HumanLoopOutput": struct{}{}, "HumanLoopInput": struct{}{}},

	"S3": {
		"ParquetInput": struct{}{},
		"CSVOutput":    struct{}{},
		"JSONOutput":   struct{}{},
		"JSONInput":    struct{}{},
		"CSVInput":     struct{}{},
	},

	"Route53Domains": {"InvalidInput": struct{}{}},
	"Route53":        {"InvalidInput": struct{}{}},
	"RoboMaker":      {"S3KeyOutput": struct{}{}},

	"Rekognition": {
		"StreamProcessorInput":      struct{}{},
		"HumanLoopActivationOutput": struct{}{},
		"StreamProcessorOutput":     struct{}{},
	},

	"Proton": {"TemplateVersionSourceInput": struct{}{}, "CompatibleEnvironmentTemplateInput": struct{}{}},

	"Personalize": {
		"BatchInferenceJobInput":  struct{}{},
		"BatchInferenceJobOutput": struct{}{},
		"DatasetExportJobOutput":  struct{}{},
	},

	"MWAA": {
		"ModuleLoggingConfigurationInput": struct{}{},
		"LoggingConfigurationInput":       struct{}{},
		"UpdateNetworkConfigurationInput": struct{}{},
	},

	"MQ": {"LdapServerMetadataOutput": struct{}{}, "LdapServerMetadataInput": struct{}{}},

	"MediaLive": {
		"InputDeviceConfiguredInput": struct{}{},
		"__listOfOutput":             struct{}{},
		"Input":                      struct{}{},
		"__listOfInput":              struct{}{},
		"Output":                     struct{}{},
		"InputDeviceActiveInput":     struct{}{},
	},

	"MediaConvert": {
		"Input":          struct{}{},
		"__listOfOutput": struct{}{},
		"Output":         struct{}{},
		"__listOfInput":  struct{}{},
	},
	"MediaConnect": {"Output": struct{}{}, "__listOfOutput": struct{}{}},

	"Lambda": {
		"LayerVersionContentOutput": struct{}{},
		"LayerVersionContentInput":  struct{}{},
	},

	"KinesisAnalyticsV2": {
		"KinesisStreamsInput":   struct{}{},
		"KinesisFirehoseInput":  struct{}{},
		"LambdaOutput":          struct{}{},
		"Output":                struct{}{},
		"KinesisFirehoseOutput": struct{}{},
		"Input":                 struct{}{},
		"KinesisStreamsOutput":  struct{}{},
	},

	"KinesisAnalytics": {
		"Output":                struct{}{},
		"KinesisFirehoseInput":  struct{}{},
		"LambdaOutput":          struct{}{},
		"KinesisFirehoseOutput": struct{}{},
		"KinesisStreamsInput":   struct{}{},
		"Input":                 struct{}{},
		"KinesisStreamsOutput":  struct{}{},
	},

	"IoTEvents": {"Input": struct{}{}},
	"IoT":       {"PutItemInput": struct{}{}},

	"Honeycode": {"CellInput": struct{}{}, "RowDataInput": struct{}{}},

	"Glue": {
		"TableInput":               struct{}{},
		"UserDefinedFunctionInput": struct{}{},
		"DatabaseInput":            struct{}{},
		"PartitionInput":           struct{}{},
		"ConnectionInput":          struct{}{},
	},

	"Glacier": {
		"CSVInput":                   struct{}{},
		"CSVOutput":                  struct{}{},
		"InventoryRetrievalJobInput": struct{}{},
	},

	"FIS": {
		"CreateExperimentTemplateTargetInput":        struct{}{},
		"CreateExperimentTemplateStopConditionInput": struct{}{},
		"UpdateExperimentTemplateStopConditionInput": struct{}{},
		"CreateExperimentTemplateActionInput":        struct{}{},
		"UpdateExperimentTemplateTargetInput":        struct{}{},
	},

	"Firehose": {"DeliveryStreamEncryptionConfigurationInput": struct{}{}},

	"CloudWatchEvents": {"TransformerInput": struct{}{}, "TargetInput": struct{}{}},

	"EventBridge": {"TransformerInput": struct{}{}, "TargetInput": struct{}{}},

	"ElasticsearchService": {
		"AutoTuneOptionsOutput":        struct{}{},
		"SAMLOptionsInput":             struct{}{},
		"AdvancedSecurityOptionsInput": struct{}{},
		"SAMLOptionsOutput":            struct{}{},
		"AutoTuneOptionsInput":         struct{}{},
	},

	"ElasticTranscoder": {
		"JobOutput":       struct{}{},
		"CreateJobOutput": struct{}{},
		"JobInput":        struct{}{},
	},

	"ElastiCache": {
		"UserGroupIdListInput": struct{}{},
		"PasswordListInput":    struct{}{},
		"UserIdListInput":      struct{}{},
	},

	"ECRPublic":  {"RepositoryCatalogDataInput": struct{}{}},
	"DeviceFarm": {"TestGridUrlExpiresInSecondsInput": struct{}{}},

	"GlueDataBrew": {"Output": struct{}{}, "Input": struct{}{}, "OverwriteOutput": struct{}{}},

	"CodePipeline": {"ActionExecutionInput": struct{}{}, "ActionExecutionOutput": struct{}{}},

	"CodeBuild": {"ValueInput": struct{}{}, "KeyInput": struct{}{}},

	"CloudFormation": {"Output": struct{}{}},

	"Backup": {
		"PlanInput":  struct{}{},
		"RulesInput": struct{}{},
		"RuleInput":  struct{}{},
	},

	"ApplicationInsights": {"StatesInput": struct{}{}},

	"ApiGatewayV2": {
		"TlsConfigInput":               struct{}{},
		"MutualTlsAuthenticationInput": struct{}{},
	},
	"APIGateway": {"MutualTlsAuthenticationInput": struct{}{}},
}


text:
<?php
	if (isset($_GET['idArticle']) && isset($_GET['UserMail']) && isset($_POST['com']))
	{
		require_once '../../module/Connexion.php';
		require_once '../../module/model/commentaire.php';
		require_once '../../module/model/user.php';

		$user=new  User();

		$userId=$user->getUserIdByEmail($_GET['UserMail']);

		$comment=new Commentaire($_POST['com'],$userId,$_GET['idArticle']);

		$result=$comment->save();

		if ($result)
		{
			header("location:../../../article?id=".$_GET['idArticle']);
		}
		else
		{
			header("location:../../../article?c=failed&&id=".$_GET['idArticle']);
		}
	}
	else
	{
		header("location:../../layout/Intrusion/url.inc");
	}

?>


text:
{-# LANGUAGE CPP #-}

module CodeGen.Platform.PPC where

import GhcPrelude

#define MACHREGS_NO_REGS 0
#define MACHREGS_powerpc 1
#include "../../../../includes/CodeGen.Platform.hs"


text:
MaxMind minFraud API client in Go. This client is built towards their v2.0 API
(minFraud Score and minFraud Insights) which differs slightly from the legacy
minFraud API.


text:
class EventsController < ApplicationController
  # set the vehicle instance for all actions
  before_action :set_vehicle

  #set the event instance for some actions
  before_action :set_event, only: [:show, :edit, :update, :destroy]
  def index
    @events = @vehicle.events
  end

  def new
    @event = @vehicle.events.new
  end

  def show
  end

  def create
    @event = @vehicle.events.new(event_params)
# binding.pry
    #GET the vendor_id & category_id from the select dropdowns in the form
    @event.vendor = Vendor.find(params[:event][:vendor_id])
    @event.category = Category.find(params[:event][:category_id])

    if @event.save
      redirect_to vehicle_path(@vehicle) #redirect to vehicle show
      # redirect_to vehicles_path #redirect to vehicles index
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @event.update(event_params)
      redirect_to vehicle_path(@vehicle), notice: 'Event updated.'
    else
      render :edit
    end
  end

  def destroy
    @vehicle = @event.vehicle
    @event.destroy
      redirect_to @vehicle
  end

private
  def set_vehicle
    @vehicle = Vehicle.find(params[:vehicle_id])
  end
  def set_event
    logger.debug "invoking set_event"
    @event = Event.find(params[:id])
  end

  # Allow params for event and for vendor & category
  def event_params
    #Also whitelist the vendor & category attributes:
    params.require(:event).permit(:name, :vehicle, :vendor, :category, :cost, :event_date, :due_date, :notes,
      vendors_attributes: [:id, :name, :address, :phone, :website, :hours, :notes],
      categories_attributes: [:id, :name])
  end

end


text:
package e2enode

import (
	"fmt"
	"os"
	"strings"
	"time"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	kubeletstatsv1alpha1 "k8s.io/kubelet/pkg/apis/stats/v1alpha1"
	"k8s.io/kubernetes/test/e2e/framework"
	e2ekubectl "k8s.io/kubernetes/test/e2e/framework/kubectl"
	e2evolume "k8s.io/kubernetes/test/e2e/framework/volume"

	systemdutil "github.com/coreos/go-systemd/v22/util"
	"github.com/onsi/ginkgo"
	"github.com/onsi/gomega"
	"github.com/onsi/gomega/gstruct"
	"github.com/onsi/gomega/types"
)

var _ = SIGDescribe("Summary API [NodeConformance]", func() {
	f := framework.NewDefaultFramework("summary-test")
	ginkgo.Context("when querying /stats/summary", func() {
		ginkgo.AfterEach(func() {
			if !ginkgo.CurrentGinkgoTestDescription().Failed {
				return
			}
			if framework.TestContext.DumpLogsOnFailure {
				e2ekubectl.LogFailedContainers(f.ClientSet, f.Namespace.Name, framework.Logf)
			}
			ginkgo.By("Recording processes in system cgroups")
			recordSystemCgroupProcesses()
		})
		ginkgo.It("should report resource usage through the stats api", func() {
			const pod0 = "stats-busybox-0"
			const pod1 = "stats-busybox-1"

			ginkgo.By("Creating test pods")
			numRestarts := int32(1)
			pods := getSummaryTestPods(f, numRestarts, pod0, pod1)
			f.PodClient().CreateBatch(pods)

			ginkgo.By("restarting the containers to ensure container metrics are still being gathered after a container is restarted")
			gomega.Eventually(func() error {
				for _, pod := range pods {
					err := verifyPodRestartCount(f, pod.Name, len(pod.Spec.Containers), numRestarts)
					if err != nil {
						return err
					}
				}
				return nil
			}, time.Minute, 5*time.Second).Should(gomega.BeNil())

			ginkgo.By("Waiting 15 seconds for cAdvisor to collect 2 stats points")
			time.Sleep(15 * time.Second)

			// Setup expectations.
			const (
				maxStartAge = time.Hour * 24 * 365 // 1 year
				maxStatsAge = time.Minute
			)
			ginkgo.By("Fetching node so we can match against an appropriate memory limit")
			node := getLocalNode(f)
			memoryCapacity := node.Status.Capacity["memory"]
			memoryLimit := memoryCapacity.Value()
			fsCapacityBounds := bounded(100*e2evolume.Mb, 10*e2evolume.Tb)
			// Expectations for system containers.
			sysContExpectations := func() types.GomegaMatcher {
				return gstruct.MatchAllFields(gstruct.Fields{
					"Name":      gstruct.Ignore(),
					"StartTime": recent(maxStartAge),
					"CPU": ptrMatchAllFields(gstruct.Fields{
						"Time": recent(maxStatsAge),
						// CRI stats provider tries to estimate the value of UsageNanoCores. This value can be
						// either 0 or between 10000 and 2e9.
						// Please refer, https://github.com/kubernetes/kubernetes/pull/95345#discussion_r501630942
						// for more information.
						"UsageNanoCores":       gomega.SatisfyAny(gstruct.PointTo(gomega.BeZero()), bounded(10000, 2e9)),
						"UsageCoreNanoSeconds": bounded(10000000, 1e15),
					}),
					"Memory": ptrMatchAllFields(gstruct.Fields{
						"Time": recent(maxStatsAge),
						// We don't limit system container memory.
						"AvailableBytes":  gomega.BeNil(),
						"UsageBytes":      bounded(1*e2evolume.Mb, memoryLimit),
						"WorkingSetBytes": bounded(1*e2evolume.Mb, memoryLimit),
						// this now returns /sys/fs/cgroup/memory.stat total_rss
						"RSSBytes":        bounded(1*e2evolume.Mb, memoryLimit),
						"PageFaults":      bounded(1000, 1e9),
						"MajorPageFaults": bounded(0, 100000),
					}),
					"Accelerators":       gomega.BeEmpty(),
					"Rootfs":             gomega.BeNil(),
					"Logs":               gomega.BeNil(),
					"UserDefinedMetrics": gomega.BeEmpty(),
				})
			}
			expectedPageFaultsUpperBound := 1000000
			expectedMajorPageFaultsUpperBound := 15
			if IsCgroup2UnifiedMode() {
				// On cgroupv2 these stats are recursive, so make sure they are at least like the value set
				// above for the container.
				expectedPageFaultsUpperBound = 1e9
				expectedMajorPageFaultsUpperBound = 100000
			}

			podsContExpectations := sysContExpectations().(*gstruct.FieldsMatcher)
			podsContExpectations.Fields["Memory"] = ptrMatchAllFields(gstruct.Fields{
				"Time": recent(maxStatsAge),
				// Pods are limited by Node Allocatable
				"AvailableBytes":  bounded(1*e2evolume.Kb, memoryLimit),
				"UsageBytes":      bounded(10*e2evolume.Kb, memoryLimit),
				"WorkingSetBytes": bounded(10*e2evolume.Kb, memoryLimit),
				"RSSBytes":        bounded(1*e2evolume.Kb, memoryLimit),
				"PageFaults":      bounded(0, expectedPageFaultsUpperBound),
				"MajorPageFaults": bounded(0, expectedMajorPageFaultsUpperBound),
			})
			runtimeContExpectations := sysContExpectations().(*gstruct.FieldsMatcher)
			systemContainers := gstruct.Elements{
				"kubelet": sysContExpectations(),
				"runtime": runtimeContExpectations,
				"pods":    podsContExpectations,
			}
			// The Kubelet only manages the 'misc' system container if the host is not running systemd.
			if !systemdutil.IsRunningSystemd() {
				framework.Logf("Host not running systemd; expecting 'misc' system container.")
				miscContExpectations := sysContExpectations().(*gstruct.FieldsMatcher)
				// Misc processes are system-dependent, so relax the memory constraints.
				miscContExpectations.Fields["Memory"] = ptrMatchAllFields(gstruct.Fields{
					"Time": recent(maxStatsAge),
					// We don't limit system container memory.
					"AvailableBytes":  gomega.BeNil(),
					"UsageBytes":      bounded(100*e2evolume.Kb, memoryLimit),
					"WorkingSetBytes": bounded(100*e2evolume.Kb, memoryLimit),
					"RSSBytes":        bounded(100*e2evolume.Kb, memoryLimit),
					"PageFaults":      bounded(1000, 1e9),
					"MajorPageFaults": bounded(0, 100000),
				})
				systemContainers["misc"] = miscContExpectations
			}
			// Expectations for pods.
			podExpectations := gstruct.MatchAllFields(gstruct.Fields{
				"PodRef":    gstruct.Ignore(),
				"StartTime": recent(maxStartAge),
				"Containers": gstruct.MatchAllElements(summaryObjectID, gstruct.Elements{
					"busybox-container": gstruct.MatchAllFields(gstruct.Fields{
						"Name":      gomega.Equal("busybox-container"),
						"StartTime": recent(maxStartAge),
						"CPU": ptrMatchAllFields(gstruct.Fields{
							"Time":                 recent(maxStatsAge),
							"UsageNanoCores":       bounded(10000, 1e9),
							"UsageCoreNanoSeconds": bounded(10000000, 1e11),
						}),
						"Memory": ptrMatchAllFields(gstruct.Fields{
							"Time":            recent(maxStatsAge),
							"AvailableBytes":  bounded(1*e2evolume.Kb, 80*e2evolume.Mb),
							"UsageBytes":      bounded(10*e2evolume.Kb, 80*e2evolume.Mb),
							"WorkingSetBytes": bounded(10*e2evolume.Kb, 80*e2evolume.Mb),
							"RSSBytes":        bounded(1*e2evolume.Kb, 80*e2evolume.Mb),
							"PageFaults":      bounded(100, expectedPageFaultsUpperBound),
							"MajorPageFaults": bounded(0, expectedMajorPageFaultsUpperBound),
						}),
						"Accelerators": gomega.BeEmpty(),
						"Rootfs": ptrMatchAllFields(gstruct.Fields{
							"Time":           recent(maxStatsAge),
							"AvailableBytes": fsCapacityBounds,
							"CapacityBytes":  fsCapacityBounds,
							"UsedBytes":      bounded(e2evolume.Kb, 10*e2evolume.Mb),
							"InodesFree":     bounded(1e4, 1e8),
							"Inodes":         bounded(1e4, 1e8),
							"InodesUsed":     bounded(0, 1e8),
						}),
						"Logs": ptrMatchAllFields(gstruct.Fields{
							"Time":           recent(maxStatsAge),
							"AvailableBytes": fsCapacityBounds,
							"CapacityBytes":  fsCapacityBounds,
							"UsedBytes":      bounded(e2evolume.Kb, 10*e2evolume.Mb),
							"InodesFree":     bounded(1e4, 1e8),
							"Inodes":         bounded(1e4, 1e8),
							"InodesUsed":     bounded(0, 1e8),
						}),
						"UserDefinedMetrics": gomega.BeEmpty(),
					}),
				}),
				"Network": ptrMatchAllFields(gstruct.Fields{
					"Time": recent(maxStatsAge),
					"InterfaceStats": gstruct.MatchAllFields(gstruct.Fields{
						"Name":     gomega.Equal("eth0"),
						"RxBytes":  bounded(10, 10*e2evolume.Mb),
						"RxErrors": bounded(0, 1000),
						"TxBytes":  bounded(10, 10*e2evolume.Mb),
						"TxErrors": bounded(0, 1000),
					}),
					"Interfaces": gomega.Not(gomega.BeNil()),
				}),
				"CPU": ptrMatchAllFields(gstruct.Fields{
					"Time":                 recent(maxStatsAge),
					"UsageNanoCores":       bounded(10000, 1e9),
					"UsageCoreNanoSeconds": bounded(10000000, 1e11),
				}),
				"Memory": ptrMatchAllFields(gstruct.Fields{
					"Time":            recent(maxStatsAge),
					"AvailableBytes":  bounded(1*e2evolume.Kb, 80*e2evolume.Mb),
					"UsageBytes":      bounded(10*e2evolume.Kb, 80*e2evolume.Mb),
					"WorkingSetBytes": bounded(10*e2evolume.Kb, 80*e2evolume.Mb),
					"RSSBytes":        bounded(1*e2evolume.Kb, 80*e2evolume.Mb),
					"PageFaults":      bounded(0, expectedPageFaultsUpperBound),
					"MajorPageFaults": bounded(0, expectedMajorPageFaultsUpperBound),
				}),
				"VolumeStats": gstruct.MatchAllElements(summaryObjectID, gstruct.Elements{
					"test-empty-dir": gstruct.MatchAllFields(gstruct.Fields{
						"Name":   gomega.Equal("test-empty-dir"),
						"PVCRef": gomega.BeNil(),
						"FsStats": gstruct.MatchAllFields(gstruct.Fields{
							"Time":           recent(maxStatsAge),
							"AvailableBytes": fsCapacityBounds,
							"CapacityBytes":  fsCapacityBounds,
							"UsedBytes":      bounded(e2evolume.Kb, 1*e2evolume.Mb),
							"InodesFree":     bounded(1e4, 1e8),
							"Inodes":         bounded(1e4, 1e8),
							"InodesUsed":     bounded(0, 1e8),
						}),
					}),
				}),
				"EphemeralStorage": ptrMatchAllFields(gstruct.Fields{
					"Time":           recent(maxStatsAge),
					"AvailableBytes": fsCapacityBounds,
					"CapacityBytes":  fsCapacityBounds,
					"UsedBytes":      bounded(e2evolume.Kb, 21*e2evolume.Mb),
					"InodesFree":     bounded(1e4, 1e8),
					"Inodes":         bounded(1e4, 1e8),
					"InodesUsed":     bounded(0, 1e8),
				}),
				"ProcessStats": ptrMatchAllFields(gstruct.Fields{
					"ProcessCount": bounded(0, 1e8),
				}),
			})

			matchExpectations := ptrMatchAllFields(gstruct.Fields{
				"Node": gstruct.MatchAllFields(gstruct.Fields{
					"NodeName":         gomega.Equal(framework.TestContext.NodeName),
					"StartTime":        recent(maxStartAge),
					"SystemContainers": gstruct.MatchAllElements(summaryObjectID, systemContainers),
					"CPU": ptrMatchAllFields(gstruct.Fields{
						"Time":                 recent(maxStatsAge),
						"UsageNanoCores":       bounded(100e3, 2e9),
						"UsageCoreNanoSeconds": bounded(1e9, 1e15),
					}),
					"Memory": ptrMatchAllFields(gstruct.Fields{
						"Time":            recent(maxStatsAge),
						"AvailableBytes":  bounded(100*e2evolume.Mb, memoryLimit),
						"UsageBytes":      bounded(10*e2evolume.Mb, memoryLimit),
						"WorkingSetBytes": bounded(10*e2evolume.Mb, memoryLimit),
						// this now returns /sys/fs/cgroup/memory.stat total_rss
						"RSSBytes":        bounded(1*e2evolume.Kb, memoryLimit),
						"PageFaults":      bounded(1000, 1e9),
						"MajorPageFaults": bounded(0, 100000),
					}),
					// TODO(#28407): Handle non-eth0 network interface names.
					"Network": ptrMatchAllFields(gstruct.Fields{
						"Time": recent(maxStatsAge),
						"InterfaceStats": gstruct.MatchAllFields(gstruct.Fields{
							"Name":     gomega.Or(gomega.BeEmpty(), gomega.Equal("eth0")),
							"RxBytes":  gomega.Or(gomega.BeNil(), bounded(1*e2evolume.Mb, 100*e2evolume.Gb)),
							"RxErrors": gomega.Or(gomega.BeNil(), bounded(0, 100000)),
							"TxBytes":  gomega.Or(gomega.BeNil(), bounded(10*e2evolume.Kb, 10*e2evolume.Gb)),
							"TxErrors": gomega.Or(gomega.BeNil(), bounded(0, 100000)),
						}),
						"Interfaces": gomega.Not(gomega.BeNil()),
					}),
					"Fs": ptrMatchAllFields(gstruct.Fields{
						"Time":           recent(maxStatsAge),
						"AvailableBytes": fsCapacityBounds,
						"CapacityBytes":  fsCapacityBounds,
						// we assume we are not running tests on machines more than 10tb of disk
						"UsedBytes":  bounded(e2evolume.Kb, 10*e2evolume.Tb),
						"InodesFree": bounded(1e4, 1e8),
						"Inodes":     bounded(1e4, 1e8),
						"InodesUsed": bounded(0, 1e8),
					}),
					"Runtime": ptrMatchAllFields(gstruct.Fields{
						"ImageFs": ptrMatchAllFields(gstruct.Fields{
							"Time":           recent(maxStatsAge),
							"AvailableBytes": fsCapacityBounds,
							"CapacityBytes":  fsCapacityBounds,
							// we assume we are not running tests on machines more than 10tb of disk
							"UsedBytes":  bounded(e2evolume.Kb, 10*e2evolume.Tb),
							"InodesFree": bounded(1e4, 1e8),
							"Inodes":     bounded(1e4, 1e8),
							"InodesUsed": bounded(0, 1e8),
						}),
					}),
					"Rlimit": ptrMatchAllFields(gstruct.Fields{
						"Time":                  recent(maxStatsAge),
						"MaxPID":                bounded(0, 1e8),
						"NumOfRunningProcesses": bounded(0, 1e8),
					}),
				}),
				// Ignore extra pods since the tests run in parallel.
				"Pods": gstruct.MatchElements(summaryObjectID, gstruct.IgnoreExtras, gstruct.Elements{
					fmt.Sprintf("%s::%s", f.Namespace.Name, pod0): podExpectations,
					fmt.Sprintf("%s::%s", f.Namespace.Name, pod1): podExpectations,
				}),
			})

			ginkgo.By("Validating /stats/summary")
			// Give pods a minute to actually start up.
			gomega.Eventually(getNodeSummary, 180*time.Second, 15*time.Second).Should(matchExpectations)
			// Then the summary should match the expectations a few more times.
			gomega.Consistently(getNodeSummary, 30*time.Second, 15*time.Second).Should(matchExpectations)
		})
	})
})

func getSummaryTestPods(f *framework.Framework, numRestarts int32, names ...string) []*v1.Pod {
	pods := make([]*v1.Pod, 0, len(names))
	for _, name := range names {
		pods = append(pods, &v1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: name,
			},
			Spec: v1.PodSpec{
				RestartPolicy: v1.RestartPolicyAlways,
				Containers: []v1.Container{
					{
						Name:  "busybox-container",
						Image: busyboxImage,
						SecurityContext: &v1.SecurityContext{
							Capabilities: &v1.Capabilities{
								Add: []v1.Capability{"NET_RAW"},
							},
						},
						Command: getRestartingContainerCommand("/test-empty-dir-mnt", 0, numRestarts, "echo 'some bytes' >/outside_the_volume.txt; ping -c 1 google.com; echo 'hello world' >> /test-empty-dir-mnt/file;"),
						Resources: v1.ResourceRequirements{
							Limits: v1.ResourceList{
								// Must set memory limit to get MemoryStats.AvailableBytes
								v1.ResourceMemory: resource.MustParse("80M"),
							},
						},
						VolumeMounts: []v1.VolumeMount{
							{MountPath: "/test-empty-dir-mnt", Name: "test-empty-dir"},
						},
					},
				},
				SecurityContext: &v1.PodSecurityContext{
					SELinuxOptions: &v1.SELinuxOptions{
						Level: "s0",
					},
				},
				Volumes: []v1.Volume{
					// TODO(#28393): Test secret volumes
					// TODO(#28394): Test hostpath volumes
					{Name: "test-empty-dir", VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}},
				},
			},
		})
	}
	return pods
}

// Mapping function for gstruct.MatchAllElements
func summaryObjectID(element interface{}) string {
	switch el := element.(type) {
	case kubeletstatsv1alpha1.PodStats:
		return fmt.Sprintf("%s::%s", el.PodRef.Namespace, el.PodRef.Name)
	case kubeletstatsv1alpha1.ContainerStats:
		return el.Name
	case kubeletstatsv1alpha1.VolumeStats:
		return el.Name
	case kubeletstatsv1alpha1.UserDefinedMetric:
		return el.Name
	default:
		framework.Failf("Unknown type: %T", el)
		return "???"
	}
}

// Convenience functions for common matcher combinations.
func ptrMatchAllFields(fields gstruct.Fields) types.GomegaMatcher {
	return gstruct.PointTo(gstruct.MatchAllFields(fields))
}

func bounded(lower, upper interface{}) types.GomegaMatcher {
	return gstruct.PointTo(gomega.And(
		gomega.BeNumerically(">=", lower),
		gomega.BeNumerically("<=", upper)))
}

func recent(d time.Duration) types.GomegaMatcher {
	return gomega.WithTransform(func(t metav1.Time) time.Time {
		return t.Time
	}, gomega.And(
		gomega.BeTemporally(">=", time.Now().Add(-d)),
		// Now() is the test start time, not the match time, so permit a few extra minutes.
		gomega.BeTemporally("<", time.Now().Add(3*time.Minute))))
}

func recordSystemCgroupProcesses() {
	cfg, err := getCurrentKubeletConfig()
	if err != nil {
		framework.Logf("Failed to read kubelet config: %v", err)
		return
	}
	cgroups := map[string]string{
		"kubelet": cfg.KubeletCgroups,
		"misc":    cfg.SystemCgroups,
	}
	for name, cgroup := range cgroups {
		if cgroup == "" {
			framework.Logf("Skipping unconfigured cgroup %s", name)
			continue
		}

		filePattern := "/sys/fs/cgroup/cpu/%s/cgroup.procs"
		if IsCgroup2UnifiedMode() {
			filePattern = "/sys/fs/cgroup/%s/cgroup.procs"
		}
		pids, err := os.ReadFile(fmt.Sprintf(filePattern, cgroup))
		if err != nil {
			framework.Logf("Failed to read processes in cgroup %s: %v", name, err)
			continue
		}

		framework.Logf("Processes in %s cgroup (%s):", name, cgroup)
		for _, pid := range strings.Fields(string(pids)) {
			path := fmt.Sprintf("/proc/%s/cmdline", pid)
			cmd, err := os.ReadFile(path)
			if err != nil {
				framework.Logf("  ginkgo.Failed to read %s: %v", path, err)
			} else {
				framework.Logf("  %s", cmd)
			}
		}
	}
}


text:
namespace Autofac.Do
{
    using Autofac;

    public sealed class TestModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);
            builder.RegisterType<ConsoleOutput>().As<IOutput>();

            MethodInjection(builder);

            builder.RegisterType<ConfigReader>().As<IConfigReader>().AsSelf();
       }

        private void MethodInjection(ContainerBuilder builder)
        {
            // for the method injection, we can use either one

            // use activiating event handler
            //builder.RegisterType<TodayWriter>().As<IDataWriter>().SingleInstance().AsSelf() .OnActivated(args => args.Instance.Subscribe(args.Context.Resolve<IOutput>()));

            // use lambda experession
            builder.Register(c =>
            {
                var writer = new TodayWriter();
                writer.Subscribe(c.Resolve<IOutput>());
                return writer;
            }).As<IDataWriter>().AsSelf().SingleInstance();
        }
    }
}


text:
set -o pipefail
# Copy files from /usr/share/maven/ref into ${MAVEN_CONFIG}
# So the initial ~/.m2 is set with expected content.
# Don't override, as this is just a reference setup
copy_reference_file() {
  local root="${1}"
  local f="${2%/}"
  local logfile="${3}"
  local rel="${f/${root}/}" # path relative to /usr/share/maven/ref/
  echo "$f" >> "$logfile"
  echo " $f -> $rel" >> "$logfile"
  if [[ ! -e ${MAVEN_CONFIG}/${rel} || $f = *.override ]]
  then
    echo "copy $rel to ${MAVEN_CONFIG}" >> "$logfile"
    mkdir -p "${MAVEN_CONFIG}/$(dirname "${rel}")"
    cp -r "${f}" "${MAVEN_CONFIG}/${rel}";
  fi;
}

copy_reference_files() {
  local log="$MAVEN_CONFIG/copy_reference_file.log"
  touch "${log}" || (echo "Can not write to ${log}. Wrong volume permissions?" && exit 1)
  echo "--- Copying files at $(date)" >> "$log"
  find /usr/share/maven/ref/ -type f -exec bash -eu -c 'copy_reference_file /usr/share/maven/ref/ "$1" "$2"' _ {} "$log" \;
}

export -f copy_reference_file
copy_reference_files

exec "$@"