text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Alfa_1.Data;
using Alfa_1.Models;
using Alfa_1.Services;
using Microsoft.AspNetCore.Identity;
using Alfa_1.Configuration;
using System.Globalization;
using Microsoft.AspNetCore.Authentication.Cookies;

using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace Alfa_1
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets<Startup>();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //---------------- DAEY add 401 em vez de redirect para login na api
            services.Configure<IdentityOptions>(config =>
            {
                config.Cookies.ApplicationCookie.Events =
                    new CookieAuthenticationEvents
                    {
                        OnRedirectToLogin = ctx =>
                        {
                            if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode != 200)
                            {
                                ctx.Response.StatusCode = 401;
                                return Task.FromResult<object>(null);
                            }

                            ctx.Response.Redirect(ctx.RedirectUri);
                            return Task.FromResult<object>(null);
                        }
                    };
            });

            // Envio de email
            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
            })
              .AddEntityFrameworkStores<ApplicationDbContext>()
              .AddDefaultTokenProviders();

            // Configure using a sub-section of the appsettings.json file.
            services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
            services.Configure<AppConfiguration>(Configuration.GetSection("AppConfiguration"));

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AppConfiguration:Key").Value)),
                    ValidAudience = Configuration.GetSection("AppConfiguration:SiteUrl").Value,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    ValidIssuer = Configuration.GetSection("AppConfiguration:SiteUrl").Value
                }
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            // -------------- inicialiar o crateRoles DAEY
            // ADD ROLES ---- 0.1
            await CreateRoles(serviceProvider);
            // problemas com "." em latitude e longitude.. alterar cultureinfo
            System.Globalization.CultureInfo customCulture = new CultureInfo("PT");
            customCulture.NumberFormat.NumberDecimalSeparator = ".";
            CultureInfo.DefaultThreadCurrentCulture = customCulture;
        }

        /// Criar Roles no startup DAEY com user login pass no appsetting.json
        /// // ADD ROLES ---- 0.1
        private async Task CreateRoles(IServiceProvider serviceProvider)
        {
            //adding custom roles
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

            string[] roleNames = { "Admin", "Manager", "Member" };
            IdentityResult roleResult;

            foreach (var roleName in roleNames)
            {
                //creating the roles and seeding them to the database
                var roleExist = await roleManager.RoleExistsAsync(roleName);
                if (!roleExist)
                {
                    roleResult = await roleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            //creating a super user who could maintain the web app
            var poweruser = new ApplicationUser
            {
                UserName = Configuration.GetSection("AppSettings")["UserEmail"],
                Email = Configuration.GetSection("AppSettings")["UserEmail"],
                EmailConfirmed = true,// autoconfirmar o email enviado
                Profile = new Profile {
                                       RegisterDate = DateTime.Now,
                                       ProfilePicture = "Profile.png"
                                       } // // criar novo profile vazio para utilizador ADD Profile ---- 0.2
            };

            string UserPassword = Configuration.GetSection("AppSettings")["UserPassword"];
            var _user = await userManager.FindByEmailAsync(Configuration.GetSection("AppSettings")["UserEmail"]);

            if (_user == null)
            {
                var createPowerUser = await userManager.CreateAsync(poweruser, UserPassword);

                if (createPowerUser.Succeeded)
                {
                    //here we tie the new user to the "Admin" role
                    await userManager.AddToRoleAsync(poweruser, "Admin");
                }
            }
        }
    }
}


text:
describe('angularjs home page', function() {
  var angularPage = require('./angularsite_page.js');

  beforeEach(function() {
    angularPage.navigate();
  })

  it('should show localization info in the tabs', function() {
    expect(angularPage.usTabContent.getText()).toMatch('Number: 98,765.432');
  });

  it('should switch to the pluralization tab', function() {
    angularPage.tabs.get(1).click();
    expect(angularPage.usTabContent.getText()).toMatch('no beers');
  });
});

redpajama_set_name: RedPajamaGithub


text:
package org.linkedin.glu.provisioner.plan.impl;

import org.linkedin.glu.provisioner.plan.api.IPlanExecution;
import org.linkedin.glu.provisioner.plan.api.Plan;
import org.linkedin.glu.provisioner.plan.api.IStepExecution;
import org.linkedin.glu.provisioner.plan.api.IStepCompletionStatus;
import org.linkedin.glu.provisioner.plan.api.IStep;
import org.linkedin.glu.provisioner.plan.api.XmlStepCompletionStatusVisitor;
import org.linkedin.util.clock.Timespan;
import org.linkedin.util.xml.XMLIndent;

import java.util.concurrent.TimeoutException;
import java.util.Map;
import java.util.LinkedHashMap;

/**
 * @author ypujante@linkedin.com
 */
public class PlanExecution<T> implements IPlanExecution<T>
{
  private final Plan<T> _plan;
  private final IStepExecution<T> _stepExecution;

  /**
   * Constructor
   */
  public PlanExecution(Plan<T> plan, IStepExecution<T> stepExecution)
  {
    _plan = plan;
    _stepExecution = stepExecution;
  }

  /**
   * @return the plan being executed
   */
  @Override
  public Plan<T> getPlan()
  {
    return _plan;
  }

  @Override
  public void pause()
  {
    _stepExecution.pause();
  }

  @Override
  public void resume()
  {
    _stepExecution.resume();
  }

  @Override
  public void cancel(boolean mayInterruptIfRunning)
  {
    _stepExecution.cancel(mayInterruptIfRunning);
  }

  @Override
  public IStepCompletionStatus<T> getCompletionStatus()
  {
    return _stepExecution.getCompletionStatus();
  }

  @Override
  public long getStartTime()
  {
    return _stepExecution.getStartTime();
  }

  /**
   * @return how long the execution took (or has been taking so far if not completed)
   */
  @Override
  public Timespan getDuration()
  {
    return _stepExecution.getDuration();
  }

  @Override
  public IStep<T> getStep()
  {
    return _stepExecution.getStep();
  }

  @Override
  public boolean isCancelled()
  {
    return _stepExecution.isCancelled();
  }

  @Override
  public boolean isCompleted()
  {
    return _stepExecution.isCompleted();
  }

  @Override
  public boolean isPaused()
  {
    return _stepExecution.isPaused();
  }

  @Override
  public IStepCompletionStatus<T> waitForCompletion()
    throws InterruptedException
  {
    return _stepExecution.waitForCompletion();
  }

  @Override
  public IStepCompletionStatus<T> waitForCompletion(Timespan timeout)
    throws InterruptedException, TimeoutException
  {
    return _stepExecution.waitForCompletion(timeout);
  }

  @Override
  public String toXml()
  {
    return toXml(null);
  }

  @Override
  public String toXml(Map<String, Object> context)
  {
    if(_stepExecution.isCompleted())
    {
      XmlStepCompletionStatusVisitor<T> visitor = new XmlStepCompletionStatusVisitor<T>();

      XMLIndent xml = visitor.getXml();

      xml.addXMLDecl("1.0");

      Map<String, Object> attributes = new LinkedHashMap<String, Object>();
      attributes.putAll(_plan.getMetadata());
      if(context != null)
      {
        attributes.putAll(context);
      }

      xml.addOpeningTag("plan", attributes);
      _stepExecution.getCompletionStatus().acceptVisitor(visitor);
      xml.addClosingTag("plan");

      return xml.getXML();
    }
    else
    {
      return _plan.toXml();
    }
  }

  @Override
  public String toString()
  {
    return toXml();
  }
}


text:
require 'rubygems'
require 'vcr'

def configure_vcr(mode = :none)
  if ENV['record'] == 'false' && mode == :none
    fail "Record flag is not applicable for mode 'none', please use with 'mode=all'"
  end

  if mode != :none
    unless system("sudo cp -rf #{File.dirname(__FILE__)}/fixtures/repositories /var/www/")
      fail "Cannot copy repository fixtures to /var/www, ensure sudo access"
    end
  end

  VCR.configure do |c|
    c.cassette_library_dir = 'test/fixtures/vcr_cassettes'
    c.hook_into :webmock

    if ENV['record'] == 'false' && mode != :none
      uri = URI.parse(TestRuncible.server.config[:url])
      c.ignore_hosts uri.host
    end

    c.default_cassette_options = {
      :record => mode,
      :match_requests_on => [:method, :path, :params, :body_json],
      :decode_compressed_response => true
    }

    begin
      c.register_request_matcher :body_json do |request_1, request_2|
        begin
          json_1 = JSON.parse(request_1.body)
          json_2 = JSON.parse(request_2.body)

          json_1 == json_2
        rescue
          #fallback incase there is a JSON parse error
          request_1.body == request_2.body
        end
      end
    rescue
      #ignore the warning thrown about this matcher already being resgistered
    end

    begin
      c.register_request_matcher :params do |request_1, request_2|
        URI(request_1.uri).query == URI(request_2.uri).query
      end
    rescue
      #ignore the warning thrown about this matcher already being resgistered
    end
  end
end


text:
/*
 * A SNTP Implementation that (probably) updates time.h's currentTime
 * sometime after ntpIssueRequest was successfully called (returned 0).
 * Implemented as described in RFC1361 (http://tools.ietf.org/html/rfc1361)
 */
#ifndef _ntp_h
#define _ntp_h

#include <net/ipv4.h>
#include <net/udp.h>
#include <net/controller.h>

#ifndef DISABLE_DNS
extern uint8_t ntpServerDomain[];
#endif

extern IPv4Address ntpServer;

uint8_t ntpHandler(Packet *p);
uint8_t ntpIssueRequest(void);

#endif


text:
module OmniAuth
  module Otp
    class Configuration
      attr_accessor :application_key, :secret_key, :interval

      def initialize
        @application_key = nil
        @secret_key = nil
        @interval = nil
      end
    end
  end
end


text:
const chai = require('chai');
const expect = chai.expect;

const Immutable = require('immutable');
const { Map, List } = Immutable;

const minitrue = require('../src');
const Probe = require('probe');
const Providence = require('providence');

