text:
package org.apache.hadoop.hdfs.nfs.nfs3;

import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.nfs.conf.NfsConfiguration;
import org.apache.hadoop.hdfs.nfs.nfs3.Nfs3;
import org.apache.hadoop.hdfs.nfs.nfs3.RpcProgramNfs3;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.nfs.nfs3.FileHandle;
import org.apache.hadoop.nfs.nfs3.response.READDIR3Response;
import org.apache.hadoop.nfs.nfs3.response.READDIR3Response.Entry3;
import org.apache.hadoop.nfs.nfs3.response.READDIRPLUS3Response;
import org.apache.hadoop.nfs.nfs3.response.READDIRPLUS3Response.EntryPlus3;
import org.apache.hadoop.oncrpc.RpcInfo;
import org.apache.hadoop.oncrpc.RpcMessage;
import org.apache.hadoop.oncrpc.XDR;
import org.apache.hadoop.oncrpc.security.SecurityHandler;
import org.apache.hadoop.security.authorize.DefaultImpersonationProvider;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;

/**
 * Test READDIR and READDIRPLUS request with zero, nonzero cookies
 */
public class TestReaddir {

  static NfsConfiguration config = new NfsConfiguration();
  static MiniDFSCluster cluster = null;
  static DistributedFileSystem hdfs;
  static NameNode nn;
  static RpcProgramNfs3 nfsd;
  static String testdir = "/tmp";
  static SecurityHandler securityHandler;

  @BeforeClass
  public static void setup() throws Exception {
    String currentUser = System.getProperty("user.name");
    config.set(
            DefaultImpersonationProvider.getProxySuperuserGroupConfKey(currentUser),
            "*");
    config.set(
            DefaultImpersonationProvider.getProxySuperuserIpConfKey(currentUser),
            "*");
    ProxyUsers.refreshSuperUserGroupsConfiguration(config);
    cluster = new MiniDFSCluster.Builder(config).numDataNodes(1).build();
    cluster.waitActive();
    hdfs = cluster.getFileSystem();
    nn = cluster.getNameNode();

    // Use emphral port in case tests are running in parallel
    config.setInt("nfs3.mountd.port", 0);
    config.setInt("nfs3.server.port", 0);

    // Start nfs
    Nfs3 nfs3 = new Nfs3(config);
    nfs3.startServiceInternal(false);

    nfsd = (RpcProgramNfs3) nfs3.getRpcProgram();

    securityHandler = Mockito.mock(SecurityHandler.class);
    Mockito.when(securityHandler.getUser()).thenReturn(
        System.getProperty("user.name"));
  }

  @AfterClass
  public static void shutdown() throws Exception {
    if (cluster != null) {
      cluster.shutdown();
    }
  }

  @Before
  public void createFiles() throws IllegalArgumentException, IOException {
    hdfs.delete(new Path(testdir), true);
    hdfs.mkdirs(new Path(testdir));
    DFSTestUtil.createFile(hdfs, new Path(testdir + "/f1"), 0, (short) 1, 0);
    DFSTestUtil.createFile(hdfs, new Path(testdir + "/f2"), 0, (short) 1, 0);
    DFSTestUtil.createFile(hdfs, new Path(testdir + "/f3"), 0, (short) 1, 0);
  }

  @Test
  public void testReaddirBasic() throws IOException {
    // Get inodeId of /tmp
    HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
    long dirId = status.getFileId();

    // Create related part of the XDR request
    XDR xdr_req = new XDR();
    FileHandle handle = new FileHandle(dirId);
    handle.serialize(xdr_req);
    xdr_req.writeLongAsHyper(0); // cookie
    xdr_req.writeLongAsHyper(0); // verifier
    xdr_req.writeInt(100); // count

    READDIR3Response response = nfsd.readdir(xdr_req.asReadOnlyWrap(),
        securityHandler, new InetSocketAddress("localhost", 1234));
    List<Entry3> dirents = response.getDirList().getEntries();
    assertTrue(dirents.size() == 5); // inculding dot, dotdot

    // Test start listing from f2
    status = nn.getRpcServer().getFileInfo(testdir + "/f2");
    long f2Id = status.getFileId();

    // Create related part of the XDR request
    xdr_req = new XDR();
    handle = new FileHandle(dirId);
    handle.serialize(xdr_req);
    xdr_req.writeLongAsHyper(f2Id); // cookie
    xdr_req.writeLongAsHyper(0); // verifier
    xdr_req.writeInt(100); // count

    response = nfsd.readdir(xdr_req.asReadOnlyWrap(), securityHandler,
        new InetSocketAddress("localhost", 1234));
    dirents = response.getDirList().getEntries();
    assertTrue(dirents.size() == 1);
    Entry3 entry = dirents.get(0);
    assertTrue(entry.getName().equals("f3"));

    // When the cookie is deleted, list starts over no including dot, dotdot
    hdfs.delete(new Path(testdir + "/f2"), false);

    response = nfsd.readdir(xdr_req.asReadOnlyWrap(), securityHandler,
        new InetSocketAddress("localhost", 1234));
    dirents = response.getDirList().getEntries();
    assertTrue(dirents.size() == 2); // No dot, dotdot
  }

  @Test
  // Test readdirplus
  public void testReaddirPlus() throws IOException {
    // Get inodeId of /tmp
    HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
    long dirId = status.getFileId();

    // Create related part of the XDR request
    XDR xdr_req = new XDR();
    FileHandle handle = new FileHandle(dirId);
    handle.serialize(xdr_req);
    xdr_req.writeLongAsHyper(0); // cookie
    xdr_req.writeLongAsHyper(0); // verifier
    xdr_req.writeInt(100); // dirCount
    xdr_req.writeInt(1000); // maxCount

    READDIRPLUS3Response responsePlus = nfsd.readdirplus(xdr_req
        .asReadOnlyWrap(), securityHandler, new InetSocketAddress("localhost",
        1234));
    List<EntryPlus3> direntPlus = responsePlus.getDirListPlus().getEntries();
    assertTrue(direntPlus.size() == 5); // including dot, dotdot

    // Test start listing from f2
    status = nn.getRpcServer().getFileInfo(testdir + "/f2");
    long f2Id = status.getFileId();

    // Create related part of the XDR request
    xdr_req = new XDR();
    handle = new FileHandle(dirId);
    handle.serialize(xdr_req);
    xdr_req.writeLongAsHyper(f2Id); // cookie
    xdr_req.writeLongAsHyper(0); // verifier
    xdr_req.writeInt(100); // dirCount
    xdr_req.writeInt(1000); // maxCount

    responsePlus = nfsd.readdirplus(xdr_req.asReadOnlyWrap(), securityHandler,
        new InetSocketAddress("localhost", 1234));
    direntPlus = responsePlus.getDirListPlus().getEntries();
    assertTrue(direntPlus.size() == 1);
    EntryPlus3 entryPlus = direntPlus.get(0);
    assertTrue(entryPlus.getName().equals("f3"));

    // When the cookie is deleted, list starts over no including dot, dotdot
    hdfs.delete(new Path(testdir + "/f2"), false);

    responsePlus = nfsd.readdirplus(xdr_req.asReadOnlyWrap(), securityHandler,
        new InetSocketAddress("localhost", 1234));
    direntPlus = responsePlus.getDirListPlus().getEntries();
    assertTrue(direntPlus.size() == 2); // No dot, dotdot
  }
}


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Diagn. pl. orient. ser. 2, 1:99. 1854

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<ruleset name="AppleApnPush Tests code standard">
    <!-- Include Symfony2 Standard -->
    <rule ref="../vendor/escapestudios/symfony2-coding-standard/Symfony/">
        <exclude name="Symfony.Commenting.ClassComment.Missing"/>
        <exclude name="Symfony.Commenting.Annotations"/>
        <exclude name="Symfony.Functions.ScopeOrder"/>
    </rule>
</ruleset>


text:
class SpreadsheetCell
{
public:
	SpreadsheetCell();
	virtual ~SpreadsheetCell();

	virtual void set(const std::string& inString) = 0;

	virtual std::string getString() const = 0;
};

#endif


text:
class Gdb < Formula
  desc "GNU debugger"
  homepage "https://www.gnu.org/software/gdb/"
  url "https://ftp.gnu.org/gnu/gdb/gdb-9.2.tar.xz"
  mirror "https://ftpmirror.gnu.org/gdb/gdb-9.2.tar.xz"
  sha256 "360cd7ae79b776988e89d8f9a01c985d0b1fa21c767a4295e5f88cb49175c555"
  license "GPL-2.0"
  revision 1
  head "https://sourceware.org/git/binutils-gdb.git"

  livecheck do
    url :stable
  end

  bottle do
    sha256 "fbfb5bb6a5f8d7edb33937ebd505fbfe5074db3d49a0403803edafcbcbde297f" => :catalina
    sha256 "64fdeef2403ae8dad106d4933dc6b5c555d560249a18dccc0a518c53f8ea26b1" => :mojave
    sha256 "cbf828704099f07e8c863c962ef8deb60b932e3d75146a16b20967e3ddca7cbe" => :high_sierra
  end

  depends_on "python@3.8"
  depends_on "xz" # required for lzma support

  uses_from_macos "expat"
  uses_from_macos "ncurses"

  on_linux do
    depends_on "pkg-config" => :build
    depends_on "guile"
  end

  conflicts_with "i386-elf-gdb", because: "both install include/gdb, share/gdb and share/info"

  fails_with :clang do
    build 800
    cause <<~EOS
      probe.c:63:28: error: default initialization of an object of const type
      'const any_static_probe_ops' without a user-provided default constructor
    EOS
  end

  def install
    args = %W[
      --enable-targets=all
      --prefix=#{prefix}
      --disable-debug
      --disable-dependency-tracking
      --with-lzma
      --with-python=#{Formula["python@3.8"].opt_bin}/python3
      --disable-binutils
    ]

    mkdir "build" do
      system "../configure", *args
      system "make"

      # Don't install bfd or opcodes, as they are provided by binutils
      system "make", "install-gdb"
    end
  end

  def caveats
    <<~EOS
      gdb requires special privileges to access Mach ports.
      You will need to codesign the binary. For instructions, see:

        https://sourceware.org/gdb/wiki/BuildingOnDarwin

      On 10.12 (Sierra) or later with SIP, you need to run this:

        echo "set startup-with-shell off" >> ~/.gdbinit
    EOS
  end

  test do
    system bin/"gdb", bin/"gdb", "-configuration"
  end
end


text:
{% extends "base.html" %}

{% block subtitle %}Blog{% endblock %}

{% block content %}

{% for blog in xml %}

{{blog['title'][ 0 ]}}

{{blog['date'][ 0 ]}}

    {% for image in blog['image'] %}

    {% if not loop.last %}

    {% endif %}
    {% endfor %}

    {{blog['text'][ 0 ] | safe}}

{% endfor %}

{% endblock %}

{% block js %}

{% endblock %}


text:
<?php

declare(strict_types=1);

use Rector\CodingStyle\Rector\ArrowFunction\StaticArrowFunctionRector;
use Rector\CodingStyle\Rector\Closure\StaticClosureRector;
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->sets([
        SetList::DEAD_CODE,
        SetList::CODING_STYLE,
        SetList::CODE_QUALITY,
        SetList::EARLY_RETURN,
        SetList::NAMING,
        LevelSetList::UP_TO_PHP_80,
        SetList::TYPE_DECLARATION,
        SetList::TYPE_DECLARATION_STRICT,
    ]);

    $rectorConfig->paths([
        __DIR__ . '/config',
        __DIR__ . '/src',
        __DIR__ . '/spec',
        __DIR__ . '/rector.php',
    ]);
    $rectorConfig->importNames();

    $rectorConfig->skip([
        StaticArrowFunctionRector::class => [
            __DIR__ . '/spec',
        ],
        StaticClosureRector::class       => [
            __DIR__ . '/spec',
        ],
    ]);
};


text:
class dtkConnectivityThresholdNodePrivate
{
public:
    dtkComposerTransmitterReceiver<double>     minSize;
    dtkComposerTransmitterReceiver<dtkImage *> image;

    dtkComposerTransmitterEmitter<dtkImage *>  resImage;
};

// /////////////////////////////////////////////////////////////////
// dtkConnectivityThresholdNode
// /////////////////////////////////////////////////////////////////

dtkConnectivityThresholdNode::dtkConnectivityThresholdNode(void) : dtkComposerNodeObject<dtkAbstractConnectivityThreshold>(), d(new dtkConnectivityThresholdNodePrivate())
{
    this->setFactory(dtkImaging::filters::connectivityThreshold::pluginFactory());

    this->appendReceiver(&d->minSize);
    this->appendReceiver(&d->image);

    this->appendEmitter (&d->resImage);
}

dtkConnectivityThresholdNode::~dtkConnectivityThresholdNode(void)
{
    delete d;
}

void dtkConnectivityThresholdNode::run(void)
{
    if (d->minSize.isEmpty() || d->image.isEmpty()) {
        dtkError() << Q_FUNC_INFO << "Missing input. Aborting.";
        return;

    } else {

        dtkAbstractConnectivityThreshold *filter = this->object();
        if (!filter) {
            dtkError() << Q_FUNC_INFO << "No Connectivity Threshold filter found. Aborting.";
            return;
        }

        filter->setMinSize(d->minSize.constData());
        filter->setImage(d->image.data());
        filter->run();
        d->resImage.setData(filter->resImage());
    }
}

//
// dtkConnectivityThresholdNode.cpp ends here


text:
import os
import re
import string
from math import ceil
import sys
from PyQt4 import QtGui

class Converter():

    def main(self, folder):
        conFilePath, jpgPaths = self.read_folder_contents(folder)
        numFiles, splitCoords = self.read_con_file(conFilePath)
        resampled = self.resample_data(numFiles, splitCoords)
        self.print_new_files(numFiles, folder, jpgPaths, splitCoords)

    def read_folder_contents(self, folder):
        """ Reads in the contents of a folder and groups
        the sorted .jpg paths together in a list, and creates an
        object for the  .con file. The folder should contain *only* the
        relevant jpgs (tongue frames) and the single corresponding con file
        generated by EdgeTrak. """
        folder
        folderContents = os.listdir(folder)
        jpgPaths=[]
        for fileName in folderContents:                                         # this loop does the sorting of .con and .jpg files
            if '.con' in fileName:
                conFilePath = os.path.normpath(os.path.join(folder, fileName))
            if ".jpg" in fileName:
                jpgPaths.append(os.path.splitext(fileName)[0])
            else:
                pass
        jpgPaths = sorted(jpgPaths)                                             # sort the .jpg paths because the .con file columns
                                                                                # are ordered according to the jpg filenames
        return conFilePath, jpgPaths

    def read_con_file(self, conFilePath):
        """Reads in a .con file, returns the list self.splitCoords,
        which is a list of the coordinates generated by EdgeTrak and then
        split according to the corresponding .jpg image"""
        conFile = open(conFilePath, 'r')                                        # read in the file
        conLines = conFile.readlines()                                          # create list with lines as elements
        conFile.close()
        numFiles = ((len(conLines[0].strip().split())) / 2)                     # count number of columns in file and divide by 2
                                                                                # (since 2 columns to each image file)
        splitCoords = [[] for i in range(numFiles)]                             # create list to append paired coordinates for
                                                                                # each image file
        for line in conLines:
            i=0
            coords = line.strip().split()
            for sublist in splitCoords:                                         # each sublist corresponds to an image file
                                                                                # (tongue frame)
                sublist.append((coords[(2*i)], coords[(2*i)+1]))                # the input .con file has paired columns from left
                i+=1                                                            # to right (1,2), (3,4), (5,6)..., and this assigns
                                                                                # each pair to a tuple
                                                                                # and the tuple to its own sublist on splitCoord
        return numFiles, splitCoords

    def resample_data(self, numFiles, splitCoords, resampleTo = 32):
        """ Used to get the EdgeTrak data compatable with
        AutoTrace, which handles 32 points per traced image. """
        for i in range(numFiles):
            origLength = len(splitCoords[i])                                    # original length of the .con file columns
                                                                                # (ie the number of traced points)
            if  origLength > resampleTo:
                resampled = []
                for j in range(resampleTo):
                    resampled.append(splitCoords[i][int(ceil(j *
                                            origLength / resampleTo))])         # walk down the array of tuples (coordinates)
                                                                                # in an evenly-spaced manner
                splitCoords[i]=resampled

            else:
                pass
        return resampled

    def print_new_files(self, numFiles, folder, jpgPaths, splitCoords):
        """ Print out a new file for each .jpg tongue image,
        using the filename of each .jpg to create the filename for the
        corresponding .txt file. """
        for fileNum in range(numFiles):
            outFile= open(folder + '/output_' +
                          str(jpgPaths[fileNum]) + '.txt' , 'w')
            i=0
            for item in splitCoords[fileNum]:
                i+=1
                outFile.write(str(i) + '\t'  + str(item[0]) +
                                  '\t' + str(item[1]) + '\n')                   # write line in the new file with tab delimiting


text:
var MOPSO = function(problems, maxGens, particleCount) {
  var self = this;
  var callbacks = [];

  function callback() {
    callbacks.forEach(function(x) { x(); });
  }

  this.onUpdate = function(callback) {
    callbacks.push(callback);
  };

  var tuning = {
    w: 0.5, // inertia
    c1: 1.49, // coefficient of self-recognition component
    c2: 1.49, // coefficient of social component
    r1: Math.random(),
    r2: Math.random()
  };
  var currentGen = 0;

  var psos = [];
  var paretoFront = [];
  var paretoInputs = [];
  var currentLeaderIdx;

  function dominates(x, y) {
    return x[0] < y[0] && x[1] < y[1];
  }

  function updateParetoFront() {
    var pos1 = getRows(psos[0].getPositions());
    var pos2 = getRows(psos[1].getPositions());
    var pos = zip(pos1, pos2);
    var zs = zip(pos1.map(problems[0].fn), pos2.map(problems[1].fn));

    var newFront = [];
    var newFrontInputs = [];

    var f = function(x, y, inputs, oldInputs) {
      for(var i = 0; i < x.length; i++) {
        var dominated = false;
        for(var j = 0; j < y.length; j++) {
          if(!(x[i] && y[j])) continue;

          if(dominates(y[j], x[i])) {
            dominated = true;
            break;
          }
          else if(dominates(x[i], y[j])) {
            delete y[j];
            delete oldInputs[j];
          }
        }

        if(!dominated) {
          newFront.push(x[i]);
          newFrontInputs.push(inputs[i]);
        }
      }
    };

    f(zs, paretoFront, pos, paretoInputs);
    f(paretoFront, newFront, paretoInputs, newFrontInputs);

    paretoFront = newFront.filter(function(x) { return x; });
    paretoInputs = newFrontInputs.filter(function(x) { return x; });
  }

  var updater = function(idx) {
    var fn = problems[idx].fn;

    this.getGBest = function() {
      return paretoInputs[currentLeaderIdx][idx];
    };

    this.getPBest = function() {
      var bests = psos[idx].getParticleBests().elements;
      var current = psos[idx].getPositions().elements;

      var bestzs = bests.map(fn);
      var zs = current.map(fn);

      var rows = [];

      for(var i = 0; i < zs.length; i++) {
        if(zs[i] < bestzs[i]) {
          rows.push(current[i]);
        }
        else {
          rows.push(bests[i]);
        }
      }

      return Matrix.create(rows);
    };
  };

  this.step = function() {
    if(currentGen < maxGens) {
      currentLeaderIdx = Math.floor(Math.random() * paretoFront.length);
      psos.forEach(function(x) { x.step(); });
      updateParetoFront();

      callback();
      currentGen += 1;
    }
  };

  this.run = function() {
    if(currentGen < maxGens) {
      self.step();
      setTimeout(self.run, 100);
    }
  };

  this.getPSOs = function() {
    return psos;
  };

  this.getParetoFront = function() {
    return paretoFront;
  };

  (function initialize() {
    var i;
    for(i = 0; i < problems.length; i++) {
      psos.push(new PSO(problems[i], maxGens, particleCount, tuning));
    }
    updateParetoFront();
    for(i = 0; i < problems.length; i++) {
      psos[i].setUpdater(new updater(i));
    }
  })();
};


text:
<?php  include("../lib/functions.php"); ?>

Registro de Sede de Escuelas Profesionales