describe('minitrue', function() {

    it('should expose Probe constructor', function() {
        expect(minitrue.Probe).to.equal(Probe);
    });

    it('should return object that is instanceof Probe and Providence', function() {
        const cursor = minitrue();
        expect(cursor instanceof Probe).to.be.true;
        expect(cursor instanceof Providence).to.be.true;
    });

    it('should create Immutable Map as default root data', function() {
        const cursor = minitrue();
        const rootData = cursor.options().getIn(['root', 'data']);
        expect(rootData).to.have.property('map');
        expect(Map.isMap(rootData.map)).to.be.true;
        expect(cursor instanceof Probe).to.be.true;
        expect(cursor instanceof Providence).to.be.true;
    });

    it('should create Immutable Map from given plain js object', function() {
        const cursor = minitrue({
            foo: {
                bar: {
                    baz: 'qux'
                }
            },
            x: [1, 'a', true, null, void 0, 3.14, { foo: 'bar'}]
        });

        const rootData = cursor.options().getIn(['root', 'data']);

        expect(rootData).to.have.property('map');
        expect(Map.isMap(rootData.map)).to.be.true;
        expect(rootData.map.toJS()).to.eql({
            foo: {
                bar: {
                    baz: 'qux'
                }
            },
            x: [1, 'a', true, null, void 0, 3.14, { foo: 'bar'}]
        });
        expect(cursor instanceof Probe).to.be.true;
        expect(cursor instanceof Providence).to.be.true;
    });

    it('should create Immutable List from given plain js array', function() {
        const cursor = minitrue([1, 'a', true, null, void 0, 3.14, { foo: 'bar'}]);

        const rootData = cursor.options().getIn(['root', 'data']);

        expect(rootData).to.have.property('map');
        expect(List.isList(rootData.map)).to.be.true;
        expect(rootData.map.toJS()).to.eql([1, 'a', true, null, void 0, 3.14, { foo: 'bar'}]);
        expect(cursor instanceof Probe).to.be.true;
        expect(cursor instanceof Providence).to.be.true;
    });

    it('should use given Immutable collection', function() {
        const imm = Immutable.Map();
        const cursor = minitrue(imm);
        const rootData = cursor.options().getIn(['root', 'data']);
        expect(rootData).to.have.property('map');
        expect(Map.isMap(rootData.map)).to.be.true;
        expect(rootData.map).to.equal(imm);
    });

    it('should access updated value from within observe/onUpdate', function() {
        let calls = 0;
        const cursor = minitrue({});

        cursor._options = cursor._options.set('onUpdate', function() {
            expect(cursor.deref().toJS()).to.eql({
                foo: 'bar'
            });
            calls++;
        });

        cursor.observe(function() {
            expect(cursor.deref().toJS()).to.eql({
                foo: 'bar'
            });
            calls++;
        });

        cursor.update((m) => m.set('foo', 'bar'));
        expect(cursor.deref().toJS()).to.eql({
            foo: 'bar'
        });
        expect(calls).to.equal(2);
    });

    it('should observe deleted value from within observe/onUpdate', function() {

        const cursor = minitrue({
            list: []
        });

        let onUpdateCalls = 0;
        cursor._options = cursor._options.set('onUpdate', function() {
            if(onUpdateCalls == 0) {
                expect(cursor.deref().toJS()).to.eql({
                    list: [42]
                });
            }

            if(onUpdateCalls == 1) {
                expect(cursor.deref().toJS()).to.eql({
                    list: []
                });
            }
            onUpdateCalls++;
        });

        let observeCalls = 0;
        cursor.observe(function() {
            if(observeCalls == 0) {
                expect(cursor.deref().toJS()).to.eql({
                    list: [42]
                });
            }

            if(observeCalls == 1) {
                expect(cursor.deref().toJS()).to.eql({
                    list: []
                });
            }
            observeCalls++;
        });

        cursor.cursor('list').update((list) => {
            return list.push(42);
        });

        expect(cursor.deref().toJS()).to.eql({
            list: [42]
        });

        cursor.cursor(['list', 0]).delete();

        expect(cursor.deref().toJS()).to.eql({
            list: []
        });

        expect(onUpdateCalls).to.equal(2);
        expect(observeCalls).to.equal(2);
    });
});


text:
package com.advancedpwr.record.methods;

import java.net.URL;

import com.advancedpwr.record.AccessPath;

public class URLBuilderFactory implements MethodWriterFactory
{
	/* (non-Javadoc)
	 * @see com.advancedpwr.record.methods.Factory#accept(java.lang.Class)
	 */
	public boolean accept( Class inClass )
	{
		return URL.class.equals( inClass );
	}

	/* (non-Javadoc)
	 * @see com.advancedpwr.record.methods.Factory#createMethodBuilder(com.advancedpwr.record.AccessPath)
	 */
	public BuildMethodWriter createMethodBuilder( AccessPath inPath )
	{
		return new URLBuilder();
	}
}


text:
#include "postgres.h"

#include <unistd.h>
#ifdef HAVE_SYS_PSTAT_H
#include <sys/pstat.h>			/* for HP-UX */
#endif
#ifdef HAVE_PS_STRINGS
#include <machine/vmparam.h>	/* for old BSD */
#include <sys/exec.h>
#endif
#if defined(__darwin__)
#include <crt_externs.h>
#endif

#include "libpq/libpq.h"
#include "miscadmin.h"
#include "utils/ps_status.h"

extern char **environ;
bool		update_process_title = true;

/*
 * Alternative ways of updating ps display:
 *
 * PS_USE_SETPROCTITLE
 *	   use the function setproctitle(const char *, ...)
 *	   (newer BSD systems)
 * PS_USE_PSTAT
 *	   use the pstat(PSTAT_SETCMD, )
 *	   (HPUX)
 * PS_USE_PS_STRINGS
 *	   assign PS_STRINGS->ps_argvstr = "string"
 *	   (some BSD systems)
 * PS_USE_CHANGE_ARGV
 *	   assign argv[0] = "string"
 *	   (some other BSD systems)
 * PS_USE_CLOBBER_ARGV
 *	   write over the argv and environment area
 *	   (most SysV-like systems)
 * PS_USE_WIN32
 *	   push the string out as the name of a Windows event
 * PS_USE_NONE
 *	   don't update ps display
 *	   (This is the default, as it is safest.)
 */
#if defined(HAVE_SETPROCTITLE)
#define PS_USE_SETPROCTITLE
#elif defined(HAVE_PSTAT) && defined(PSTAT_SETCMD)
#define PS_USE_PSTAT
#elif defined(HAVE_PS_STRINGS)
#define PS_USE_PS_STRINGS
#elif (defined(BSD) || defined(__bsdi__) || defined(__hurd__)) && !defined(__darwin__)
#define PS_USE_CHANGE_ARGV
#elif defined(__linux__) || defined(_AIX) || defined(__sgi) || (defined(sun) && !defined(BSD)) || defined(ultrix) || defined(__ksr__) || defined(__osf__) || defined(__svr4__) || defined(__svr5__) || defined(__darwin__)
#define PS_USE_CLOBBER_ARGV
#elif defined(WIN32)
#define PS_USE_WIN32
#else
#define PS_USE_NONE
#endif

/* Different systems want the buffer padded differently */
#if defined(_AIX) || defined(__linux__) || defined(__svr4__)
#define PS_PADDING '\0'
#else
#define PS_PADDING ' '
#endif

#ifndef PS_USE_CLOBBER_ARGV
/* all but one options need a buffer to write their ps line in */
#define PS_BUFFER_SIZE 256
static char ps_buffer[PS_BUFFER_SIZE];
static const size_t ps_buffer_size = PS_BUFFER_SIZE;
#else							/* PS_USE_CLOBBER_ARGV */
static char *ps_buffer;			/* will point to argv area */
static size_t ps_buffer_size;	/* space determined at run time */
static size_t last_status_len;	/* use to minimize length of clobber */
#endif   /* PS_USE_CLOBBER_ARGV */

static size_t ps_buffer_fixed_size;		/* size of the constant prefix */

/* save the original argv[] location here */
static int	save_argc;
static char **save_argv;

/*
 * Call this early in startup to save the original argc/argv values.
 * If needed, we make a copy of the original argv[] array to preserve it
 * from being clobbered by subsequent ps_display actions.
 *
 * (The original argv[] will not be overwritten by this routine, but may be
 * overwritten during init_ps_display.	Also, the physical location of the
 * environment strings may be moved, so this should be called before any code
 * that might try to hang onto a getenv() result.)
 */
char	  **
save_ps_display_args(int argc, char **argv)
{
	save_argc = argc;
	save_argv = argv;

#if defined(PS_USE_CLOBBER_ARGV)

	/*
	 * If we're going to overwrite the argv area, count the available space.
	 * Also move the environment to make additional room.
	 */
	{
		char	   *end_of_area = NULL;
		char	  **new_environ;
		int			i;

		/*
		 * check for contiguous argv strings
		 */
		for (i = 0; i < argc; i++)
		{
			if (i == 0 || end_of_area + 1 == argv[i])
				end_of_area = argv[i] + strlen(argv[i]);
		}

		if (end_of_area == NULL)	/* probably can't happen? */
		{
			ps_buffer = NULL;
			ps_buffer_size = 0;
			return argv;
		}

		/*
		 * check for contiguous environ strings following argv
		 */
		for (i = 0; environ[i] != NULL; i++)
		{
			if (end_of_area + 1 == environ[i])
				end_of_area = environ[i] + strlen(environ[i]);
		}

		ps_buffer = argv[0];
		last_status_len = ps_buffer_size = end_of_area - argv[0];

		/*
		 * move the environment out of the way
		 */
		new_environ = (char **) malloc((i + 1) * sizeof(char *));
		for (i = 0; environ[i] != NULL; i++)
			new_environ[i] = strdup(environ[i]);
		new_environ[i] = NULL;
		environ = new_environ;
	}
#endif   /* PS_USE_CLOBBER_ARGV */

#if defined(PS_USE_CHANGE_ARGV) || defined(PS_USE_CLOBBER_ARGV)

	/*
	 * If we're going to change the original argv[] then make a copy for
	 * argument parsing purposes.
	 *
	 * (NB: do NOT think to remove the copying of argv[], even though
	 * postmaster.c finishes looking at argv[] long before we ever consider
	 * changing the ps display.  On some platforms, getopt() keeps pointers
	 * into the argv array, and will get horribly confused when it is
	 * re-called to analyze a subprocess' argument string if the argv storage
	 * has been clobbered meanwhile.  Other platforms have other dependencies
	 * on argv[].
	 */
	{
		char	  **new_argv;
		int			i;

		new_argv = (char **) malloc((argc + 1) * sizeof(char *));
		for (i = 0; i < argc; i++)
			new_argv[i] = strdup(argv[i]);
		new_argv[argc] = NULL;

#if defined(__darwin__)

		/*
		 * Darwin (and perhaps other NeXT-derived platforms?) has a static
		 * copy of the argv pointer, which we may fix like so:
		 */
		*_NSGetArgv() = new_argv;
#endif

		argv = new_argv;
	}
#endif   /* PS_USE_CHANGE_ARGV or PS_USE_CLOBBER_ARGV */

	return argv;
}