<form id="frm" action="index.php" method="POST">
    <input type="hidden" name="controller" value="sedeescuela" />
    <input type="hidden" name="action" value="save" />

            <fieldset class="ui-corner-all" >
                    <legend>Datos</legend>
                    Codigo Sede:
                <input id="CodigoSedeEscuela" name="CodigoSedeEscuela" class="text ui-widget-content ui-corner-all" style=" width: 50px; text-align: left;" value="<?php echo $obj->CodigoSedeEscuela; ?>" readonly />

                Facultad:
                <?php echo $facultades; ?>

                Codigo Siga
                <input id="CodigoSiga" maxlength="100" name="CodigoSiga" class="text ui-widget-content ui-corner-all" style=" width: 50px; text-align: left;" value="<?php echo $obj->CodigoSiga; ?>" />

                Escuela:

                 <?php if($readonly==""){ ?>
                     <select id="CodigoEscuela" name="CodigoEscuela" class="ui-corner-all text ui-widget-content">
                          <option value="">...</option>
                             </select>
                                 <?php }
                                    else {
                                        echo $escuelaprofesional;
                                       }
                                        ?>

                Codigo Sira:
   		<input id="CodigoSira" name="CodSira" class="text ui-widget-content ui-corner-all" style=" width: 100px; text-align: left;" value="<?php echo $obj->CodigoSira; ?>"  />

                Sede:
                <?php echo $sedes; ?>

       </fieldset>

            <fieldset>

            <legend>Accion</legend>

                    GRABAR
                    ATRAS

                </fieldset>

</form>


text:
#ifndef TRANSLATIONUNIT_H
#define TRANSLATIONUNIT_H

#include "tokenengine.h"
#include "tokenstreamadapter.h"
#include "ast.h"
#include "codemodel.h"
#include "smallobject.h"
#include "cpplexer.h"
#include "parser.h"
#include "semantic.h"
#include <QSharedData>

QT_BEGIN_NAMESPACE

class TranslationUnitData : public QSharedData
{
public:
    TranslationUnitData(const TokenEngine::TokenSectionSequence &t)
    :tokens(t),  globalScope(0) {};
    TokenEngine::TokenSectionSequence tokens;
    CodeModel::NamespaceScope *globalScope;
    TypedPool<CodeModel::Item> codeModelMemoryPool;
};

class TranslationUnit
{
public:
    TranslationUnit();
    TranslationUnit(const TokenEngine::TokenSectionSequence &tokens);
    TokenEngine::TokenSectionSequence tokens() const;
    CodeModel::NamespaceScope *codeModel();
    TypedPool<CodeModel::Item> *codeModelMemoryPool();
private:
    friend class TranslationUnitAnalyzer;
    void setCodeModel(CodeModel::NamespaceScope *globalScope);
    QExplicitlySharedDataPointer<TranslationUnitData> d;
};

class TranslationUnitAnalyzer
{
public:
    TranslationUnit analyze
            (const TokenEngine::TokenSectionSequence &translationUnitTokens, int targetMaxASTNodes = 10000);
private:
    CppLexer lexer;
    Parser parser;
};

QT_END_NAMESPACE

#endif


text:
<title>Output Section Fill - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Output-Section-Attributes.html#Output-Section-Attributes" title="Output Section Attributes">
<link rel="prev" href="Output-Section-Phdr.html#Output-Section-Phdr" title="Output Section Phdr">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

<link rel="stylesheet" type="text/css" href="../cs.css">

Previous: Output Section Phdr,
Up: Output Section Attributes

3.6.8.8 Output Section Fill

You can set the fill pattern for an entire section by using
‘<samp>=<var>fillexp</var></samp>’.  <var>fillexp</var> is an expression
(see Expressions).  Any otherwise unspecified regions of memory
within the output section (for example, gaps left due to the required
alignment of input sections) will be filled with the value, repeated as
necessary.  If the fill expression is a simple hex number, ie. a string
of hex digit starting with ‘<samp>0x</samp>’ and without a trailing ‘<samp>k</samp>’ or ‘<samp>M</samp>’, then
an arbitrarily long sequence of hex digits can be used to specify the
fill pattern;  Leading zeros become part of the pattern too.  For all
other cases, including extra parentheses or a unary +, the fill
pattern is the four least significant bytes of the value of the
expression.  In all cases, the number is big-endian.

You can also change the fill value with a FILL command in the
output section commands; (see Output Section Data).

Here is a simple example:

     SECTIONS { .text : { *(.text) } =0x90909090 }


text:
(function(){
	var self = window.utils = {};

	self.capitalize = function(aString) {
		return aString.charAt(0).toUpperCase() + aString.slice(1);
	};

})();


text:
package com.idylwood.utils;

import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;
import org.apache.commons.math3.linear.SingularValueDecomposition;

// Holder class for new stuff which hasn't had the dependencies gotten rid of yet.
public final class OptimizationUtils {

	private OptimizationUtils() {}

	/**
	 * Solves for Markowitz optimal portfolio by means of lagrange multiplier.
	 * Returns null if it does not exist (the matrix is singular)
	 * Otherwise it attempts to find the lowest variance portfolio for
	 * the given portfolio_return
	 * @param covariance Precalculated covariance matrix
	 * @param returns Precalculated vector of returns
	 * @param portfolio_return Return to optimize risk for
	 * @author Harry C Kim
	 * @return
	 */
	static final double[] MarkowitzSolve(final double[][] covariance, final double[] returns, final double portfolio_return)
	{
		if (covariance.length!=covariance[0].length)
			throw new IllegalArgumentException("Covariance needs to be square matrix");
		if (returns.length!=covariance.length)
			throw new IllegalArgumentException("Returns must be same length as covariance");

		/*
		for (int i = 0; i < covariance.length; i++)
			MathUtils.printArray(covariance[i]);
		System.out.println();
		MathUtils.printArray(returns);
		System.out.println();
		*/

		final int timePoints = covariance.length;
		final double[][] lagrangeMatrix = new double[timePoints+2][timePoints+2];
		//b as in Ax = b
		final double[] b = new double[timePoints+2];
		for(int i = 0; i < timePoints; i++)
		{
			for(int j = 0; j < timePoints; j++)
			{
				lagrangeMatrix[i][j] = 2*covariance[i][j];
				b[i] = 0;
				// this is like riskTolerance*returns[i]; but since
				// returns[i]*weights[i] = portfolio_return it will go away in the derivative
			}
		}

		for(int j = 0; j<timePoints; j++)
		{
			lagrangeMatrix[timePoints][j] = returns[j];
			lagrangeMatrix[timePoints+1][j] = 1;
			lagrangeMatrix[j][timePoints] = returns[j];
			lagrangeMatrix[j][timePoints+1] = 1;
		}
		b[timePoints] = portfolio_return; //**** what is the constraint on total expected return?
		b[timePoints + 1] = 1;

		/*
		// Print out lagrangeMatrix augmented with b vector
		for(int i=0; i<timePoints+2; i++)
		{
			for(int j=0; j<timePoints+2;j++)
			{
				System.out.print(lagrangeMatrix[i][j] + " ");
			}
			System.out.println(b[i]);
		}
		*/
		// TODO use Gaussian elimination solver, may be faster
		// TODO maybe refactor to use idylblas
		RealMatrix lagrangeReal = MatrixUtils.createRealMatrix(lagrangeMatrix);
		RealVector bReal = MatrixUtils.createRealVector(b);
		SingularValueDecomposition svd = new SingularValueDecomposition(lagrangeReal);

		if (!svd.getSolver().isNonSingular())
			return null;

		RealVector solution = svd.getSolver().solve(bReal);

		final double weights[] = new double[timePoints];

		// last two elements of solution are just lagrange multipliers
		for (int i = 0; i < weights.length; i++)
			weights[i] = solution.getEntry(i);

		// put these in some test class
		if (!MathUtils.fuzzyEquals(1,MathUtils.sum(weights)))
			throw new RuntimeException();
		if (!MathUtils.fuzzyEquals(portfolio_return,MathUtils.linearCombination(returns, weights)))
			throw new RuntimeException();
		//The following calculates the risk(variance) for the weights found
		// final double risk = MathUtils.linearCombination(MathUtils.matrixMultiply(covariance, weights),weights);
		return weights;
	}

/*
	private static final class MarkowitzFunction implements org.apache.commons.math3.analysis.MultivariateFunction
	{
		final double[][] S;
		final double[]R;
		final double q;
		MarkowitzFunction(final double[][] S, final double[]R, final double q)
		{
			this.S = S; this.R = R; this.q = q;
		}
		// this is gonna be so effing slow! haha
		// see http://en.wikipedia.org/wiki/Modern_portfolio_theory
		@Override public final double value(double[] w)
		// w weights, S cov matrix, R expected returns, q risk tolerance
		{
			final double foo = MathUtils.linearCombination(w,MathUtils.matrixMultiply(S,w));
			final double bar = MathUtils.linearCombination(R,w) * q;
			return foo - bar;
		}
	}
	// TODO make this work
	static final double[] cvxSolve(final double[][] S, final double []R, final double q)
	{
		ObjectiveFunction f = new ObjectiveFunction(new MarkowitzFunction(S,R,q));
		final double[] startPoint = new double[S.length];
		java.util.Arrays.fill(startPoint,1.0/S.length);

		final double[] ret =
			new NonLinearConjugateGradientOptimizer(
					NonLinearConjugateGradientOptimizer.Formula.FLETCHER_REEVES,
					new SimpleValueChecker(.1,.1)
				)
			.optimize(f,
					GoalType.MINIMIZE,
					new InitialGuess(startPoint)
				)
			.getPoint();
		return ret;
	}

	// returns double[] x such that T(c)*x is maximized, A*x <= b, and x>=0
	// TODO debug!
	static final double[] lpSolve(final double[][] A, final double[] b, final double[] c)
	{
		// TODO implement Feynman's simplex solver!
		// all apache stuff
		LinearObjectiveFunction f = new LinearObjectiveFunction(c, 0);
		List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(A.length);
		for (int i = 0; i < A.length; ++i)
			constraints.add(new LinearConstraint(A[i],Relationship.GEQ,b[i]));

		final double ret[] = new SimplexSolver()
			.optimize(f,
					new LinearConstraintSet(constraints),
					GoalType.MINIMIZE,
					new NonNegativeConstraint(false),
					new MaxIter(100)
				 )
			.getPoint();

		return ret;
	}
	*/

}


text:
<audio src="sounds/mario_pipe.mp3" controls></audio>
<audio src="sounds/zelda_secret.mp3" controls></audio>
<audio src="sounds/sonic_rings_lost.mp3" controls></audio>
<audio src="sounds/pacman_death.mp3" controls></audio>
<audio src="sounds/megaman_death.mp3" controls></audio>

--

# Sounds are Hard

--

# My Perspective

![Frozen JS](img/frozen.png)

--

# Let's Look At

* WebAudio vs HTML5 Audio
* Codecs
* Mobile


text:
package model;

public class Transfer {
	private String address;
	private Long amount;

	public void setAddress(Account account){
		this.address = account.getAddress();
	}
	public String getAddress(){
		return address;
	}
	public void setAmount(Long amount){
		this.amount = amount;
	}
	public Long getAmount(){
		return amount;
	}
}