/*
 * Call this once during subprocess startup to set the identification
 * values.	At this point, the original argv[] array may be overwritten.
 */
void
init_ps_display(const char *username, const char *dbname,
				const char *host_info, const char *initial_str)
{
	Assert(username);
	Assert(dbname);
	Assert(host_info);

#ifndef PS_USE_NONE
	/* no ps display for stand-alone backend */
	if (!IsUnderPostmaster)
		return;

	/* no ps display if you didn't call save_ps_display_args() */
	if (!save_argv)
		return;
#ifdef PS_USE_CLOBBER_ARGV
	/* If ps_buffer is a pointer, it might still be null */
	if (!ps_buffer)
		return;
#endif

	/*
	 * Overwrite argv[] to point at appropriate space, if needed
	 */

#ifdef PS_USE_CHANGE_ARGV
	save_argv[0] = ps_buffer;
	save_argv[1] = NULL;
#endif   /* PS_USE_CHANGE_ARGV */

#ifdef PS_USE_CLOBBER_ARGV
	{
		int			i;

		/* make extra argv slots point at end_of_area (a NUL) */
		for (i = 1; i < save_argc; i++)
			save_argv[i] = ps_buffer + ps_buffer_size;
	}
#endif   /* PS_USE_CLOBBER_ARGV */

	/*
	 * Make fixed prefix of ps display.
	 */

#ifdef PS_USE_SETPROCTITLE

	/*
	 * apparently setproctitle() already adds a `progname:' prefix to the ps
	 * line
	 */
	snprintf(ps_buffer, ps_buffer_size,
			 "%s %s %s ",
			 username, dbname, host_info);
#else
	snprintf(ps_buffer, ps_buffer_size,
			 "postgres: %s %s %s ",
			 username, dbname, host_info);
#endif

	ps_buffer_fixed_size = strlen(ps_buffer);

	set_ps_display(initial_str, true);
#endif   /* not PS_USE_NONE */
}

/*
 * Call this to update the ps status display to a fixed prefix plus an
 * indication of what you're currently doing passed in the argument.
 */
void
set_ps_display(const char *activity, bool force)
{

	if (!force && !update_process_title)
		return;

#ifndef PS_USE_NONE
	/* no ps display for stand-alone backend */
	if (!IsUnderPostmaster)
		return;

#ifdef PS_USE_CLOBBER_ARGV
	/* If ps_buffer is a pointer, it might still be null */
	if (!ps_buffer)
		return;
#endif

	/* Update ps_buffer to contain both fixed part and activity */
	strlcpy(ps_buffer + ps_buffer_fixed_size, activity,
			ps_buffer_size - ps_buffer_fixed_size);

	/* Transmit new setting to kernel, if necessary */

#ifdef PS_USE_SETPROCTITLE
	setproctitle("%s", ps_buffer);
#endif

#ifdef PS_USE_PSTAT
	{
		union pstun pst;

		pst.pst_command = ps_buffer;
		pstat(PSTAT_SETCMD, pst, strlen(ps_buffer), 0, 0);
	}
#endif   /* PS_USE_PSTAT */

#ifdef PS_USE_PS_STRINGS
	PS_STRINGS->ps_nargvstr = 1;
	PS_STRINGS->ps_argvstr = ps_buffer;
#endif   /* PS_USE_PS_STRINGS */

#ifdef PS_USE_CLOBBER_ARGV
	{
		int			buflen;

		/* pad unused memory */
		buflen = strlen(ps_buffer);
		/* clobber remainder of old status string */
		if (last_status_len > buflen)
			MemSet(ps_buffer + buflen, PS_PADDING, last_status_len - buflen);
		last_status_len = buflen;
	}
#endif   /* PS_USE_CLOBBER_ARGV */

#ifdef PS_USE_WIN32
	{
		/*
		 * Win32 does not support showing any changed arguments. To make it at
		 * all possible to track which backend is doing what, we create a
		 * named object that can be viewed with for example Process Explorer.
		 */
		static HANDLE ident_handle = INVALID_HANDLE_VALUE;
		char		name[PS_BUFFER_SIZE + 32];

		if (ident_handle != INVALID_HANDLE_VALUE)
			CloseHandle(ident_handle);

		sprintf(name, "pgident(%d): %s", MyProcPid, ps_buffer);

		ident_handle = CreateEvent(NULL, TRUE, FALSE, name);
	}
#endif   /* PS_USE_WIN32 */
#endif   /* not PS_USE_NONE */
}

/*
 * Returns what's currently in the ps display, in case someone needs
 * it.	Note that only the activity part is returned.  On some platforms
 * the string will not be null-terminated, so return the effective
 * length into *displen.
 */
const char *
get_ps_display(int *displen)
{
#ifdef PS_USE_CLOBBER_ARGV
	size_t		offset;

	/* If ps_buffer is a pointer, it might still be null */
	if (!ps_buffer)
	{
		*displen = 0;
		return "";
	}

	/* Remove any trailing spaces to offset the effect of PS_PADDING */
	offset = ps_buffer_size;
	while (offset > ps_buffer_fixed_size && ps_buffer[offset - 1] == PS_PADDING)
		offset--;

	*displen = offset - ps_buffer_fixed_size;
#else
	*displen = strlen(ps_buffer + ps_buffer_fixed_size);
#endif

	return ps_buffer + ps_buffer_fixed_size;
}


text:
package org.apache.skywalking.oap.server.starter;

/**
 * OAP starter specific for the ES7 storage. This includes the same code of OAPServerStartUp in the `server-starter`
 * module.
 */
public class OAPServerStartUp {
    public static void main(String[] args) {
        OAPServerBootstrap.start();
    }
}


text:
// ReSharper disable InconsistentNaming

using EasyNetQ.Producer;
using FluentAssertions;
using NSubstitute;
using RabbitMQ.Client;
using System;
using Xunit;

namespace EasyNetQ.Tests.ClientCommandDispatcherTests
{
    public class When_an_action_is_invoked_using_multi_channel : IDisposable
    {
        private readonly IClientCommandDispatcher dispatcher;
        private readonly IPersistentChannelFactory channelFactory;
        private readonly int actionResult;

        public When_an_action_is_invoked_using_multi_channel()
        {
            channelFactory = Substitute.For<IPersistentChannelFactory>();
            var channel = Substitute.For<IPersistentChannel>();
            var action = Substitute.For<Func<IModel, int>>();
            channelFactory.CreatePersistentChannel(new PersistentChannelOptions()).Returns(channel);
            channel.InvokeChannelActionAsync(action).Returns(42);

            dispatcher = new MultiChannelClientCommandDispatcher(1, channelFactory);
            actionResult = dispatcher.InvokeAsync(action, ChannelDispatchOptions.Default)
                .GetAwaiter()
                .GetResult();
        }

        public void Dispose()
        {
            dispatcher.Dispose();
        }

        [Fact]
        public void Should_create_a_persistent_channel()
        {
            channelFactory.Received().CreatePersistentChannel(new PersistentChannelOptions());
        }

        [Fact]
        public void Should_receive_action_result()
        {
            actionResult.Should().Be(42);
        }
    }
}

// ReSharper restore InconsistentNaming


text:
package armservicefabricmesh

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// NetworkClient contains the methods for the Network group.
// Don't use this type directly, use NewNetworkClient() instead.
type NetworkClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewNetworkClient creates a new instance of NetworkClient with the specified values.
// subscriptionID - The customer subscription identifier
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewNetworkClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*NetworkClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &NetworkClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// Create - Creates a network resource with the specified name, description and properties. If a network resource with the
// same name exists, then it is updated with the specified description and properties.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2018-09-01-preview
// resourceGroupName - Azure resource group name
// networkResourceName - The identity of the network.
// networkResourceDescription - Description for creating a Network resource.
// options - NetworkClientCreateOptions contains the optional parameters for the NetworkClient.Create method.
func (client *NetworkClient) Create(ctx context.Context, resourceGroupName string, networkResourceName string, networkResourceDescription NetworkResourceDescription, options *NetworkClientCreateOptions) (NetworkClientCreateResponse, error) {
	req, err := client.createCreateRequest(ctx, resourceGroupName, networkResourceName, networkResourceDescription, options)
	if err != nil {
		return NetworkClientCreateResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return NetworkClientCreateResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
		return NetworkClientCreateResponse{}, runtime.NewResponseError(resp)
	}
	return client.createHandleResponse(resp)
}

// createCreateRequest creates the Create request.
func (client *NetworkClient) createCreateRequest(ctx context.Context, resourceGroupName string, networkResourceName string, networkResourceDescription NetworkResourceDescription, options *NetworkClientCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks/{networkResourceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	urlPath = strings.ReplaceAll(urlPath, "{networkResourceName}", networkResourceName)
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2018-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, networkResourceDescription)
}

// createHandleResponse handles the Create response.
func (client *NetworkClient) createHandleResponse(resp *http.Response) (NetworkClientCreateResponse, error) {
	result := NetworkClientCreateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.NetworkResourceDescription); err != nil {
		return NetworkClientCreateResponse{}, err
	}
	return result, nil
}