text:
package org.apache.camel.component.salesforce.internal.processor;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.ZoneId;
import java.time.ZonedDateTime;

import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.component.salesforce.SalesforceComponent;
import org.apache.camel.component.salesforce.SalesforceEndpoint;
import org.apache.camel.component.salesforce.SalesforceEndpointConfig;
import org.apache.camel.component.salesforce.api.SalesforceException;
import org.apache.camel.component.salesforce.api.dto.AbstractDTOBase;
import org.apache.camel.component.salesforce.internal.OperationName;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.DefaultExchange;
import org.apache.camel.support.DefaultMessage;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class JsonRestProcessorTest {

    static class TestObject extends AbstractDTOBase {

        private ZonedDateTime creationDate;

        public ZonedDateTime getCreationDate() {
            return creationDate;
        }

        public void setCreationDate(final ZonedDateTime creationDate) {
            this.creationDate = creationDate;
        }
    }

    @Test
    public void byDefaultItShouldNotSerializeNullValues() throws SalesforceException, IOException {
        final SalesforceComponent salesforce = new SalesforceComponent();
        final SalesforceEndpointConfig configuration = new SalesforceEndpointConfig();
        final SalesforceEndpoint endpoint = new SalesforceEndpoint("", salesforce, configuration,
            OperationName.UPDATE_SOBJECT, "");

        final JsonRestProcessor jsonProcessor = new JsonRestProcessor(endpoint);

        final Message in = new DefaultMessage(new DefaultCamelContext());
        try (InputStream stream = jsonProcessor.getRequestStream(in, new TestObject());
            InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
            final String json = IOUtils.toString(reader);

            assertThat(json).isEqualTo("{}");
        }
    }

    @Test
    public void getRequestStream() throws Exception {
        final SalesforceComponent comp = new SalesforceComponent();
        final SalesforceEndpointConfig conf = new SalesforceEndpointConfig();
        final OperationName op = OperationName.CREATE_BATCH;
        final SalesforceEndpoint endpoint = new SalesforceEndpoint("", comp, conf, op, "");
        final JsonRestProcessor jsonRestProcessor = new JsonRestProcessor(endpoint);
        final DefaultCamelContext context = new DefaultCamelContext();
        final Exchange exchange = new DefaultExchange(context, ExchangePattern.InOut);
        final TestObject doc = new TestObject();
        doc.setCreationDate(ZonedDateTime.of(1717, 1, 2, 3, 4, 5, 6, ZoneId.systemDefault()));

        exchange.getIn().setBody(doc);
        try (InputStream stream = jsonRestProcessor.getRequestStream(exchange);
            InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
            final String result = IOUtils.toString(reader);
            assertThat(result.length()).isLessThanOrEqualTo(48);
        }
    }

    @Test
    public void shouldSerializeNullValuesViaEndpointConfiguration() throws SalesforceException, IOException {
        final SalesforceComponent salesforce = new SalesforceComponent();
        final SalesforceEndpointConfig configuration = new SalesforceEndpointConfig();
        configuration.setSerializeNulls(true);
        final SalesforceEndpoint endpoint = new SalesforceEndpoint("", salesforce, configuration,
            OperationName.UPDATE_SOBJECT, "");

        final JsonRestProcessor jsonProcessor = new JsonRestProcessor(endpoint);

        final Message in = new DefaultMessage(new DefaultCamelContext());
        try (InputStream stream = jsonProcessor.getRequestStream(in, new TestObject());
            InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
            final String json = IOUtils.toString(reader);

            assertThat(json).isEqualTo("{\"creationDate\":null}");
        }
    }

    @Test
    public void shouldSerializeNullValuesViaHeaderConfiguration() throws SalesforceException, IOException {
        final SalesforceComponent salesforce = new SalesforceComponent();
        final SalesforceEndpointConfig configuration = new SalesforceEndpointConfig();
        final SalesforceEndpoint endpoint = new SalesforceEndpoint("", salesforce, configuration,
            OperationName.UPDATE_SOBJECT, "");

        final JsonRestProcessor jsonProcessor = new JsonRestProcessor(endpoint);

        final Message in = new DefaultMessage(new DefaultCamelContext());
        in.setHeader(SalesforceEndpointConfig.SERIALIZE_NULLS, true);
        try (InputStream stream = jsonProcessor.getRequestStream(in, new TestObject());
            InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
            final String json = IOUtils.toString(reader);

            assertThat(json).isEqualTo("{\"creationDate\":null}");
        }
    }
}


text:
<?php

namespace Organo\Test\Unitario\v1\Repositorios;

use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
use Organo\v1\Repositorios\Usuario;
use PHPUnit\Framework\TestCase;

class UsuarioTest extends TestCase
{

    public function setUp()
    {
        $this->conn = DriverManager::getConnection([
            'driver' => getenv('ORGANO_DB_DRIVER'),
            'host' => getenv('ORGANO_DB_SERVIDOR'),
            'port' => getenv('ORGANO_DB_PORTA'),
            'dbname' => getenv('ORGANO_DB_NOME'),
            'user' => getenv('ORGANO_DB_USUARIO'),
            'password' => getenv('ORGANO_DB_SENHA')
        ], new Configuration());
    }

    public function testInserirDados()
    {
        $usuario = ['nome' => 'Vinicius Guedes'];
        $resultado = (new Usuario($this->conn))
            ->inserir($usuario);

        $this->assertTrue($resultado);
        $this->assertArrayHasKey('id', $usuario);
    }

    public function testErroAoInserirDados()
    {
        $usuario = ['status' => 0];

        $repositorio = new Usuario($this->conn);

        $this->assertFalse($repositorio->inserir($usuario));
    }

    public function testContaDados()
    {
        $repositorio = new Usuario($this->conn);
        $this->assertGreaterThanOrEqual(1, $repositorio->conta());
    }

    public function testConsultaUsuarioPorId()
    {
        $repositorio = new Usuario($this->conn);

        $usuario = $repositorio->obtem(1, 0)[0];
        $usuarioConsultado = $repositorio->obtemPorId($usuario['id']);

        $this->assertEquals($usuario['id'], $usuarioConsultado['id']);
    }

    public function testConsultaUsuarioInexistente()
    {
        $usuario = (new Usuario($this->conn))->obtemPorId(999);
        $this->assertNull($usuario);
    }

    public function testRemocaoDeDadosPorId()
    {
        $repositorio = new Usuario($this->conn);
        $usuario = $repositorio->obtem(1, 0)[0];

        $this->assertTrue($repositorio->removerPorId($usuario['id']));

        $resultado = $repositorio->remover(["id > ?"], [0]);
    }

}


text:
package org.apache.ambari.server.controller.internal;

import java.util.Set;

import org.apache.ambari.server.controller.spi.QueryResponse;
import org.apache.ambari.server.controller.spi.Resource;

/**
 * Simple {@link org.apache.ambari.server.controller.spi.QueryResponse} implementation.
 */
public class QueryResponseImpl implements QueryResponse {

  /**
   * The set of resources returned by the query.
   */
  private final Set<Resource> resources;

  /**
   * {@code true} if the response is sorted.
   */
  private final boolean sortedResponse;

  /**
   * {@code true} if the response is paginated.
   */
  private final boolean pagedResponse;

  /**
   * The total number of resources returned by the query.
   */
  private final int totalResourceCount;

  // ----- Constructors ------------------------------------------------------

  /**
   * Constructor.
   *
   * @param resources the set of resources returned by the query.
   */
  public QueryResponseImpl(Set<Resource> resources) {
    this.resources          = resources;
    this.sortedResponse     = false;
    this.pagedResponse      = false;
    this.totalResourceCount = 0;
  }

  /**
   * Constructor.
   *
   * @param resources           the set of resources returned by the query.
   * @param sortedResponse      indicates whether or not the response is sorted
   * @param pagedResponse       indicates whether or not the response is paged
   * @param totalResourceCount  the total number of resources returned by the query
   */
  public QueryResponseImpl(Set<Resource> resources, boolean sortedResponse,
                           boolean pagedResponse, int totalResourceCount) {
    this.resources          = resources;
    this.sortedResponse     = sortedResponse;
    this.pagedResponse      = pagedResponse;
    this.totalResourceCount = totalResourceCount;
  }

  // ----- QueryResponse -----------------------------------------------------

  @Override
  public Set<Resource> getResources() {
    return resources;
  }

  @Override
  public boolean isSortedResponse() {
    return sortedResponse;
  }

  @Override
  public boolean isPagedResponse() {
    return pagedResponse;
  }

  @Override
  public int getTotalResourceCount() {
    return totalResourceCount;
  }
}


text:
title: Ori and the Blind Forest
href: Ori_And_The_Blind_Forest
class: intest
subtitle: WAITING FOR TEST
layout: default
modal-id: 68
date: 2017-04-15
img: ori_and_the_blind_forest_gameplay.jpg
thumbnail: ori_and_the_blind_forest.jpg
alt: image-alt
game-date:
developer:
category:
multiplayer:
description: WORK IN PROGRESS
---


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: org.apache.http.impl.conn.DefaultClientConnectionOperator
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_IMPL_CONN_DEFAULTCLIENTCONNECTIONOPERATOR_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_IMPL_CONN_DEFAULTCLIENTCONNECTIONOPERATOR_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace net { class InetAddress; } } }
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpHost; } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace conn { class ClientConnectionOperator; } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace conn { class OperatedClientConnection; } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace conn { namespace scheme { class SchemeRegistry; } } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace params { class HttpParams; } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace protocol { class HttpContext; } } } } }

#include <java/lang/Object.hpp>
#include <java/net/InetAddress.hpp>
#include <org/apache/http/HttpHost.hpp>
#include <org/apache/http/conn/ClientConnectionOperator.hpp>
#include <org/apache/http/conn/OperatedClientConnection.hpp>
#include <org/apache/http/conn/scheme/SchemeRegistry.hpp>
#include <org/apache/http/params/HttpParams.hpp>
#include <org/apache/http/protocol/HttpContext.hpp>

namespace j2cpp {

namespace org { namespace apache { namespace http { namespace impl { namespace conn {

	class DefaultClientConnectionOperator;
	class DefaultClientConnectionOperator
		: public object<DefaultClientConnectionOperator>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_METHOD(4)
		J2CPP_DECLARE_FIELD(0)

		explicit DefaultClientConnectionOperator(jobject jobj)
		: object<DefaultClientConnectionOperator>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;
		operator local_ref<org::apache::http::conn::ClientConnectionOperator>() const;

		DefaultClientConnectionOperator(local_ref< org::apache::http::conn::scheme::SchemeRegistry > const&);
		local_ref< org::apache::http::conn::OperatedClientConnection > createConnection();
		void openConnection(local_ref< org::apache::http::conn::OperatedClientConnection >  const&, local_ref< org::apache::http::HttpHost >  const&, local_ref< java::net::InetAddress >  const&, local_ref< org::apache::http::protocol::HttpContext >  const&, local_ref< org::apache::http::params::HttpParams >  const&);
		void updateSecureConnection(local_ref< org::apache::http::conn::OperatedClientConnection >  const&, local_ref< org::apache::http::HttpHost >  const&, local_ref< org::apache::http::protocol::HttpContext >  const&, local_ref< org::apache::http::params::HttpParams >  const&);

	}; //class DefaultClientConnectionOperator

} //namespace conn
} //namespace impl
} //namespace http
} //namespace apache
} //namespace org

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_IMPL_CONN_DEFAULTCLIENTCONNECTIONOPERATOR_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_IMPL_CONN_DEFAULTCLIENTCONNECTIONOPERATOR_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_IMPL_CONN_DEFAULTCLIENTCONNECTIONOPERATOR_HPP_IMPL

namespace j2cpp {

org::apache::http::impl::conn::DefaultClientConnectionOperator::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

org::apache::http::impl::conn::DefaultClientConnectionOperator::operator local_ref<org::apache::http::conn::ClientConnectionOperator>() const
{
	return local_ref<org::apache::http::conn::ClientConnectionOperator>(get_jobject());
}

org::apache::http::impl::conn::DefaultClientConnectionOperator::DefaultClientConnectionOperator(local_ref< org::apache::http::conn::scheme::SchemeRegistry > const &a0)
: object<org::apache::http::impl::conn::DefaultClientConnectionOperator>(
	call_new_object<
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_CLASS_NAME,
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_NAME(0),
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_SIGNATURE(0)
	>(a0)
)
{
}

local_ref< org::apache::http::conn::OperatedClientConnection > org::apache::http::impl::conn::DefaultClientConnectionOperator::createConnection()
{
	return call_method<
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_CLASS_NAME,
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_NAME(1),
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_SIGNATURE(1),
		local_ref< org::apache::http::conn::OperatedClientConnection >
	>(get_jobject());
}

void org::apache::http::impl::conn::DefaultClientConnectionOperator::openConnection(local_ref< org::apache::http::conn::OperatedClientConnection > const &a0, local_ref< org::apache::http::HttpHost > const &a1, local_ref< java::net::InetAddress > const &a2, local_ref< org::apache::http::protocol::HttpContext > const &a3, local_ref< org::apache::http::params::HttpParams > const &a4)
{
	return call_method<
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_CLASS_NAME,
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_NAME(2),
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_SIGNATURE(2),
		void
	>(get_jobject(), a0, a1, a2, a3, a4);
}

void org::apache::http::impl::conn::DefaultClientConnectionOperator::updateSecureConnection(local_ref< org::apache::http::conn::OperatedClientConnection > const &a0, local_ref< org::apache::http::HttpHost > const &a1, local_ref< org::apache::http::protocol::HttpContext > const &a2, local_ref< org::apache::http::params::HttpParams > const &a3)
{
	return call_method<
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_CLASS_NAME,
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_NAME(3),
		org::apache::http::impl::conn::DefaultClientConnectionOperator::J2CPP_METHOD_SIGNATURE(3),
		void
	>(get_jobject(), a0, a1, a2, a3);
}

J2CPP_DEFINE_CLASS(org::apache::http::impl::conn::DefaultClientConnectionOperator,"org/apache/http/impl/conn/DefaultClientConnectionOperator")
J2CPP_DEFINE_METHOD(org::apache::http::impl::conn::DefaultClientConnectionOperator,0,"<init>","(Lorg/apache/http/conn/scheme/SchemeRegistry;)V")
J2CPP_DEFINE_METHOD(org::apache::http::impl::conn::DefaultClientConnectionOperator,1,"createConnection","()Lorg/apache/http/conn/OperatedClientConnection;")
J2CPP_DEFINE_METHOD(org::apache::http::impl::conn::DefaultClientConnectionOperator,2,"openConnection","(Lorg/apache/http/conn/OperatedClientConnection;Lorg/apache/http/HttpHost;Ljava/net/InetAddress;Lorg/apache/http/protocol/HttpContext;Lorg/apache/http/params/HttpParams;)V")
J2CPP_DEFINE_METHOD(org::apache::http::impl::conn::DefaultClientConnectionOperator,3,"updateSecureConnection","(Lorg/apache/http/conn/OperatedClientConnection;Lorg/apache/http/HttpHost;Lorg/apache/http/protocol/HttpContext;Lorg/apache/http/params/HttpParams;)V")
J2CPP_DEFINE_METHOD(org::apache::http::impl::conn::DefaultClientConnectionOperator,4,"prepareSocket","(Ljava/net/Socket;Lorg/apache/http/protocol/HttpContext;Lorg/apache/http/params/HttpParams;)V")
J2CPP_DEFINE_FIELD(org::apache::http::impl::conn::DefaultClientConnectionOperator,0,"schemeRegistry","Lorg/apache/http/conn/scheme/SchemeRegistry;")

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_IMPL_CONN_DEFAULTCLIENTCONNECTIONOPERATOR_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
import { useCallback, useEffect, useMemo, useState, VFC } from 'react';
import { SortingRule, useFlexLayout, useSortBy, useTable } from 'react-table';
import { VirtualizedTable, TablePlaceholder } from 'component/common/Table';
import { styled, useMediaQuery, useTheme } from '@mui/material';
import { Add, Delete, Edit } from '@mui/icons-material';
import { sortTypes } from 'utils/sortTypes';
import useProjectAccess, {
    ENTITY_TYPE,
    IProjectAccess,
} from 'hooks/api/getters/useProjectAccess/useProjectAccess';
import PermissionIconButton from 'component/common/PermissionIconButton/PermissionIconButton';
import { UPDATE_PROJECT } from 'component/providers/AccessProvider/permissions';
import { TextCell } from 'component/common/Table/cells/TextCell/TextCell';
import { ActionCell } from 'component/common/Table/cells/ActionCell/ActionCell';
import { SearchHighlightProvider } from 'component/common/Table/SearchHighlightContext/SearchHighlightContext';
import { ConditionallyRender } from 'component/common/ConditionallyRender/ConditionallyRender';
import { useSearch } from 'hooks/useSearch';
import useHiddenColumns from 'hooks/useHiddenColumns';
import {
    Link,
    Route,
    Routes,
    useNavigate,
    useSearchParams,
} from 'react-router-dom';
import { createLocalStorage } from 'utils/createLocalStorage';
import { HighlightCell } from 'component/common/Table/cells/HighlightCell/HighlightCell';
import { TimeAgoCell } from 'component/common/Table/cells/TimeAgoCell/TimeAgoCell';
import { PageContent } from 'component/common/PageContent/PageContent';
import { PageHeader } from 'component/common/PageHeader/PageHeader';
import { Search } from 'component/common/Search/Search';
import useProjectApi from 'hooks/api/actions/useProjectApi/useProjectApi';
import useToast from 'hooks/useToast';
import { Dialogue } from 'component/common/Dialogue/Dialogue';
import useUiConfig from 'hooks/api/getters/useUiConfig/useUiConfig';
import { ProjectGroupView } from '../ProjectGroupView/ProjectGroupView';
import { useRequiredPathParam } from 'hooks/useRequiredPathParam';
import { IUser } from 'interfaces/user';
import { IGroup } from 'interfaces/group';
import { LinkCell } from 'component/common/Table/cells/LinkCell/LinkCell';
import { UserAvatar } from 'component/common/UserAvatar/UserAvatar';
import ResponsiveButton from 'component/common/ResponsiveButton/ResponsiveButton';
import { ProjectAccessCreate } from 'component/project/ProjectAccess/ProjectAccessCreate/ProjectAccessCreate';
import { ProjectAccessEditUser } from 'component/project/ProjectAccess/ProjectAccessEditUser/ProjectAccessEditUser';
import { ProjectAccessEditGroup } from 'component/project/ProjectAccess/ProjectAccessEditGroup/ProjectAccessEditGroup';
import { ProjectAccessRoleCell } from './ProjectAccessRoleCell/ProjectAccessRoleCell';
import {
    PA_ASSIGN_BUTTON_ID,
    PA_EDIT_BUTTON_ID,
    PA_REMOVE_BUTTON_ID,
} from 'utils/testIds';

export type PageQueryType = Partial<
    Record<'sort' | 'order' | 'search', string>
>;

const defaultSort: SortingRule<string> = { id: 'added' };

const { value: storedParams, setValue: setStoredParams } = createLocalStorage(
    'ProjectAccess:v1',
    defaultSort
);

const StyledUserAvatars = styled('div')(({ theme }) => ({
    display: 'inline-flex',
    alignItems: 'center',
    flexWrap: 'wrap',
    marginLeft: theme.spacing(1),
}));

const StyledEmptyAvatar = styled(UserAvatar)(({ theme }) => ({
    marginRight: theme.spacing(-3.5),
}));

const StyledGroupAvatar = styled(UserAvatar)(({ theme }) => ({
    outline: `${theme.spacing(0.25)} solid ${theme.palette.background.paper}`,
}));

const hiddenColumnsSmall = ['imageUrl', 'role', 'added', 'lastLogin'];
const hiddenColumnsMedium = ['lastLogin', 'added'];

export const ProjectAccessTable: VFC = () => {
    const projectId = useRequiredPathParam('projectId');

    const { uiConfig } = useUiConfig();
    const { flags } = uiConfig;
    const entityType = flags.UG ? 'user / group' : 'user';

    const navigate = useNavigate();
    const theme = useTheme();
    const isSmallScreen = useMediaQuery(theme.breakpoints.down('md'));
    const isMediumScreen = useMediaQuery(theme.breakpoints.down('lg'));
    const { setToastData } = useToast();

    const { access, refetchProjectAccess } = useProjectAccess(projectId);
    const { removeUserFromRole, removeGroupFromRole } = useProjectApi();
    const [removeOpen, setRemoveOpen] = useState(false);
    const [groupOpen, setGroupOpen] = useState(false);
    const [selectedRow, setSelectedRow] = useState<IProjectAccess>();

    const columns = useMemo(
        () => [
            {
                Header: 'Avatar',
                accessor: 'imageUrl',
                Cell: ({ row: { original: row } }: any) => (
                    <StyledUserAvatars>
                        <ConditionallyRender
                            condition={row.type === ENTITY_TYPE.GROUP}
                            show={<StyledEmptyAvatar />}
                        />
                        <StyledGroupAvatar user={row.entity}>
                            {row.entity.users?.length}
                        </StyledGroupAvatar>
                    </StyledUserAvatars>
                ),
                maxWidth: 85,
                disableSortBy: true,
            },
            {
                id: 'name',
                Header: 'Name',
                accessor: (row: IProjectAccess) => row.entity.name || '',
                Cell: ({ value, row: { original: row } }: any) => (
                    <ConditionallyRender
                        condition={row.type === ENTITY_TYPE.GROUP}
                        show={
                            <LinkCell
                                onClick={() => {
                                    setSelectedRow(row);
                                    setGroupOpen(true);
                                }}
                                title={value}
                                subtitle={`${row.entity.users?.length} users`}
                            />
                        }
                        elseShow={
                            <HighlightCell
                                value={value}
                                subtitle={
                                    row.entity?.username || row.entity?.email
                                }
                            />
                        }
                    />
                ),
                minWidth: 100,
                searchable: true,
            },
            {
                id: 'username',
                Header: 'Username',
                accessor: (row: IProjectAccess) => {
                    if (row.type === ENTITY_TYPE.USER) {
                        const userRow = row.entity as IUser;
                        return userRow.username || userRow.email;
                    }
                    return '';
                },
                Cell: HighlightCell,
                minWidth: 100,
                searchable: true,
            },
            {
                id: 'role',
                Header: 'Role',
                accessor: (row: IProjectAccess) =>
                    access?.roles.find(({ id }) => id === row.entity.roleId)
                        ?.name,
                Cell: ({ value, row: { original: row } }: any) => (
                    <ProjectAccessRoleCell
                        roleId={row.entity.roleId}
                        value={value}
                    />
                ),
                maxWidth: 125,
                filterName: 'role',
            },
            {
                id: 'added',
                Header: 'Added',
                accessor: (row: IProjectAccess) => {
                    const userRow = row.entity as IUser | IGroup;
                    return userRow.addedAt || '';
                },
                Cell: ({ value }: { value: Date }) => (
                    <TimeAgoCell value={value} emptyText="Never" />
                ),
                sortType: 'date',
                maxWidth: 100,
            },
            {
                id: 'lastLogin',
                Header: 'Last login',
                accessor: (row: IProjectAccess) => {
                    if (row.type === ENTITY_TYPE.USER) {
                        const userRow = row.entity as IUser;
                        return userRow.seenAt || '';
                    }
                    const userGroup = row.entity as IGroup;
                    return userGroup.users
                        .map(({ seenAt }) => seenAt)
                        .sort()
                        .reverse()[0];
                },
                Cell: ({ value }: { value: Date }) => (
                    <TimeAgoCell value={value} emptyText="Never" />
                ),
                sortType: 'date',
                maxWidth: 100,
            },
            {
                id: 'actions',
                Header: 'Actions',
                disableSortBy: true,
                align: 'center',
                maxWidth: 150,
                Cell: ({
                    row: { original: row },
                }: {
                    row: { original: IProjectAccess };
                }) => (
                    <ActionCell>
                        <PermissionIconButton
                            data-testid={PA_EDIT_BUTTON_ID}
                            component={Link}
                            permission={UPDATE_PROJECT}
                            projectId={projectId}
                            to={`edit/${
                                row.type === ENTITY_TYPE.USER ? 'user' : 'group'
                            }/${row.entity.id}`}
                            disabled={access?.rows.length === 1}
                            tooltipProps={{
                                title:
                                    access?.rows.length === 1
                                        ? 'Cannot edit access. A project must have at least one owner'
                                        : 'Edit access',
                            }}
                        >
                            <Edit />
                        </PermissionIconButton>
                        <PermissionIconButton
                            data-testid={PA_REMOVE_BUTTON_ID}
                            permission={UPDATE_PROJECT}
                            projectId={projectId}
                            onClick={() => {
                                setSelectedRow(row);
                                setRemoveOpen(true);
                            }}
                            disabled={access?.rows.length === 1}
                            tooltipProps={{
                                title:
                                    access?.rows.length === 1
                                        ? 'Cannot remove access. A project must have at least one owner'
                                        : 'Remove access',
                            }}
                        >
                            <Delete />
                        </PermissionIconButton>
                    </ActionCell>
                ),
            },
        ],
        [access, projectId]
    );

    const [searchParams, setSearchParams] = useSearchParams();
    const [initialState] = useState(() => ({
        sortBy: [
            {
                id: searchParams.get('sort') || storedParams.id,
                desc: searchParams.has('order')
                    ? searchParams.get('order') === 'desc'
                    : storedParams.desc,
            },
        ],
        globalFilter: searchParams.get('search') || '',
    }));
    const [searchValue, setSearchValue] = useState(initialState.globalFilter);

    const { data, getSearchText, getSearchContext } = useSearch(
        columns,
        searchValue,
        access?.rows ?? []
    );

    const {
        headerGroups,
        rows,
        prepareRow,
        setHiddenColumns,
        state: { sortBy },
    } = useTable(
        {
            columns: columns as any[],
            data,
            initialState,
            sortTypes,
            autoResetSortBy: false,
            disableSortRemove: true,
            disableMultiSort: true,
            defaultColumn: {
                Cell: TextCell,
            },
        },
        useSortBy,
        useFlexLayout
    );

    useHiddenColumns(setHiddenColumns, hiddenColumnsSmall, isSmallScreen);
    useHiddenColumns(setHiddenColumns, hiddenColumnsMedium, isMediumScreen);

    useEffect(() => {
        const tableState: PageQueryType = {};
        tableState.sort = sortBy[0].id;
        if (sortBy[0].desc) {
            tableState.order = 'desc';
        }
        if (searchValue) {
            tableState.search = searchValue;
        }

        setSearchParams(tableState, {
            replace: true,
        });
        setStoredParams({ id: sortBy[0].id, desc: sortBy[0].desc || false });
    }, [sortBy, searchValue, setSearchParams]);

    const removeAccess = async (userOrGroup?: IProjectAccess) => {
        if (!userOrGroup) return;
        const { id, roleId } = userOrGroup.entity;
        let name = userOrGroup.entity.name;
        if (userOrGroup.type === ENTITY_TYPE.USER) {
            const user = userOrGroup.entity as IUser;
            name = name || user.email || user.username || '';
        }

        try {
            if (userOrGroup.type === ENTITY_TYPE.USER) {
                await removeUserFromRole(projectId, roleId, id);
            } else {
                await removeGroupFromRole(projectId, roleId, id);
            }
            refetchProjectAccess();
            setToastData({
                type: 'success',
                title: `${
                    name || `The ${entityType}`
                } has been removed from project`,
            });
        } catch (err: any) {
            setToastData({
                type: 'error',
                title:
                    err.message ||
                    `Server problems when removing ${entityType}.`,
            });
        }
        setRemoveOpen(false);
    };

    return (
        <PageContent
            header={
                <PageHeader
                    secondary
                    title={`Access (${
                        rows.length < data.length
                            ? `${rows.length} of ${data.length}`
                            : data.length
                    })`}
                    actions={
                        <>
                            <ConditionallyRender
                                condition={!isSmallScreen}
                                show={
                                    <>
                                        <Search
                                            initialValue={searchValue}
                                            onChange={setSearchValue}
                                            hasFilters
                                            getSearchContext={getSearchContext}
                                        />
                                        <PageHeader.Divider />
                                    </>
                                }
                            />
                            <ResponsiveButton
                                onClick={() => navigate('create')}
                                maxWidth="700px"
                                Icon={Add}
                                permission={UPDATE_PROJECT}
                                projectId={projectId}
                                data-testid={PA_ASSIGN_BUTTON_ID}
                            >
                                Assign {entityType}
                            </ResponsiveButton>
                        </>
                    }
                >
                    <ConditionallyRender
                        condition={isSmallScreen}
                        show={
                            <Search
                                initialValue={searchValue}
                                onChange={setSearchValue}
                                hasFilters
                                getSearchContext={getSearchContext}
                            />
                        }
                    />
                </PageHeader>
            }
        >
            <SearchHighlightProvider value={getSearchText(searchValue)}>
                <VirtualizedTable
                    rows={rows}
                    headerGroups={headerGroups}
                    prepareRow={prepareRow}
                />
            </SearchHighlightProvider>
            <ConditionallyRender
                condition={rows.length === 0}
                show={
                    <ConditionallyRender
                        condition={searchValue?.length > 0}
                        show={
                            <TablePlaceholder>
                                No access found matching “
                                {searchValue}
                                ”
                            </TablePlaceholder>
                        }
                        elseShow={
                            <TablePlaceholder>
                                No access available. Get started by assigning a{' '}
                                {entityType}.
                            </TablePlaceholder>
                        }
                    />
                }
            />
            <Routes>
                <Route path="create" element={<ProjectAccessCreate />} />
                <Route
                    path="edit/group/:groupId"
                    element={<ProjectAccessEditGroup />}
                />
                <Route
                    path="edit/user/:userId"
                    element={<ProjectAccessEditUser />}
                />
            </Routes>
            <Dialogue
                open={removeOpen}
                onClick={() => removeAccess(selectedRow)}
                onClose={() => {
                    setRemoveOpen(false);
                }}
                title={`Really remove ${entityType} from this project?`}
            />
            <ProjectGroupView
                open={groupOpen}
                setOpen={setGroupOpen}
                group={selectedRow?.entity as IGroup}
                projectId={projectId}
                subtitle={`Role: ${
                    access?.roles.find(
                        ({ id }) => id === selectedRow?.entity.roleId
                    )?.name
                }`}
                onEdit={() => {
                    navigate(`edit/group/${selectedRow?.entity.id}`);
                }}
                onRemove={() => {
                    setGroupOpen(false);
                    setRemoveOpen(true);
                }}
            />
        </PageContent>
    );
};


text:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import './index.sass'

import 'normalize.css/normalize.css'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootswatch/flatly/bootstrap.css'

ReactDOM.render(
  <App />,
  document.getElementById('root')
)


text:
'use strict';

var commist = require('commist')
var registry = require('./registry')
var pull = require('./pull')
var fs = require('fs')
var path = require('path')

function cli(args) {
  var program = commist()

  program.register('registry', registry)
  program.register('pull', function(opts) {
    pull(opts, function(err) {
      if (err) {
        console.log(err)
        process.exit(1)
      }
      if (!opts.keep) {
        process.exit(0)
      }
    })
  })

  return program.parse(args)
}

if (require.main === module) {
  var remaining = cli(process.argv.splice(2))

  if (remaining) {
    fs.createReadStream(path.join(__dirname, 'docs', 'help.txt'))
      .pipe(process.stdout)
  }
}

module.exports = {
    pull: pull
  , registry: registry
  , cli: cli
}


text:
'use strict'

class Async {
  run (executors) {
    const args = Array.from(arguments).slice(1)
    return new Promise(resolve => resolve(executors.async.apply(null, args)))
  }