// Delete - Deletes the network resource identified by the name.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2018-09-01-preview
// resourceGroupName - Azure resource group name
// networkResourceName - The identity of the network.
// options - NetworkClientDeleteOptions contains the optional parameters for the NetworkClient.Delete method.
func (client *NetworkClient) Delete(ctx context.Context, resourceGroupName string, networkResourceName string, options *NetworkClientDeleteOptions) (NetworkClientDeleteResponse, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, networkResourceName, options)
	if err != nil {
		return NetworkClientDeleteResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return NetworkClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
		return NetworkClientDeleteResponse{}, runtime.NewResponseError(resp)
	}
	return NetworkClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *NetworkClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkResourceName string, options *NetworkClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks/{networkResourceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	urlPath = strings.ReplaceAll(urlPath, "{networkResourceName}", networkResourceName)
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2018-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets the information about the network resource with the given name. The information include the description and
// other properties of the network.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2018-09-01-preview
// resourceGroupName - Azure resource group name
// networkResourceName - The identity of the network.
// options - NetworkClientGetOptions contains the optional parameters for the NetworkClient.Get method.
func (client *NetworkClient) Get(ctx context.Context, resourceGroupName string, networkResourceName string, options *NetworkClientGetOptions) (NetworkClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, networkResourceName, options)
	if err != nil {
		return NetworkClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return NetworkClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return NetworkClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *NetworkClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkResourceName string, options *NetworkClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks/{networkResourceName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	urlPath = strings.ReplaceAll(urlPath, "{networkResourceName}", networkResourceName)
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2018-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *NetworkClient) getHandleResponse(resp *http.Response) (NetworkClientGetResponse, error) {
	result := NetworkClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.NetworkResourceDescription); err != nil {
		return NetworkClientGetResponse{}, err
	}
	return result, nil
}

// NewListByResourceGroupPager - Gets the information about all network resources in a given resource group. The information
// include the description and other properties of the Network.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2018-09-01-preview
// resourceGroupName - Azure resource group name
// options - NetworkClientListByResourceGroupOptions contains the optional parameters for the NetworkClient.ListByResourceGroup
// method.
func (client *NetworkClient) NewListByResourceGroupPager(resourceGroupName string, options *NetworkClientListByResourceGroupOptions) *runtime.Pager[NetworkClientListByResourceGroupResponse] {
	return runtime.NewPager(runtime.PagingHandler[NetworkClientListByResourceGroupResponse]{
		More: func(page NetworkClientListByResourceGroupResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *NetworkClientListByResourceGroupResponse) (NetworkClientListByResourceGroupResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return NetworkClientListByResourceGroupResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return NetworkClientListByResourceGroupResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return NetworkClientListByResourceGroupResponse{}, runtime.NewResponseError(resp)
			}
			return client.listByResourceGroupHandleResponse(resp)
		},
	})
}

// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *NetworkClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *NetworkClientListByResourceGroupOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2018-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *NetworkClient) listByResourceGroupHandleResponse(resp *http.Response) (NetworkClientListByResourceGroupResponse, error) {
	result := NetworkClientListByResourceGroupResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.NetworkResourceDescriptionList); err != nil {
		return NetworkClientListByResourceGroupResponse{}, err
	}
	return result, nil
}

// NewListBySubscriptionPager - Gets the information about all network resources in a given resource group. The information
// include the description and other properties of the network.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2018-09-01-preview
// options - NetworkClientListBySubscriptionOptions contains the optional parameters for the NetworkClient.ListBySubscription
// method.
func (client *NetworkClient) NewListBySubscriptionPager(options *NetworkClientListBySubscriptionOptions) *runtime.Pager[NetworkClientListBySubscriptionResponse] {
	return runtime.NewPager(runtime.PagingHandler[NetworkClientListBySubscriptionResponse]{
		More: func(page NetworkClientListBySubscriptionResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *NetworkClientListBySubscriptionResponse) (NetworkClientListBySubscriptionResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listBySubscriptionCreateRequest(ctx, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return NetworkClientListBySubscriptionResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return NetworkClientListBySubscriptionResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return NetworkClientListBySubscriptionResponse{}, runtime.NewResponseError(resp)
			}
			return client.listBySubscriptionHandleResponse(resp)
		},
	})
}

// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *NetworkClient) listBySubscriptionCreateRequest(ctx context.Context, options *NetworkClientListBySubscriptionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabricMesh/networks"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2018-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *NetworkClient) listBySubscriptionHandleResponse(resp *http.Response) (NetworkClientListBySubscriptionResponse, error) {
	result := NetworkClientListBySubscriptionResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.NetworkResourceDescriptionList); err != nil {
		return NetworkClientListBySubscriptionResponse{}, err
	}
	return result, nil
}


text:
static const NSString * RunsDefaultVideoDeviceKey = @"RunsDefaultVideoDeviceKey";
static const NSString * RunsCurrentVideoDeviceKey = @"RunsCurrentVideoDeviceKey";
static const NSString * RunsDefaultAudioDeviceKey = @"RunsDefaultAudioDeviceKey";
static const NSString * RunsDefaultDeviceInputKey = @"RunsDefaultDeviceInputKey";

@implementation AVCaptureDevice (Configure)