  all (arr) {
    return Promise.all(arr)
  }

  returns (value) {
    return Promise.resolve(value)
  }

  throws (reason) {
    return Promise.reject(reason)
  }
}
module.exports = Async


text:
require("prototypes.item.trading-chest")
require("prototypes.recipe.trading-chest")
require("prototypes.entity.trading-chest")
require("prototypes.technology.trading-chest")
--require("prototypes.scripts.item-credit-values")
--require("data-final-fixes")


text:
@extends('layouts.app')

@section('content')

修改密码

                        <form class="form-horizontal" role="form" method="POST" action="/password/update">
                            {{ csrf_field() }}

has('old_password') ? ' has-error' : '' }}">
                                原始密码

                                    <input id="old_password" type="password" class="form-control" name="old_password" value="{{ old('old_password') }}" required>
                                    @if ($errors->has('old_password'))

                                        {{ $errors->first('old_password') }}

                                    @endif

has('password') ? ' has-error' : '' }}">
                                输入新密码

                                    <input id="password" type="password" class="form-control" name="password" required>
                                    @if ($errors->has('password'))

                                        {{ $errors->first('password') }}

                                    @endif

                                确认新密码

                                    <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

                                    <button type="submit" class="btn btn-primary btn-block">
                                        更改密码
                                    </button>

                        </form>

@endsection


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_new"
          android:icon="@drawable/ic_menu_new"
          android:title="@string/menu_new"
          android:showAsAction="ifRoom|withText" />
    <item android:id="@+id/menu_setting"
          android:title="@string/settings"/>
    <item android:id="@+id/menu_about"
          android:title="@string/about"/>
    <item android:id="@+id/menu_problems"
        android:title="@string/problems"/>
</menu><!-- From: file:/home/marco/AndroidStudioProjects/StudentAssistantProject/StudentAssistant/src/main/res/menu/menu.xml -->


text:
package main

import (
	"database/sql"

	"github.com/apache/incubator-trafficcontrol/lib/go-log"

	"github.com/jmoiron/sqlx"
)

// PrivLevelInvalid - The Default Priv level
const PrivLevelInvalid = -1

// PrivLevelReadOnly - The user cannot do any API updates
const PrivLevelReadOnly = 10

// PrivLevelOperations - The user has minimal privileges
const PrivLevelOperations = 20

// PrivLevelAdmin - The user has full privileges
const PrivLevelAdmin = 30

func preparePrivLevelStmt(db *sqlx.DB) (*sql.Stmt, error) {
	return db.Prepare("select r.priv_level from tm_user as u join role as r on u.role = r.id where u.username = $1")
}

// PrivLevel - returns the privilege level of the given user, or PrivLevelInvalid if the user doesn't exist.
func PrivLevel(privLevelStmt *sql.Stmt, user string) int {
	var privLevel int
	err := privLevelStmt.QueryRow(user).Scan(&privLevel)
	switch {
	case err == sql.ErrNoRows:
		log.Errorf("checking user %v priv level: user not in database", user)
		return PrivLevelInvalid
	case err != nil:
		log.Errorf("Error checking user %v priv level: %v", user, err.Error())
		return PrivLevelInvalid
	default:
		return privLevel
	}
}


text:
<?php

namespace canisunit\secureToken;

use yii\di\Container;
use yii\helpers\ArrayHelper;
use Yii;
use canis\secureToken\Extension as SecureTokenExtension;
use canis\keyProvider\Extension as KeyProviderExtension;

/**
 * This is the base class for all yii framework unit tests.
 */
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * Clean up after test.
     * By default the application created with [[mockApplication]] will be destroyed.
     */
    protected function tearDown()
    {
        parent::tearDown();
        $this->destroyApplication();
    }

    /**
     * Populates Yii::$app with a new application
     * The application will be destroyed on tearDown() automatically.
     * @param array $config The application configuration, if needed
     * @param string $appClass name of the application class to create
     */
    protected function mockApplication($config = [], $appClass = '\yii\console\Application')
    {
        $app = new $appClass(ArrayHelper::merge([
            'id' => 'testapp',
            'basePath' => __DIR__,
            'vendorPath' => dirname(__DIR__) . '/vendor',
        ], $config));
        $keyProvider = new KeyProviderExtension();
        $keyProvider->bootstrap($app);
        $ext = new SecureTokenExtension();
        $ext->bootstrap($app);
    }

    protected function mockWebApplication($config = [], $appClass = '\yii\web\Application')
    {
        $app = new $appClass(ArrayHelper::merge([
            'id' => 'testapp',
            'basePath' => __DIR__,
            'vendorPath' => dirname(__DIR__) . '/vendor',
            'components' => [
                'request' => [
                    'cookieValidationKey' => 'wefJDF8sfdsfSDefwqdxj9oq',
                    'scriptFile' => __DIR__ .'/index.php',
                    'scriptUrl' => '/index.php',
                ],
            ]
        ], $config));
        $keyProvider = new KeyProviderExtension();
        $keyProvider->bootstrap($app);
        $ext = new SecureTokenExtension();
        $ext->bootstrap($app);
    }

    /**
     * Destroys application in Yii::$app by setting it to null.
     */
    protected function destroyApplication()
    {
        if (\Yii::$app && \Yii::$app->has('session', true)) {
            \Yii::$app->session->close();
        }
        Yii::$app = null;
        Yii::$container = new Container();
    }

    /**
     * Invokes object method, even if it is private or protected.
     * @param object $object object.
     * @param string $method method name.
     * @param array $args method arguments
     * @return mixed method result
     */
    protected function invoke($object, $method, array $args = [])
    {
        $classReflection = new \ReflectionClass(get_class($object));
        $methodReflection = $classReflection->getMethod($method);
        $methodReflection->setAccessible(true);
        $result = $methodReflection->invokeArgs($object, $args);
        $methodReflection->setAccessible(false);
        return $result;
    }

    /**
     * Asserting two strings equality ignoring line endings
     *
     * @param string $expected
     * @param string $actual
     */
    public function assertEqualsWithoutLE($expected, $actual)
    {
        $expected = str_replace("\r\n", "\n", $expected);
        $actual = str_replace("\r\n", "\n", $actual);

        $this->assertEquals($expected, $actual);
    }
}


text:
package foundation.softwaredesign.orbi.rest.filter;

import foundation.softwaredesign.orbi.model.exception.ErrorMessage;
import foundation.softwaredesign.orbi.persistence.entity.IdentityEntity;
import foundation.softwaredesign.orbi.persistence.repo.auth.IdentityRepository;
import foundation.softwaredesign.orbi.service.auth.IdentityThreadLocal;

import javax.annotation.Priority;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.Objects;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;

/**
 * @author Lucas Reeh <lr86gm@gmail.com>
 */
@Provider
@PreMatching
@Priority(value = 2)
@Produces({APPLICATION_JSON})
@Consumes({APPLICATION_JSON})
public class AuthorizationFilter implements ContainerRequestFilter {

    @Inject
    IdentityRepository identityRepository;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        IdentityThreadLocal.set(null);
        String path = requestContext.getUriInfo().getPath();
        if (path.equals("server/version") || path.equals("server/info") || path.equals("auth/login") || path.equals("auth/requestcode")) {
            return;
        }
        String bearerString = requestContext.getHeaderString("Authorization");
        if (Objects.isNull(bearerString)) {
            abort(requestContext, "Please log in");
            return;
        }
        String[] berearStringSplitted = bearerString.split(" ");
        if (Objects.isNull(berearStringSplitted) || (berearStringSplitted.length < 2)) {
            abort(requestContext, "Please log in");
            return;
        }
        if (Objects.isNull(berearStringSplitted[0]) || Objects.isNull(berearStringSplitted[1])) {
            abort(requestContext, "Please log in");
            return;
        }
        if (berearStringSplitted[0].isEmpty() || berearStringSplitted[1].isEmpty()) {
            abort(requestContext, "Please log in");
            return;
        }
        IdentityEntity identityEntity = null;
        try {
            identityEntity = identityRepository.findByToken(berearStringSplitted[1]);

        } catch (NoResultException|NullPointerException|IllegalStateException ex) {
            abort(requestContext, "Please log in");
        }
        IdentityThreadLocal.set(identityEntity);
    }

    private void abort(ContainerRequestContext requestContext, String text) {
        ErrorMessage message = new ErrorMessage();
        message.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
        message.setMessage("Unauthorized - " + text);
        requestContext.abortWith(Response
                .status(Response.Status.UNAUTHORIZED)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                .entity(message)
                .build());
    }
}


text:
package decorator.enums;

import org.apache.commons.lang3.StringUtils;

public enum PaymentMethod {
    DIRECT_BANK_TRANSFER,
    CHECK_PAYMENTS;

    @Override
    public String toString() {
        return StringUtils.capitalize(name().replace('_', ' ').toLowerCase());
    }
}


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

namespace RazorEngine.Templating
{
    /// <summary>
    /// A TemplateManager resolving remplates by path, given a list of folders to look into.
    /// </summary>
    public class ResolvePathTemplateManager : ITemplateManager
    {
        private readonly ReadOnlyCollection<string> layoutRoots;
        /// <summary>
        /// Initializes a new TemplateManager.
        /// </summary>
        /// <param name="layoutRoots">the list of folders to look for templates.</param>
        public ResolvePathTemplateManager(IEnumerable<string> layoutRoots)
        {
            this.layoutRoots = new ReadOnlyCollection<string>(new List<string>(layoutRoots));
        }

        internal ResolvePathTemplateManager(ReadOnlyCollection<string> list)
        {
            this.layoutRoots = list;
        }

        /// <summary>
        /// Resolve the given key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public ITemplateSource Resolve(ITemplateKey key)
        {
            var full = key as FullPathTemplateKey;
            if (full == null)
            {
                throw new NotSupportedException("You can only use FullPathTemplateKey with this manager");
            }
            var template = File.ReadAllText(full.FullPath);
            return new LoadedTemplateSource(template, full.FullPath);
        }