+ (instancetype)rs_defaultVideoDevice {
    AVCaptureDevice *videoDev = (AVCaptureDevice *)objc_getAssociatedObject(UIApplication.sharedApplication, &RunsDefaultVideoDeviceKey);
    if (videoDev) return videoDev;
    videoDev = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    objc_setAssociatedObject(UIApplication.sharedApplication, &RunsDefaultVideoDeviceKey, videoDev, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//    [videoDev testKVO];

    return videoDev;
}

-(void)testKVO{
    [self addObserver:self forKeyPath:@"subjectAreaChangeMonitoringEnabled" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"subjectAreaChangeMonitoringEnabled"]) {
        RCKLog(@"Name is changed! new = %@",[change valueForKey:NSKeyValueChangeNewKey]);
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

+ (instancetype)rs_defaultAudioDevice {
    AVCaptureDevice *audioDev = (AVCaptureDevice *)objc_getAssociatedObject(UIApplication.sharedApplication, &RunsDefaultAudioDeviceKey);
    if (audioDev) return audioDev;
    audioDev = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    objc_setAssociatedObject(UIApplication.sharedApplication, &RunsDefaultAudioDeviceKey, audioDev, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    return audioDev;
}

+ (instancetype)rs_currentVideoDevice {
    AVCaptureDevice *videoDev = (AVCaptureDevice *)objc_getAssociatedObject(UIApplication.sharedApplication, &RunsCurrentVideoDeviceKey);
    if (videoDev) {
        return videoDev;
    }
    return [self rs_defaultVideoDevice];
}

+ (void)rs_setCurrentDevice:(AVCaptureDevice *)curDev {
    objc_setAssociatedObject(UIApplication.sharedApplication, &RunsCurrentVideoDeviceKey, curDev, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (instancetype)rs_switchCameraToPosition:(AVCaptureDevicePosition)position {
    NSArray<AVCaptureDevice *> *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    if (devices.count <= 1) return nil;
    for (AVCaptureDevice *dev in devices) {
        if (position == dev.position) {
            return dev;
        }
    }
    return nil;
}

- (AVCaptureDeviceInput *)rs_defaultDeviceInput {
    AVCaptureDeviceInput *input = (AVCaptureDeviceInput *)objc_getAssociatedObject(self, &RunsDefaultDeviceInputKey);
    if (input)  return input;

    NSError *error = nil;
    input = [AVCaptureDeviceInput deviceInputWithDevice:self error:&error];
    if (error) {
#ifdef DEBUG
        NSString *mediaType = [self valueForKeyPath:@"mediaType"];
        RCKLog(@"获取%@ DeviceInput 失败 error: %@",mediaType, error);
#endif
        return nil;
    }
    objc_setAssociatedObject(self, &RunsDefaultDeviceInputKey, input, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    return input;
}

- (void)rs_modifyConfigureCompleted:(void (^)(void))completed {
    if (!completed) {
        RCKLog(@"completed 回调为空 修改设备配置失败");
        return;
    }

    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *error = nil;
        [weakSelf lockForConfiguration:&error];
        if (error) {
            RCKLogEX(@"锁定设备失败,修改配置失败")
            return;
        }
        completed();
        [weakSelf unlockForConfiguration];
    });

}

- (void)rs_focusOnPoint:(CGPoint)point isContinuousMode:(BOOL)bRet {
    AVCaptureFocusMode focusMode = bRet ? AVCaptureFocusModeContinuousAutoFocus : AVCaptureFocusModeAutoFocus;
    AVCaptureExposureMode exposurMode = bRet ? AVCaptureExposureModeContinuousAutoExposure : AVCaptureExposureModeAutoExpose;
    AVCaptureWhiteBalanceMode whiteBalanceMode = bRet ? AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance : AVCaptureWhiteBalanceModeAutoWhiteBalance;
    CGPoint focus = CGPointMake(point.y/RCK_SCREEN_HEIGHT, 1 - point.x/RCK_SCREEN_WIDTH);
    [self rs_modifyConfigureCompleted:^{
        if ([AVCaptureDevice.rs_defaultVideoDevice isFocusModeSupported:focusMode]) {
            [AVCaptureDevice.rs_defaultVideoDevice setFocusPointOfInterest:focus];
            [AVCaptureDevice.rs_defaultVideoDevice setFocusMode:focusMode];
        }
        if ([AVCaptureDevice.rs_defaultVideoDevice isExposureModeSupported:exposurMode]) {
            [AVCaptureDevice.rs_defaultVideoDevice setExposurePointOfInterest:focus];
            [AVCaptureDevice.rs_defaultVideoDevice setExposureMode:exposurMode];
        }
        if ([AVCaptureDevice.rs_defaultVideoDevice isWhiteBalanceModeSupported:whiteBalanceMode]) {
            [AVCaptureDevice.rs_defaultVideoDevice setWhiteBalanceMode:whiteBalanceMode];
        }
        [AVCaptureDevice.rs_defaultVideoDevice setSubjectAreaChangeMonitoringEnabled:!bRet];
    }];
    RCKLog(@"单点聚焦 x : %f, y : %f", focus.x, focus.y);
}

+ (void)rs_releaseAssociateObj {
    objc_setAssociatedObject(UIApplication.sharedApplication, &RunsDefaultVideoDeviceKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(UIApplication.sharedApplication, &RunsDefaultAudioDeviceKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(UIApplication.sharedApplication, &RunsCurrentVideoDeviceKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(AVCaptureDevice.rs_defaultVideoDevice, &RunsDefaultDeviceInputKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(AVCaptureDevice.rs_defaultAudioDevice, &RunsDefaultDeviceInputKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


text:
package dashboard;

import java.util.ArrayList;
import java.util.List;

public class WidgetAndDV  {

    private String id;
    private String name;
    private String type;
    private String datasource;
    private String filter;
    private List<Column> columns;
    private Widget widget;

    public WidgetAndDV() {
       this.columns = new ArrayList<Column>();
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDatasource() {
        return datasource;
    }

    public void setDatasource(String datasource) {
        this.datasource = datasource;
    }

    public String getFilter() {
        return filter;
    }

    public void setFilter(String filter) {
        this.filter = filter;
    }

    public List<Column> getColumns() {
        return columns;
    }

    public void setColumns(List<Column> columns) {
        this.columns = columns;
    }

    public Widget getWidget() {
        return widget;
    }

    public void setWidget(Widget widget) {
        this.widget = widget;
    }
}


text:
package org.apache.camel.standalone.config;

import org.apache.camel.standalone.StandaloneRunner;
import org.crsh.spring.SpringBootstrap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class StandaloneConfig {
    private static final SpringBootstrap springBootstrap = new SpringBootstrap();

    @Bean
    public SpringBootstrap springBootstrap() {
        return springBootstrap;
    }

    @Bean(name = "StandaloneRunner")
    public StandaloneRunner standaloneRunner() {
        return StandaloneRunner.getInstance();
    }
}


text:
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery                                    |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+

/**
 * Management of elements set. Elements can belong to a category or to the
 * user caddie.
 *
 */

if (!defined('PHPWG_ROOT_PATH'))
{
  die('Hacking attempt!');
}

include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');

// +-----------------------------------------------------------------------+
// | Check Access and exit when user status is not ok                      |
// +-----------------------------------------------------------------------+

check_status(ACCESS_ADMINISTRATOR);

check_input_parameter('selection', $_POST, true, PATTERN_ID);

// +-----------------------------------------------------------------------+
// | specific actions                                                      |
// +-----------------------------------------------------------------------+

if (isset($_GET['action']))
{
  if ('empty_caddie' == $_GET['action'])
  {
    $query = '
DELETE FROM '.CADDIE_TABLE.'
  WHERE user_id = '.$user['id'].'
;';
    pwg_query($query);

    $_SESSION['page_infos'] = array(
      l10n('Information data registered in database')
      );

    redirect(get_root_url().'admin.php?page='.$_GET['page']);
  }
}

// +-----------------------------------------------------------------------+
// |                      initialize current set                           |
// +-----------------------------------------------------------------------+

// filters from form
if (isset($_POST['submitFilter']))
{
  // echo '
'; print_r($_POST); echo '
';
  unset($_REQUEST['start']); // new photo set must reset the page
  $_SESSION['bulk_manager_filter'] = array();

  if (isset($_POST['filter_prefilter_use']))
  {
    $_SESSION['bulk_manager_filter']['prefilter'] = $_POST['filter_prefilter'];

    if ('duplicates' == $_POST['filter_prefilter'])
    {
      if (isset($_POST['filter_duplicates_date']))
      {
        $_SESSION['bulk_manager_filter']['duplicates_date'] = true;
      }

      if (isset($_POST['filter_duplicates_dimensions']))
      {
        $_SESSION['bulk_manager_filter']['duplicates_dimensions'] = true;
      }
    }
  }

  if (isset($_POST['filter_category_use']))
  {
    $_SESSION['bulk_manager_filter']['category'] = $_POST['filter_category'];

    if (isset($_POST['filter_category_recursive']))
    {
      $_SESSION['bulk_manager_filter']['category_recursive'] = true;
    }
  }

  if (isset($_POST['filter_tags_use']))
  {
    $_SESSION['bulk_manager_filter']['tags'] = get_tag_ids($_POST['filter_tags'], false);

    if (isset($_POST['tag_mode']) and in_array($_POST['tag_mode'], array('AND', 'OR')))
    {
      $_SESSION['bulk_manager_filter']['tag_mode'] = $_POST['tag_mode'];
    }
  }

  if (isset($_POST['filter_level_use']))
  {
    if (in_array($_POST['filter_level'], $conf['available_permission_levels']))
    {
      $_SESSION['bulk_manager_filter']['level'] = $_POST['filter_level'];

      if (isset($_POST['filter_level_include_lower']))
      {
        $_SESSION['bulk_manager_filter']['level_include_lower'] = true;
      }
    }
  }

  if (isset($_POST['filter_dimension_use']))
  {
    foreach (array('min_width','max_width','min_height','max_height') as $type)
    {
      if (filter_var($_POST['filter_dimension_'.$type], FILTER_VALIDATE_INT) !== false)
      {
        $_SESSION['bulk_manager_filter']['dimension'][$type] = $_POST['filter_dimension_'. $type ];
      }
    }
    foreach (array('min_ratio','max_ratio') as $type)
    {
      if (filter_var($_POST['filter_dimension_'.$type], FILTER_VALIDATE_FLOAT) !== false)
      {
        $_SESSION['bulk_manager_filter']['dimension'][$type] = $_POST['filter_dimension_'. $type ];
      }
    }
  }

  if (isset($_POST['filter_filesize_use']))
  {
    foreach (array('min','max') as $type)
    {
      if (filter_var($_POST['filter_filesize_'.$type], FILTER_VALIDATE_FLOAT) !== false)
      {
        $_SESSION['bulk_manager_filter']['filesize'][$type] = $_POST['filter_filesize_'. $type ];
      }
    }
  }

  if (isset($_POST['filter_search_use']))
  {
    $_SESSION['bulk_manager_filter']['search']['q'] = $_POST['q'];
  }

  $_SESSION['bulk_manager_filter'] = trigger_change('batch_manager_register_filters', $_SESSION['bulk_manager_filter']);
}
// filters from url
elseif (isset($_GET['filter']))
{
  if (!is_array($_GET['filter']))
  {
    $_GET['filter'] = explode(',', $_GET['filter']);
  }

  $_SESSION['bulk_manager_filter'] = array();

  foreach ($_GET['filter'] as $filter)
  {
    list($type, $value) = explode('-', $filter, 2);

    switch ($type)
    {
    case 'prefilter':
      $_SESSION['bulk_manager_filter']['prefilter'] = $value;
      break;

    case 'album': case 'category': case 'cat':
      if (is_numeric($value))
      {
        $_SESSION['bulk_manager_filter']['category'] = $value;
      }
      break;

    case 'tag':
      if (is_numeric($value))
      {
        $_SESSION['bulk_manager_filter']['tags'] = array($value);
        $_SESSION['bulk_manager_filter']['tag_mode'] = 'AND';
      }
      break;

    case 'level':
      if (is_numeric($value) && in_array($value, $conf['available_permission_levels']))
      {
        $_SESSION['bulk_manager_filter']['level'] = $value;
      }
      break;

    case 'search':
      $_SESSION['bulk_manager_filter']['search']['q'] = $value;
      break;

    case 'dimension':
      $dim_map = array('w'=>'width','h'=>'height','r'=>'ratio');
      foreach (explode('-', $value) as $part)
      {
        $values = explode('..', substr($part, 1));
        if (isset($dim_map[$part[0]]))
        {
          $type = $dim_map[$part[0]];
          list(
            $_SESSION['bulk_manager_filter']['dimension']['min_'.$type],
            $_SESSION['bulk_manager_filter']['dimension']['max_'.$type]
          ) = $values;
        }
      }
      break;

    case 'filesize':
      list(
        $_SESSION['bulk_manager_filter']['filesize']['min'],
        $_SESSION['bulk_manager_filter']['filesize']['max']
      ) = explode('..', $value);
      break;

    default:
      $_SESSION['bulk_manager_filter'] = trigger_change('batch_manager_url_filter', $_SESSION['bulk_manager_filter'], $filter);
      break;
    }
  }
}

if (empty($_SESSION['bulk_manager_filter']))
{
  $_SESSION['bulk_manager_filter'] = array(
    'prefilter' => 'caddie'
    );
}

// echo '
'; print_r($_SESSION['bulk_manager_filter']); echo '
';

// depending on the current filter (in session), we find the appropriate photos
$filter_sets = array();
if (isset($_SESSION['bulk_manager_filter']['prefilter']))
{
  switch ($_SESSION['bulk_manager_filter']['prefilter'])
  {
  case 'caddie':
    $query = '
SELECT element_id
  FROM '.CADDIE_TABLE.'
  WHERE user_id = '.$user['id'].'
;';
    $filter_sets[] = query2array($query, null, 'element_id');

    break;

  case 'favorites':
    $query = '
SELECT image_id
  FROM '.FAVORITES_TABLE.'
  WHERE user_id = '.$user['id'].'
;';
    $filter_sets[] = query2array($query, null, 'image_id');

    break;

  case 'last_import':
    $query = '
SELECT MAX(date_available) AS date
  FROM '.IMAGES_TABLE.'
;';
    $row = pwg_db_fetch_assoc(pwg_query($query));
    if (!empty($row['date']))
    {
      $query = '
SELECT id
  FROM '.IMAGES_TABLE.'
  WHERE date_available BETWEEN '.pwg_db_get_recent_period_expression(1, $row['date']).' AND \''.$row['date'].'\'
;';
      $filter_sets[] = query2array($query, null, 'id');
    }

    break;

  case 'no_virtual_album':
    // we are searching elements not linked to any virtual category
    $query = '
 SELECT id
   FROM '.IMAGES_TABLE.'
 ;';
    $all_elements = query2array($query, null, 'id');

    $query = '
 SELECT id
   FROM '.CATEGORIES_TABLE.'
   WHERE dir IS NULL
 ;';
    $virtual_categories = query2array($query, null, 'id');
    if (!empty($virtual_categories))
    {
      $query = '
 SELECT DISTINCT(image_id)
   FROM '.IMAGE_CATEGORY_TABLE.'
   WHERE category_id IN ('.implode(',', $virtual_categories).')
 ;';
      $linked_to_virtual = query2array($query, null, 'image_id');
    }

    $filter_sets[] = array_diff($all_elements, $linked_to_virtual);

    break;

  case 'no_album':
    $query = '
SELECT
    id
  FROM '.IMAGES_TABLE.'
    LEFT JOIN '.IMAGE_CATEGORY_TABLE.' ON id = image_id
  WHERE category_id is null
;';
    $filter_sets[] = query2array($query, null, 'id');

    break;

  case 'no_tag':
    $query = '
SELECT
    id
  FROM '.IMAGES_TABLE.'
    LEFT JOIN '.IMAGE_TAG_TABLE.' ON id = image_id
  WHERE tag_id is null
;';
    $filter_sets[] = query2array($query, null, 'id');

    break;

  case 'duplicates':
    $duplicates_on_fields = array('file');

    if (isset($_SESSION['bulk_manager_filter']['duplicates_date']))
    {
      $duplicates_on_fields[] = 'date_creation';
    }

    if (isset($_SESSION['bulk_manager_filter']['duplicates_dimensions']))
    {
      $duplicates_on_fields[] = 'width';
      $duplicates_on_fields[] = 'height';
    }

    $query = '
SELECT
    GROUP_CONCAT(id) AS ids
  FROM '.IMAGES_TABLE.'
  GROUP BY '.implode(',', $duplicates_on_fields).'
  HAVING COUNT(*) > 1
;';
    $array_of_ids_string = query2array($query, null, 'ids');

    $ids = array();

    foreach ($array_of_ids_string as $ids_string)
    {
      $ids = array_merge($ids, explode(',', $ids_string));
    }

    $filter_sets[] = $ids;

    break;

  case 'all_photos':
    if ( count($_SESSION['bulk_manager_filter']) == 1 )
    {// make the query only if this is the only filter
      $query = '
SELECT id
  FROM '.IMAGES_TABLE.'
  '.$conf['order_by'];

      $filter_sets[] = query2array($query, null, 'id');
    }
    break;

  default:
    $filter_sets = trigger_change('perform_batch_manager_prefilters', $filter_sets, $_SESSION['bulk_manager_filter']['prefilter']);
    break;
  }
}

if (isset($_SESSION['bulk_manager_filter']['category']))
{
  $categories = array();

  if (isset($_SESSION['bulk_manager_filter']['category_recursive']))
  {
    $categories = get_subcat_ids(array($_SESSION['bulk_manager_filter']['category']));
  }
  else
  {
    $categories = array($_SESSION['bulk_manager_filter']['category']);
  }

  $query = '
 SELECT DISTINCT(image_id)
   FROM '.IMAGE_CATEGORY_TABLE.'
   WHERE category_id IN ('.implode(',', $categories).')
 ;';
  $filter_sets[] = query2array($query, null, 'image_id');
}

if (isset($_SESSION['bulk_manager_filter']['level']))
{
  $operator = '=';
  if (isset($_SESSION['bulk_manager_filter']['level_include_lower']))
  {
    $operator = '<=';
  }

  $query = '
SELECT id
  FROM '.IMAGES_TABLE.'
  WHERE level '.$operator.' '.$_SESSION['bulk_manager_filter']['level'].'
  '.$conf['order_by'];

  $filter_sets[] = query2array($query, null, 'id');
}

if (!empty($_SESSION['bulk_manager_filter']['tags']))
{
  $filter_sets[] = get_image_ids_for_tags(
    $_SESSION['bulk_manager_filter']['tags'],
    $_SESSION['bulk_manager_filter']['tag_mode'],
    null,
    null,
    false // we don't apply permissions in administration screens
    );
}

if (isset($_SESSION['bulk_manager_filter']['dimension']))
{
  $where_clauses = array();
  if (isset($_SESSION['bulk_manager_filter']['dimension']['min_width']))
  {
    $where_clause[] = 'width >= '.$_SESSION['bulk_manager_filter']['dimension']['min_width'];
  }
  if (isset($_SESSION['bulk_manager_filter']['dimension']['max_width']))
  {
    $where_clause[] = 'width <= '.$_SESSION['bulk_manager_filter']['dimension']['max_width'];
  }
  if (isset($_SESSION['bulk_manager_filter']['dimension']['min_height']))
  {
    $where_clause[] = 'height >= '.$_SESSION['bulk_manager_filter']['dimension']['min_height'];
  }
  if (isset($_SESSION['bulk_manager_filter']['dimension']['max_height']))
  {
    $where_clause[] = 'height <= '.$_SESSION['bulk_manager_filter']['dimension']['max_height'];
  }
  if (isset($_SESSION['bulk_manager_filter']['dimension']['min_ratio']))
  {
    $where_clause[] = 'width/height >= '.$_SESSION['bulk_manager_filter']['dimension']['min_ratio'];
  }
  if (isset($_SESSION['bulk_manager_filter']['dimension']['max_ratio']))
  {
    // max_ratio is a floor value, so must be a bit increased
    $where_clause[] = 'width/height < '.($_SESSION['bulk_manager_filter']['dimension']['max_ratio']+0.01);
  }

  $query = '
SELECT id
  FROM '.IMAGES_TABLE.'
  WHERE '.implode(' AND ',$where_clause).'
  '.$conf['order_by'];

  $filter_sets[] = query2array($query, null, 'id');
}

if (isset($_SESSION['bulk_manager_filter']['filesize']))
{
  $where_clauses = array();

  if (isset($_SESSION['bulk_manager_filter']['filesize']['min']))
  {
    $where_clause[] = 'filesize >= '.$_SESSION['bulk_manager_filter']['filesize']['min']*1024;
  }

  if (isset($_SESSION['bulk_manager_filter']['filesize']['max']))
  {
    $where_clause[] = 'filesize <= '.$_SESSION['bulk_manager_filter']['filesize']['max']*1024;
  }

  $query = '
SELECT id
  FROM '.IMAGES_TABLE.'
  WHERE '.implode(' AND ',$where_clause).'
  '.$conf['order_by'];

  $filter_sets[] = query2array($query, null, 'id');
}

if (isset($_SESSION['bulk_manager_filter']['search']) &&
    strlen($_SESSION['bulk_manager_filter']['search']['q']))
{
  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
  $res = get_quick_search_results_no_cache($_SESSION['bulk_manager_filter']['search']['q'], array('permissions'=>false));
  if (!empty($res['items']) && !empty($res['qs']['unmatched_terms']))
  {
    $template->assign('no_search_results', array_map('htmlspecialchars', $res['qs']['unmatched_terms']) );
  }
  $filter_sets[] = $res['items'];
}

$filter_sets = trigger_change('batch_manager_perform_filters', $filter_sets, $_SESSION['bulk_manager_filter']);

$current_set = array_shift($filter_sets);
foreach ($filter_sets as $set)
{
  $current_set = array_intersect($current_set, $set);
}
$page['cat_elements_id'] = $current_set;

// +-----------------------------------------------------------------------+
// |                       first element to display                        |
// +-----------------------------------------------------------------------+

// $page['start'] contains the number of the first element in its
// category. For exampe, $page['start'] = 12 means we must show elements #12
// and $page['nb_images'] next elements

if (!isset($_REQUEST['start'])
    or !is_numeric($_REQUEST['start'])
    or $_REQUEST['start'] < 0
    or (isset($_REQUEST['display']) and 'all' == $_REQUEST['display']))
{
  $page['start'] = 0;
}
else
{
  $page['start'] = $_REQUEST['start'];
}

// +-----------------------------------------------------------------------+
// |                                 Tabs                                  |
// +-----------------------------------------------------------------------+
$manager_link = get_root_url().'admin.php?page=batch_manager&mode=';

if (isset($_GET['mode']))
{
  $page['tab'] = $_GET['mode'];
}
else
{
  $page['tab'] = 'global';
}

$tabsheet = new tabsheet();
$tabsheet->set_id('batch_manager');
$tabsheet->select($page['tab']);
$tabsheet->assign();

// +-----------------------------------------------------------------------+
// |                              dimensions                               |
// +-----------------------------------------------------------------------+

$widths = array();
$heights = array();
$ratios = array();
$dimensions = array();

// get all width, height and ratios
$query = '
SELECT
  DISTINCT width, height
  FROM '.IMAGES_TABLE.'
  WHERE width IS NOT NULL
    AND height IS NOT NULL
;';
$result = pwg_query($query);

if (pwg_db_num_rows($result))
{
  while ($row = pwg_db_fetch_assoc($result))
  {
    if ($row['width']>0 && $row['height']>0)
    {
      $widths[] = $row['width'];
      $heights[] = $row['height'];
      $ratios[] = floor($row['width'] / $row['height'] * 100) / 100;
    }
  }
}
if (empty($widths))
{ // arbitrary values, only used when no photos on the gallery
  $widths = array(600, 1920, 3500);
  $heights = array(480, 1080, 2300);
  $ratios = array(1.25, 1.52, 1.78);
}

foreach (array('widths','heights','ratios') as $type)
{
  ${$type} = array_unique(${$type});
  sort(${$type});
  $dimensions[$type] = implode(',', ${$type});
}

$dimensions['bounds'] = array(
  'min_width' => $widths[0],
  'max_width' => end($widths),
  'min_height' => $heights[0],
  'max_height' => end($heights),
  'min_ratio' => $ratios[0],
  'max_ratio' => end($ratios),
  );

// find ratio categories
$ratio_categories = array(
  'portrait' => array(),
  'square' => array(),
  'landscape' => array(),
  'panorama' => array(),
  );

foreach ($ratios as $ratio)
{
  if ($ratio < 0.95)
  {
    $ratio_categories['portrait'][] = $ratio;
  }
  else if ($ratio >= 0.95 and $ratio <= 1.05)
  {
    $ratio_categories['square'][] = $ratio;
  }
  else if ($ratio > 1.05 and $ratio < 2)
  {
    $ratio_categories['landscape'][] = $ratio;
  }
  else if ($ratio >= 2)
  {
    $ratio_categories['panorama'][] = $ratio;
  }
}

foreach (array_keys($ratio_categories) as $type)
{
  if (count($ratio_categories[$type]) > 0)
  {
    $dimensions['ratio_'.$type] = array(
      'min' => $ratio_categories[$type][0],
      'max' => end($ratio_categories[$type]),
      );
  }
}

// selected=bound if nothing selected
foreach (array_keys($dimensions['bounds']) as $type)
{
  $dimensions['selected'][$type] = isset($_SESSION['bulk_manager_filter']['dimension'][$type])
    ? $_SESSION['bulk_manager_filter']['dimension'][$type]
    : $dimensions['bounds'][$type]
  ;
}

$template->assign('dimensions', $dimensions);

// +-----------------------------------------------------------------------+
// | filesize                                                              |
// +-----------------------------------------------------------------------+

$filesizes = array();
$filesize = array();

$query = '
SELECT
  filesize
  FROM '.IMAGES_TABLE.'
  WHERE filesize IS NOT NULL
  GROUP BY filesize
;';
$result = pwg_query($query);

while ($row = pwg_db_fetch_assoc($result))
{
  $filesizes[] = sprintf('%.1f', $row['filesize']/1024);
}

if (empty($filesizes))
{ // arbitrary values, only used when no photos on the gallery
  $filesizes = array(0, 1, 2, 5, 8, 15);
}

$filesizes = array_unique($filesizes);
sort($filesizes);

// add 0.1MB to the last value, to make sure the heavier photo will be in
// the result
$filesizes[count($filesizes)-1]+= 0.1;

$filesize['list'] = implode(',', $filesizes);

$filesize['bounds'] = array(
  'min' => $filesizes[0],
  'max' => end($filesizes),
  );

// selected=bound if nothing selected
foreach (array_keys($filesize['bounds']) as $type)
{
  $filesize['selected'][$type] = isset($_SESSION['bulk_manager_filter']['filesize'][$type])
    ? $_SESSION['bulk_manager_filter']['filesize'][$type]
    : $filesize['bounds'][$type]
  ;
}

$template->assign('filesize', $filesize);

// +-----------------------------------------------------------------------+
// |                         open specific mode                            |
// +-----------------------------------------------------------------------+

include(PHPWG_ROOT_PATH.'admin/batch_manager_'.$page['tab'].'.php');
?>


text:
<?xml version="1.0" ?>
<Simulation>
  <TestInfo>
    <name>framework/ROM/SKLearn.linearRegression</name>
    <author>maljdan</author>
    <created>2016-04-28</created>
    <classesTested>SupervisedLearning.SciKitLearn</classesTested>
    <description>
       An example exercising supervised sklearn methods, specifically
       the linear_model|LinearRegression model is tested here.
       Note, all of the tests in SKLearn operate on a 2D input domain with
       the goal of fitting a paraboloid function. The input dimensions are
       of largely different scales and one dimension is off-centered from
       the origin to ensure that normalization is being handled correctly.
       Classifiers will use this same function to determine if a point is
       above 0.25, and multitask methods will additionally fit an additive
       model (x+y).
    </description>
    <revisions>
      <revision author="alfoa" date="2016-07-13">    removed renormalization</revision>
      <revision author="talbpaul" date="2016-09-15">    other test updates</revision>
      <revision author="maljdan" date="2017-01-19">Adding this test description.</revision>
      <revision author="wangc" date="2021-08-10">Replace subType of SciKitLearn ROM with SKLtype, and Remove SKLtype</revision>
    </revisions>
  </TestInfo>

  <RunInfo>
    <WorkingDir>data</WorkingDir>
    <Sequence>
      sample,
      train,
      resample,
      writemodel
    </Sequence>
  </RunInfo>

  <Models>
    <ExternalModel ModuleToLoad="./testFunction" name="foo" subType="">
      <variables>X,Y,Z</variables>
    </ExternalModel>
    <ROM name="modelUnderTest" subType="LinearRegression">
      <!-- Using all of the defaults -->
      <Features>X,Y</Features>
      <Target>Z</Target>
      <fit_intercept>True</fit_intercept>
      <normalize>True</normalize>
    </ROM>
  </Models>

  <ExternalXML node="Distributions" xmlToLoad="sharedDistributions.xml"/>
  <ExternalXML node="Samplers" xmlToLoad="sharedSamplers.xml"/>
  <!-- <ExternalXML node="Steps" xmlToLoad="sharedSteps.xml"/> -->

  <Steps>
    <MultiRun name="sample" sleepTime="1e-5">
      <Input class="DataObjects" type="PointSet">dummyIN</Input>
      <Model class="Models" type="ExternalModel">foo</Model>
      <Sampler class="Samplers" type="MonteCarlo">mcSampler</Sampler>
      <Output class="DataObjects" type="PointSet">trainingData</Output>
    </MultiRun>
    <MultiRun name="resample" sleepTime="1e-5">
      <Input class="DataObjects" type="PointSet">dummyIN</Input>
      <Model class="Models" type="ROM">modelUnderTest</Model>
      <Sampler class="Samplers" type="Grid">gridSampler</Sampler>
      <Output class="DataObjects" type="PointSet">outData</Output>
      <Output class="OutStreams" type="Print">outData</Output>
    </MultiRun>
    <RomTrainer name="train">
      <Input class="DataObjects" type="PointSet">trainingData</Input>
      <Output class="Models" type="ROM">modelUnderTest</Output>
    </RomTrainer>
    <IOStep name="writemodel">
      <Input class="Models" type="ROM">modelUnderTest</Input>
      <Output class="DataObjects" type="PointSet">modelOut</Output>
      <Output class="OutStreams" type="Print">modelOut</Output>
    </IOStep>
  </Steps>

  <OutStreams>
    <!-- A csv file containing the output of the example -->
    <Print name="outData">
      <type>csv</type>
      <source>outData</source>
      <what>input,output</what>
      <filename>outLinearRegression</filename>
    </Print>
    <Print name="modelOut">
      <type>csv</type>
      <source>modelOut</source>
      <what>input,output</what>
      <filename>outLinearRegressionModel</filename>
    </Print>
  </OutStreams>

  <ExternalXML node="DataObjects" xmlToLoad="sharedDataObjects.xml"/>

</Simulation>


text:
using System;
using Alachisoft.NCache.Common.Threading;

namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
    /// <summary>
    /// Asynchronous notification dispatcher.
    /// </summary>
    internal class AsyncBroadcastCustomNotifyRemoval : AsyncProcessor.IAsyncTask
    {
        /// <summary> The listener class </summary>
        private ClusterCacheBase _parent;

        /// <summary> Message to broadcast </summary>
        private object _key;

        private ItemRemoveReason _reason = ItemRemoveReason.Removed;
        private OperationContext _operationContext;
        private EventContext _eventContext;
        private CacheEntry _entry;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="listener"></param>
        /// <param name="data"></param>
        public AsyncBroadcastCustomNotifyRemoval(ClusterCacheBase parent, object key, CacheEntry entry, ItemRemoveReason reason, OperationContext operationContext, EventContext eventContext)
        {
            _parent = parent;
            _key = key;
            _entry = entry;
            _reason = reason;
            _operationContext = operationContext;
            _eventContext = eventContext;
        }

        /// <summary>
        /// Implementation of message sending.
        /// </summary>
        void AsyncProcessor.IAsyncTask.Process()
        {
            try
            {
                if (_parent != null)
                {
                    _parent.RaiseCustomRemoveCalbackNotifier(_key, _entry, _reason, false, _operationContext, _eventContext);
                }
            }
            catch (Exception)
            {

            }

        }
    }
}


text:
/*
 * include/linux/ion.h
 *
 * Copyright (C) 2011 Google, Inc.
 *
 * This software is licensed under the terms of the GNU General Public


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FibSquares
{
    public class MinMaxXY
    {
        public float MinX { get; set; }
        public float MaxX { get; set; }
        public float MinY { get; set; }
        public float MaxY { get; set; }

        public MinMaxXY()
        {
            MinX = MaxX = MinY = MaxY = 0;
        }
    }
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Cordova, Plugin } from './plugin';
/**
 * @name NativeStorage
 * @description Native storage of variables in Android and iOS
 *
 * @usage
 * ```typescript
 * import { NativeStorage } from 'ionic-native';
 *
 * NativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
 *   .then(
 *     () => console.log('Stored item!'),
 *     error => console.error('Error storing item', error)
 *   );
 *
 * NativeStorage.getItem('myitem')
 *   .then(
 *     data => console.log(data),
 *     error => console.error(error)
 *   );
 * ```
 */
export var NativeStorage = (function () {
    function NativeStorage() {
    }
    /**
     * Stores a value
     * @param reference {string}
     * @param value
     * @returns {Promise<any>}
     */
    NativeStorage.setItem = function (reference, value) { return; };
    /**
     * Gets a stored item
     * @param reference {string}
     * @returns {Promise<any>}
     */
    NativeStorage.getItem = function (reference) { return; };
    /**
     * Removes a single stored item
     * @param reference {string}
     * @returns {Promise<any>}
     */
    NativeStorage.remove = function (reference) { return; };
    /**
     * Removes all stored values.
     * @returns {Promise<any>}
     */
    NativeStorage.clear = function () { return; };
    __decorate([
        Cordova()
    ], NativeStorage, "setItem", null);
    __decorate([
        Cordova()
    ], NativeStorage, "getItem", null);
    __decorate([
        Cordova()
    ], NativeStorage, "remove", null);
    __decorate([
        Cordova()
    ], NativeStorage, "clear", null);
    NativeStorage = __decorate([
        Plugin({
            pluginName: 'NativeStorage',
            plugin: 'cordova-plugin-nativestorage',
            pluginRef: 'NativeStorage',
            repo: 'https://github.com/TheCocoaProject/cordova-plugin-nativestorage'
        })
    ], NativeStorage);
    return NativeStorage;
}());
//# sourceMappingURL=nativestorage.js.map


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Forced colors mode - outline and column color with sys colors.</title>
<link rel="help" href="https://www.w3.org/TR/css-color-adjust-1/#forced-colors-properties">
<link rel=match href="forced-colors-mode-31-ref.html">
<style>
  :root {
    --hc-color: LinkText;
  }
  h1 {
    outline-color: var(--hc-color);
    outline-style: solid;
    column-count: 3;
    column-gap: 40px;
    column-rule-color: var(--hc-color);
    column-rule-style: solid;
  }
</style>
<h1>
  The outline-color and column-rule-color should be LinkText when forced colors
  mode is enabled.
</h1>


text:
<?php

namespace PhpSsrs\ReportingService2005;

class GetResourceContents
{

  /**
   *
   * @var string $Resource
   * @access public
   */
  public $Resource = null;

  /**
   *
   * @param string $Resource
   * @access public
   */
  public function __construct($Resource = null)
  {
    $this->Resource = $Resource;
  }

}


text:
FROM python:2.7.8

MAINTAINER Taariq Levack <taariql@gmail.com>

# Add the licenses for third party software and libraries
ADD licenses /licenses

# Add the external tasks directory into /tasks
ADD locust-tasks /locust-tasks

# Install the required dependencies via pip
RUN pip install -r /locust-tasks/requirements.txt

# Expose the required Locust ports
EXPOSE 5557 5558 8089

# Set script to be executable
RUN chmod 755 /locust-tasks/run.sh

ADD tasks.py /locust-tasks/tasks.py

# Start Locust using LOCUS_OPTS environment variable
ENTRYPOINT ["/locust-tasks/run.sh"]


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Function template operator<<</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../utilities.html#header.boost.log.utility.manipulators.range_hpp" title="Header <boost/log/utility/manipulators/range.hpp>">
<link rel="prev" href="range_manipulator_idm37480.html" title="Class template range_manipulator<RangeT, void>">
<link rel="next" href="range_manip_idm37516.html" title="Function template range_manip">

Function template operator<<

boost::log::operator<<

Synopsis

// In header: <boost/log/utility/manipulators/range.hpp>

template<typename StreamT, typename RangeT, typename DelimiterT>
  unspecified operator<<(StreamT & strm,
                         range_manipulator< RangeT, DelimiterT > const & manip);

Description

Stream output operator for range_manipulator. Outputs every element of the range, separated with a delimiter, if one was specified on manipulator construction.

Copyright © 2007-2021 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


text:
'use strict';

import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actions from '../actions';
import Counter from '../components/Counter';

// How should the store be passed to the App
function mapStateToProps(state) {
	return {...state};
}

// How should actions be passed into the App
function mapDispatchToProps(dispatch) {
	return {
		actions: bindActionCreators(actions, dispatch)
	}
}

class App extends Component {
	render() {
		// Render app
		return (
			<div>
				<Counter count={this.props.count} increment={this.props.actions.increment} decrement={this.props.actions.decrement} />
			</div>
		);
	}
}

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(App);


text:
namespace content {

class MediaStreamAudioTrack;

// TODO(miu): In a soon-upcoming set of refactoring changes, this class will
// become a base class for managing tracks (part of what WebRtcAudioCapturer
// does today).  Then, the rest of WebRtcAudioCapturer will be rolled into a
// subclass.   http://crbug.com/577874
class CONTENT_EXPORT MediaStreamAudioSource
    : NON_EXPORTED_BASE(public MediaStreamSource) {
 public:
  MediaStreamAudioSource(int render_frame_id,
                         const StreamDeviceInfo& device_info,
                         const SourceStoppedCallback& stop_callback,
                         PeerConnectionDependencyFactory* factory);
  MediaStreamAudioSource();
  ~MediaStreamAudioSource() override;

  // Returns the MediaStreamAudioSource instance owned by the given blink
  // |source| or null.
  static MediaStreamAudioSource* From(const blink::WebMediaStreamSource& track);

  void AddTrack(const blink::WebMediaStreamTrack& track,
                const blink::WebMediaConstraints& constraints,
                const ConstraintsCallback& callback);

  base::WeakPtr<MediaStreamAudioSource> GetWeakPtr() {
    return weak_factory_.GetWeakPtr();
  }

  // Removes |track| from the list of instances that get a copy of the source
  // audio data.
  void StopAudioDeliveryTo(MediaStreamAudioTrack* track);

  WebRtcAudioCapturer* audio_capturer() const { return audio_capturer_.get(); }

  void SetAudioCapturer(scoped_ptr<WebRtcAudioCapturer> capturer) {
    DCHECK(!audio_capturer_.get());
    audio_capturer_ = std::move(capturer);
  }

  webrtc::AudioSourceInterface* local_audio_source() {
    return local_audio_source_.get();
  }

  void SetLocalAudioSource(scoped_refptr<webrtc::AudioSourceInterface> source) {
    local_audio_source_ = std::move(source);
  }

  WebAudioCapturerSource* webaudio_capturer() const {
    return webaudio_capturer_.get();
  }

  void SetWebAudioCapturer(scoped_ptr<WebAudioCapturerSource> capturer) {
    DCHECK(!webaudio_capturer_.get());
    webaudio_capturer_ = std::move(capturer);
  }

 protected:
  void DoStopSource() override;

 private:
  const int render_frame_id_;
  PeerConnectionDependencyFactory* const factory_;

  // MediaStreamAudioSource is the owner of either a WebRtcAudioCapturer or a
  // WebAudioCapturerSource.
  //
  // TODO(miu): In a series of soon-upcoming changes, WebRtcAudioCapturer and
  // WebAudioCapturerSource will become subclasses of MediaStreamAudioSource
  // instead.
  scoped_ptr<WebRtcAudioCapturer> audio_capturer_;
  scoped_ptr<WebAudioCapturerSource> webaudio_capturer_;

  // This member holds an instance of webrtc::LocalAudioSource. This is used
  // as a container for audio options.
  scoped_refptr<webrtc::AudioSourceInterface> local_audio_source_;

  // Provides weak pointers so that MediaStreamAudioTracks won't call
  // StopAudioDeliveryTo() if this instance dies first.
  base::WeakPtrFactory<MediaStreamAudioSource> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(MediaStreamAudioSource);
};

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_MEDIA_STREAM_AUDIO_SOURCE_H_


text:
#pragma once
#include <aws/wafv2/WAFV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace WAFV2
{
namespace Model
{
  enum class PayloadType
  {
    NOT_SET,
    JSON,
    FORM_ENCODED
  };

namespace PayloadTypeMapper
{
AWS_WAFV2_API PayloadType GetPayloadTypeForName(const Aws::String& name);

AWS_WAFV2_API Aws::String GetNameForPayloadType(PayloadType value);
} // namespace PayloadTypeMapper
} // namespace Model
} // namespace WAFV2
} // namespace Aws


text:
class CreateTransactionItems < ActiveRecord::Migration
  def change
    create_table :transaction_items do |t|
      t.integer :account_id, :null => false
      t.integer :transaction_id, :null => false
      t.integer :category_id
      t.string :memo
      t.decimal :amount, :precision => 9, :scale => 2, :null => false

      t.timestamps
    end
    add_index :transaction_items, :account_id
    add_index :transaction_items, :transaction_id
    add_index :transaction_items, :category_id
  end
end


text:
sudo apt-get update
sudo apt-get upgrade -y

sudo apt-get -y install curl vim openjdk-7-jdk redis-server maven


text:
app.directive("appLoader", ["login", "$route", function(login, $route) {
  // this directive only exists to instantiate Login and provide $route to
  // the included ng-view in the directive .html file
  return {
    restrict: "E",
    templateUrl: 'js/directives/appLoader.html'
  };
}]);


text:
import coremltools
import sys, os
from _infer_shapes_nn_mlmodel import _infer_shapes
import operator

def inspect(model_path, output_txt_file):
    spec = coremltools.utils.load_spec(model_path)
    sys.stdout = open(os.devnull, "w")
    shape_dict = _infer_shapes(model_path)
    sys.stdout = sys.__stdout__

    types_dict = {}

    sys.stdout = open(output_txt_file, 'w')

    nn = spec.neuralNetwork
    if spec.WhichOneof('Type') == 'neuralNetwork':
        nn = spec.neuralNetwork
    elif spec.WhichOneof('Type') == 'neuralNetworkRegressor':
        nn = spec.neuralNetworkRegressor
    elif spec.WhichOneof('Type') == 'neuralNetworkClassifier':
        nn = spec.neuralNetworkClassifier
    else:
        raise ValueError("Only neural network model Type is supported")

    for i, layer in enumerate(nn.layers):
        print('---------------------------------------------------------------------------------------------------------------------------------------------')
        print("{}: layer name = {}, layer type = ( {} ), \n inputs = \n {}, \n input shapes = {}, \n outputs = \n {}, \n output shapes = {} ".format(i, layer.name, \
                layer.WhichOneof('layer'), ", ".join([x for x in layer.input]), ", ".join([str(shape_dict[x]) for x in layer.input]),
                ", ".join([x for x in layer.output]),
                ", ".join([str(shape_dict[x]) for x in layer.output])))

        layer_type = layer.WhichOneof('layer')
        if layer_type == 'convolution' and layer.convolution.isDeconvolution:
            layer_type = 'deconvolution'
        if layer_type in types_dict:
            types_dict[layer_type] += 1
        else:
            types_dict[layer_type] = 1

    print('---------------------------------------------------------------------------------------------------------------------------------------------')
    sorted_types_count = sorted(types_dict.items(), key=operator.itemgetter(1))
    print('Layer Type counts:')
    for i in sorted_types_count:
        print("{} : {}".format(i[0], i[1]))

if __name__ == "__main__":
    """
    Write a summary of the CoreML model to a text file.
    Summary includes layer name, type, input and output names and shapes.

    Arguments
    ----------
    - path to the CoreML .mlmodel file
    - path to the output .txt file where the summary is written

    python inspect_mlmodel.py model.mlmodel text_file.txt

    """
    if len(sys.argv) != 3:
        raise ValueError("Script expects two arguments. " +
            "Usage: python inspect_mlmodel.py /path/to/the/coreml/model.mlmodel /path/to/the/output/text/file.txt")
    inspect(sys.argv[1], sys.argv[2])


text:
package com.mongodb.internal.event;

import com.mongodb.event.CommandFailedEvent;
import com.mongodb.event.CommandListener;
import com.mongodb.event.CommandStartedEvent;
import com.mongodb.event.CommandSucceededEvent;
import com.mongodb.internal.diagnostics.logging.Logger;
import com.mongodb.internal.diagnostics.logging.Loggers;

import java.util.ArrayList;
import java.util.List;

import static com.mongodb.assertions.Assertions.isTrue;
import static java.lang.String.format;

final class CommandListenerMulticaster implements CommandListener {
    private static final Logger LOGGER = Loggers.getLogger("protocol.event");

    private final List<CommandListener> commandListeners;

    CommandListenerMulticaster(final List<CommandListener> commandListeners) {
        isTrue("All CommandListener instances are non-null", !commandListeners.contains(null));
        this.commandListeners = new ArrayList<>(commandListeners);
    }

    @Override
    public void commandStarted(final CommandStartedEvent event) {
        for (CommandListener cur : commandListeners) {
            try {
                cur.commandStarted(event);
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn(format("Exception thrown raising command started event to listener %s", cur), e);
                }
            }
        }
    }

    @Override
    public void commandSucceeded(final CommandSucceededEvent event) {
        for (CommandListener cur : commandListeners) {
            try {
                cur.commandSucceeded(event);
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn(format("Exception thrown raising command succeeded event to listener %s", cur), e);
                }
            }
        }
    }

    @Override
    public void commandFailed(final CommandFailedEvent event) {
        for (CommandListener cur : commandListeners) {
            try {
                cur.commandFailed(event);
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn(format("Exception thrown raising command failed event to listener %s", cur), e);
                }
            }
        }
    }
}


text:
from __future__ import print_function

import cx_Oracle
import db_config

con = cx_Oracle.connect(db_config.user, db_config.pw, db_config.dsn)

print(cx_Oracle.version)
print("Database version:", con.version)
print("Client version:", cx_Oracle.clientversion())