        /// <summary>
        /// Get the given key.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="resolveType"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
        {
            if (File.Exists (name))
            {
                return new FullPathTemplateKey(name, name, resolveType, context);
            }
            else
            {
                var resolved = layoutRoots.Select(l =>
                    {
                        var p = Path.Combine(l, name);
                        if (File.Exists(p))
                        {
                            return p;
                        }
                        else if (File.Exists(p + ".cshtml"))
                        {
                            return p + ".cshtml";
                        }
                        else
                        {
                            return null;
                        }
                    }).Where(l => l != null).FirstOrDefault();
                if (resolved == null)
                {
                    throw new InvalidOperationException(string.Format("Could not resolve template {0}", name));
                }
                else
                {
                    return new FullPathTemplateKey(name, resolved, resolveType, context);
                }
            }
        }

        /// <summary>
        /// Throws NotSupportedException.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="source"></param>
        public void AddDynamic(ITemplateKey key, ITemplateSource source)
        {
            throw new NotSupportedException("Adding templates dynamically is not supported! Instead you probably want to use the full-path in the name parameter?");
        }
    }
}


text:
<?

/**
 * Useful functions for getting paths for concrete5 items.
 * @package Core
 * @author Andrew Embler <andrew@concrete5.org>
 * @copyright  Copyright (c) 2003-2012 Concrete5. (http://www.concrete5.org)
 * @license    http://www.concrete5.org/license/     MIT License
 */

defined('C5_EXECUTE') or die("Access Denied.");

class Concrete5_Library_Environment_Record {

	public $override;
	public $file;
	public $url;
	public function exists() {
		return file_exists($this->file);
	}

}


text:
'use babel';

import os from 'os';

// Public: GrammarUtils.OperatingSystem - a module which exposes different
// platform related helper functions.
export default {
  isDarwin() {
    return this.platform() === 'darwin';
  },

  isWindows() {
    return this.platform() === 'win32';
  },

  isLinux() {
    return this.platform() === 'linux';
  },

  platform() {
    return os.platform();
  },

  release() {
    return os.release();
  },
};


text:
layout: post
date: 2016-03-30
title: "Ellis Bridals Style 11399 Sleeveless Chapel Train Aline/Princess"
category: Ellis
tags: [Ellis ,Ellis,Aline/Princess ,Queen Anne,Chapel Train,Sleeveless]
---
### Ellis Bridals Style 11399
Just **$299.99**
###   Sleeveless Chapel Train Aline/Princess

BRANDS	Ellis

Silhouette	Aline/Princess

Neckline	Queen Anne

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/ellis/4733-ellis-bridals-style-11399.html](https://www.readybrides.com/en/ellis/4733-ellis-bridals-style-11399.html)


text:
<?php

// get db connection
$db = Pimcore_Resource_Mysql::get("database");

$db->getConnection()->exec("ALTER TABLE `properties_predefined` ADD COLUMN `inheritable` tinyint(1) unsigned NOT NULL DEFAULT 0;");

?>


text:
package org.jboss.resteasy.skeleton.key;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

/**
 * Any class with package org.jboss.resteasy.skeleton.key will use NON_DEFAULT inclusion
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@Provider
public class SkeletonKeyContextResolver implements ContextResolver<ObjectMapper>
{
   protected ObjectMapper mapper = new ObjectMapper();

   public SkeletonKeyContextResolver()
   {
      mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
   }

   public SkeletonKeyContextResolver(boolean indent)
   {
      mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
      if (indent)
      {
         mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
      }
   }

   @Override
   public ObjectMapper getContext(Class<?> type)
   {
      if (type.getPackage().getName().startsWith("org.jboss.resteasy.skeleton.key")) return mapper;
      return null;
   }
}


text:
from __future__ import absolute_import, division, print_function

# Import the relevant PTS classes and modules
from .component import PlottingComponent
from ..photometry.component import PhotometryComponent
from ...core.tools import filesystem as fs
from ...core.tools.logging import log
from ..core.sed import ObservedSED
from ...core.plot.sed import SEDPlotter

# -----------------------------------------------------------------

class PhotometryPlotter(PlottingComponent, PhotometryComponent):

    """
    This class...
    """

    def __init__(self, config=None):

        """
        The constructor ...
        :param config:
        :return:
        """

        # Call the constructor of the base class
        #super(PlottingComponent, self).__init__(config) # not sure this will work
        PlottingComponent.__init__(self, config)
        PhotometryComponent.__init__(self)

        # -- Attributes --

        # The SEDs
        self.seds = dict()

    # -----------------------------------------------------------------

    def run(self, features=None):

        """
        This function ...
        :return:
        """

        # 1. Call the setup function
        self.setup()

        # 2. Load the SEDs
        self.load_seds()

        # 2. Load the aperture data
        #self.load_apertures()

        # 3. Plot
        self.plot()

    # -----------------------------------------------------------------

    def load_seds(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Loading the SEDs ...")

        # Load the 'DustPedia' observed SED
        dustpedia_sed = ObservedSED.from_file(self.observed_sed_dustpedia_path)

        # Load the PTS observed SED
        pts_sed = ObservedSED.from_file(self.observed_sed_path)

        # Add the SEDs
        self.seds["DustPedia"] = dustpedia_sed
        self.seds["PTS"] = pts_sed

    # -----------------------------------------------------------------

    def load_apertures(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Loading the apertures ...")

    # -----------------------------------------------------------------

    def plot(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Plotting ...")

        # Plot the SEDs
        self.plot_seds()

    # -----------------------------------------------------------------

    def plot_seds(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Plotting the SEDs ...")

        # Create the SED plotter
        plotter = SEDPlotter()

        # Add the SEDs
        for label in self.seds: plotter.add_observed_sed(self.seds[label], label)

        # Determine the path to the plot file
        path = fs.join(self.plot_photometry_path, "seds.pdf")

        # Run the plotter
        plotter.run(path)

# -----------------------------------------------------------------


text:
  'use strict';

  var index   = require('../controllers');
  var express = require('express')
  var util    = require('util')

  //intialize all the requirement paths GET POST DELETE PUT
  var GET 		= require('../controllers/GET');
  var DELETE 	= require('../controllers/DELETE');
  var POST 		= require('../controllers/POST');
  var app     = express();
  var router  = express.Router();
  var paragalaStudentGET = require('../controllers/paragala/GET')
  var paragalaStudentPOST = require('../controllers/paragala/POST')
  var path = require('path')
  var viewsPath   = path.normalize(__dirname + '/../app');

  /*
   * Rave Api
   **/
   var ravePOST = require('../controllers/rave/POST')
   var raveGET  = require('../controllers/rave/GET')

  /**
   * Application routes
   */
  module.exports = function(app, passport) {

    //enable cors
    app.all('/*', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });

  /**
   * Router
   */
  var router = express.Router();

    // list all Databases
    app.route("/mongo-api/dbs")
        .get(GET.dbs)
        .post(POST.db)
        .delete(DELETE.db)

    app.route("/mongo-api/db/:collection")
        .get( GET.collections )
        .post( POST.collections )
        .delete( DELETE.collections )

    app.route( "/mongo-api/db/:db/:collection" )
        .get( GET.listDocuments )
        .post( POST.documents )
        .delete( DELETE.documents )

    app.route( "/mongo-api/db/:db/:collection/:id" )
        .get( GET.document )
        .post( POST.doc )

    app.route( '/rave-api/login-judges' )
      .get( raveGET.judges )
      .post( ravePOST.judges )

    app.route( '/rave-api/judges-vote' )
      .get( raveGET.judgesVote )
      .post( ravePOST.judgesVote )

    app.route( '/rave-api/admin-vote' )
      .get( raveGET.judgesVoteResult )
      .post( ravePOST.adminVote )

    app.route( '/rave-api/final-result' )
      .get( raveGET.finalResult )

    app.get( '/isAdminLogin/admin', function ( req, res, next ) {
      res.send({ isAdminLogin: req.session.isAdminLogin })
    })

    app.get( '/isStudentLogin/student', function ( req, res, next ) {
      res.send( { isStudentLogin: req.session.isLogin } )
    })

    app.post( "/paragala-api/users", function (req, res, next) {
      passport.authenticate('local-login', function (err, user, info) {
        var error = req.flash('loginMessage');
        if (err) { return next(err); }
        if(user) {
          return req.logIn(user, function(err) {
            req.session.isAdminLogin = true;
            return res.json( {valid: 'success', adminUser: req.isAuthenticated()} )
          });
        }
        if (!user) {
          return res.json( {  valid: error.toString() } );
        } else {
          return res.json( { valid: error.toString() } )
        }
      })(req, res, next);
    })

    app.post( "/paragala-api/logout", function (req, res) {
      req.session.isAdminLogin = false;
      req.logout();
      res.send("success")
    })

    app.post( "/paragala-student-api/logout", function (req, res, next) {
      req.session.isLogin = false
      req.session.SN = null
      res.json( {isStudentLogout: req.session.isLogin} )
    })

    app.get( "/paragala-student-api/student", paragalaStudentGET.user )
    app.get( "/paragala-student-api/userResults", paragalaStudentGET.results )
    app.get( "/paragala-student-api/questionBuilder", paragalaStudentGET.questionBuilder )
    app.post( "/paragala-student-api/castUserVotes", paragalaStudentPOST.user )
    app.post( "/paragala-student-api/addStudent", paragalaStudentPOST.addStudent )

    app.get('/main/*', index.partials)
    app.get('/login/*', index.partials)
    app.get('/dashboard/*', index.partials);
    app.get('/database/*', index.partials);
    app.get('/paragala/*', index.partials);
    app.get('/paragalaAddStudent/*', isLoggedIn, index.partials);
    app.get('/paragalaQuestions/*', index.partials);
    app.get('/paragalaResults/*', isLoggedIn, index.partials);

    /*
     * Mr. and Mrs. Rave
     **/
    app.get('/rave/*', index.partials)

    app.all('/*', function(req, res, next) {
      // Just send the index.html for other files to support HTML5Mode
      res.render('index.html', { root: path.join(viewsPath, 'views') });
    });

  };

  function isLoggedIn(req, res, next) {
    console.log('ISLOGIN: ' + req.headers)
    //console.log(util.inspect("AM I: " + req.user.email, {showHidden: true, depth: null}))
    if (req.isAuthenticated()) {
      res.locals.user = req.user
      return next();
    }
    res.redirect('/main/index.html');
  }

  function adminLogin(req, res, next) {
    if(req.user.email == undefined) {
      return next();
    } else if(req.user.email == "canino_jories@hotmail.com") {
      return next();
    }

    res.redirect('/main/index.html')
  }

  function login(req, res, next) {
     if (req.user) {
      res.locals.user = req.user
    }
    return next();
  }


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Newtonsoft.Json;
using System;
using System.Reflection;

namespace Microsoft.Fx.Portability.Utils.JsonConverters
{
    internal abstract class JsonConverter<T> : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
    }
}