text:
package br.com.msl09.passwordgenerator;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;

public class PasswordDetails extends AppCompatActivity {
    public static final String DELETE_PASSWORD = "br.com.msl09.passwordgenerator.DELETE_PASSWORD";
    public static final String SAVE_LIST = "br.com.msl09.passwordgenerator.SHOW_PASSWORD";
    EditText hostnameField;
    EditText usernameField;
    EditText extraField;
    EditText lengthField;
    EditText masterField;
    TextView saltLabel;
    TextView generatedPasswordLabel;
    private PasswordInfo passwordInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password_details);
        hostnameField = (EditText) findViewById(R.id.hostname);
        usernameField = (EditText) findViewById(R.id.username);
        extraField = (EditText) findViewById(R.id.extra_symbols);
        lengthField = (EditText) findViewById(R.id.length);
        masterField = (EditText) findViewById(R.id.master_password);
        saltLabel = (TextView) findViewById(R.id.salt);
        generatedPasswordLabel = (TextView) findViewById(R.id.generated_password);

        Button saveButton = (Button) findViewById(R.id.save_password_button);

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendToMainActivity();
            }
        });

        Button saltButton = (Button) findViewById(R.id.regenerate_salt_button);

        saltButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passwordInfo.genNewSalt();
                saltLabel.setText(shortenText(passwordInfo.salt));
            }
        });

        Button deleteButton = (Button) findViewById(R.id.delete_password_button);

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deletePassword();
            }
        });

        passwordInfo = (PasswordInfo) getIntent().getSerializableExtra(MainActivity.EXTRA_MESSAGE);
        setText(hostnameField, passwordInfo.hostname);
        setText(usernameField, passwordInfo.user);
        setText(extraField, passwordInfo.symbols);
        setText(lengthField, passwordInfo.length.toString());
        setText(masterField, "");
        saltLabel.setText(shortenText(passwordInfo.salt));
        generatedPasswordLabel.setText("");

    }

    private void deletePassword() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 2. Chain together various setter methods to set the dialog characteristics
        builder.setMessage(R.string.delete_password)
                .setTitle(R.string.are_you_sure_delete)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        sendDeleteIntent();
                    }
                })
                .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // Nothing to do
                    }
                })
                .show();
    }

    private void sendDeleteIntent() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(DELETE_PASSWORD, passwordInfo.key());
        this.startActivity(intent);
    }

    @NonNull
    private String shortenText(String string) {
        if (string.length() > 3) {
            return string.substring(0, 3) + "…";
        } else {
            return string;
        }
    }

    private void setText(EditText view, String text) {
        view.setText(text, TextView.BufferType.EDITABLE);
    }

    private void sendToMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        updatePasswordInfo();
        intent.putExtra(SAVE_LIST, passwordInfo);
        this.startActivity(intent);
    }

    private void updatePasswordInfo() {
        passwordInfo.user = usernameField.getText().toString();
        passwordInfo.hostname = hostnameField.getText().toString();
        passwordInfo.symbols = extraField.getText().toString();
        try {
            passwordInfo.length = Integer.valueOf(lengthField.getText().toString());
        } catch (NumberFormatException ex) {
            Snackbar.make(findViewById(R.id.activity_password_details), R.string.length_format_error,
                    Snackbar.LENGTH_SHORT)
                    .show();
        }
        // salt is updated in place
        passwordInfo.hostname = hostnameField.getText().toString();
    }

    public void clickGenerateButton(View view) {
        PasswordTuple tuple = new PasswordTuple();
        tuple.master = masterField.getText().toString();
        updatePasswordInfo();
        tuple.passwordInfo = passwordInfo;
        new CalculatePasswordTask().execute(tuple);
    }

    public class PasswordTuple {
        String master;
        PasswordInfo passwordInfo;
    }

    private class CalculatePasswordTask extends AsyncTask<PasswordTuple, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Button genButton = (Button) findViewById(R.id.generate_password_button);
            genButton.setText(R.string.wait);
            genButton.setEnabled(false);
            Context context = getApplicationContext();
            Toast toast = Toast.makeText(context, R.string.calculatingPassword, Toast.LENGTH_SHORT);
            toast.show();
        }

        @Override
        protected String doInBackground(PasswordTuple... passwordTuples) {
            PasswordTuple passwordTuple = passwordTuples[0];
            String generatedPassword = "";
            try {
                generatedPassword = PasswordInfo.getPassword(
                        passwordTuple.master,
                        passwordTuple.passwordInfo);
            } catch (UnsupportedEncodingException e) {
                System.out.println("Some field(s) could not be converted to UTF-8");
                e.printStackTrace();
            }
            return generatedPassword;
        }

        @Override
        protected void onPostExecute(String result) {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, R.string.copyNotification, duration);
            toast.show();
            Button genButton = (Button) findViewById(R.id.generate_password_button);
            genButton.setText(R.string.copy);
            genButton.setEnabled(true);
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("simple text", result);
            clipboardManager.setPrimaryClip(clip);
            generatedPasswordLabel.setText(shortenText(result));
        }
    }

}


text:
require 'rexml/document'
require 'rexml/entity'
module REXML
  class Entity < Child
    def unnormalized
      # Due to an optimisation in REXML, the default entities aren't
      # associated with a document.  As these enties are defined and
      # not recursive, we know that expanding them won't cause any
      # issues.  Other entities in the document will still have
      # the association to the document preventing this from opening
      # a new attack vector.
      document.record_entity_expansion! if document
      v = value()
      return nil if v.nil?
      @unnormalized = Text::unnormalize(v, parent)
      @unnormalized
    end
  end

  class Document < Element
    def record_entity_expansion!
      @number_of_expansions ||= 0
      @number_of_expansions += 1
      if @number_of_expansions > Security.entity_expansion_limit
        raise "Processing aborted: number of entity expansions (#{@number_of_expansions}) exceeded the limit (#{Security.entity_expansion_limit})."
      end
    end
  end

  class Security
    @@entity_expansion_limit = 10_000

    # Set the entity expansion limit. By default the limit is set to 10000.
    def self.entity_expansion_limit=( val )
      @@entity_expansion_limit = val
    end

    # Get the entity expansion limit. By default the limit is set to 10000.
    def self.entity_expansion_limit
      return @@entity_expansion_limit
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.dataflow.sdk.transforms;

import static com.google.cloud.dataflow.sdk.TestUtils.LINES;
import static com.google.cloud.dataflow.sdk.TestUtils.NO_LINES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.google.cloud.dataflow.sdk.Pipeline;
import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder;
import com.google.cloud.dataflow.sdk.testing.DataflowAssert;
import com.google.cloud.dataflow.sdk.testing.TestPipeline;
import com.google.cloud.dataflow.sdk.values.PCollection;

import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * Tests for First.
 */
@RunWith(JUnit4.class)
@SuppressWarnings("serial")
public class FirstTest
    implements Serializable /* to allow anon inner classes */ {
  // PRE: lines contains no duplicates.
  void runTestFirst(final List<String> lines, int limit, boolean ordered) {
    Pipeline p = TestPipeline.create();

    PCollection<String> input = p.apply(Create.of(lines))
        .setCoder(StringUtf8Coder.of());

    if (ordered) {
      input.setOrdered(true);
    }

    PCollection<String> output =
        input.apply(First.<String>of(limit));

    if (ordered) {
      output.setOrdered(true);
    }

    final int expectedSize = Math.min(limit, lines.size());
    if (ordered) {
      List<String> expected = lines.subList(0, expectedSize);
      if (expected.isEmpty()) {
        DataflowAssert.that(output)
            .containsInAnyOrder(expected);
      } else {
        DataflowAssert.that(output)
            .containsInOrder(expected);
      }
    } else {
      DataflowAssert.that(output)
          .satisfies(new SerializableFunction<Iterable<String>, Void>() {
              @Override
              public Void apply(Iterable<String> actualIter) {
                // Make sure actual is the right length, and is a
                // subset of expected.
                List<String> actual = new ArrayList<>();
                for (String s : actualIter) {
                  actual.add(s);
                }
                assertEquals(expectedSize, actual.size());
                Set<String> actualAsSet = new TreeSet<>(actual);
                Set<String> linesAsSet = new TreeSet<>(lines);
                assertEquals(actual.size(), actualAsSet.size());
                assertEquals(lines.size(), linesAsSet.size());
                assertTrue(linesAsSet.containsAll(actualAsSet));
                return null;
              }
            });
    }

    p.run();
  }

  @Test
  @Category(com.google.cloud.dataflow.sdk.testing.RunnableOnService.class)
  public void testFirst() {
    runTestFirst(LINES, 0, false);
    runTestFirst(LINES, LINES.size() / 2, false);
    runTestFirst(LINES, LINES.size() * 2, false);
  }

  @Test
  // Extra tests, not worth the time to run on the real service.
  public void testFirstMore() {
    runTestFirst(LINES, LINES.size() - 1, false);
    runTestFirst(LINES, LINES.size(), false);
    runTestFirst(LINES, LINES.size() + 1, false);
  }

  // TODO: setOrdered(true) isn't supported yet by the Dataflow service.
  @Test
  public void testFirstOrdered() {
    runTestFirst(LINES, 0, true);
    runTestFirst(LINES, LINES.size() / 2, true);
    runTestFirst(LINES, LINES.size() - 1, true);
    runTestFirst(LINES, LINES.size(), true);
    runTestFirst(LINES, LINES.size() + 1, true);
    runTestFirst(LINES, LINES.size() * 2, true);
  }

  @Test
  @Category(com.google.cloud.dataflow.sdk.testing.RunnableOnService.class)
  public void testFirstEmpty() {
    runTestFirst(NO_LINES, 0, false);
    runTestFirst(NO_LINES, 1, false);
  }

  @Test
  // TODO: setOrdered(true) isn't supported yet by the Dataflow service.
  public void testFirstEmptyOrdered() {
    runTestFirst(NO_LINES, 0, true);
    runTestFirst(NO_LINES, 1, true);
  }
}


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) PIOClient *client;
@property (strong, nonatomic) NSString *currentUser;
@property (strong, nonatomic) NSMutableArray *userList;
@property (nonatomic, strong) NSMutableDictionary *foodDictionary;

- (void) createNewUser: (NSString *) uname;
- (void) changeCurrentUserTo: (NSString *) user;
@end


text:
"""
Duct tape an OpenSSH instance into a Twisted Protocol.  This is rather getto as
it assumes the connection will succeed and just rudely closes things off when
it receives data on stderr on the assumption that anything that will case data
to be written there is a irrecoverable error condition (Probably true).

Eventually I wish for this module to go away, but in the short term it's
unlikely, especially since I have better things to do with my life than making
Conch/Libssh2/paramiko/libssh do what is required.

In theory, this is where all the portability cruft will live, apart from the
py2exe stuff.
"""

import re
import os
import sys
import subprocess

from twisted.internet import protocol, reactor
from twisted.internet.protocol import Factory, Protocol, ClientCreator

from twisted.python import log

_SSH_ARGS = [
    "ssh",
    "-o ForwardAgent no",
    "-o ForwardX11 no",
    "-o BatchMode yes",
    "-o StrictHostKeyChecking yes",
    "-o VerifyHostKeyDNS no",
    "-o GSSAPIAuthentication no",
    "-o KbdInteractiveAuthentication no",
    "-o PasswordAuthentication no",
    "-o IdentitiesOnly yes",
    "-o ControlMaster no"   # In theory this can save us connections, but
                            # certain versions of OpenSSH break with this
                            # enabled when using -W, and there should only
                            # ever be one connection per bridge at a time.
    # XXX: Check to see if there are any other options that can screw us if we
    # don't set them explicitly.
]

_SSH_EXECUTABLE = None
_SSH_ENV = None
_SSH_W_IS_FUCKED = False
_NULL_FILE = None

# As far as I know, no one uses this cert shit, but if the remote sshd is
# configured to use them then negotiation will fail because we don't support
# verifying those at the moment.  It's not possible to remove them since
# we will look different from standard OpenSSH.
_SSH_ARGS_HKEY_NO_ECDSA = (
    "-o HostKeyAlgorithms "
    "ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,"
    "ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,"
    "ssh-rsa,ssh-dss"
)

_SSH_ARGS_HKEY_ECDSA = (
    "-o HostKeyAlgorithms "
    "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
    "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
    "ecdsa-sha2-nistp521-cert-v01@openssh.com,"
    "ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,"
    "ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,"
    "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,"
    "ssh-rsa,ssh-dss"
)

class ducttape(protocol.ProcessProtocol):
    socks_obj = None
    host = None
    port = None

    pid = None

    l_client_creator = None
    l_client = None
    l_port = None
    l_attempts = None

    def __init__(self, socks_obj, host, port):
        self.socks_obj = socks_obj
        self.host = host
        self.port = port

    def connectionMade(self):
        if _SSH_W_IS_FUCKED is False:
            self.connectionReallyMade()
        else:
            log.msg("SSH: Using -L, port:" + str(self.l_port))
            self.pid = self.transport.pid
            self.socks_obj.state_mgr.monitor.watch_pid(self.pid)
            self.l_client_creator = ClientCreator(reactor, ducttape_l_client,
                                                  self)
            self.l_attempts = 0
            self.scheduleLocalConnect()

    def scheduleLocalConnect(self):
        if self.l_attempts > 3:
            log.msg("SSH: Giving up connecting to local proxy")
            self.transport.signalProcess("KILL")
        else:
            self.l_attempts += 1
            reactor.callLater(self.l_attempts * 5, self.tryLocalConnect)

    def tryLocalConnect(self):
        log.msg("SSH: Attempting to connect to local proxy port, try ",
                self.l_attempts)
        d = self.l_client_creator.connectTCP("127.0.0.1", self.l_port)
        d.addErrback(ducttape_l_client_errback, self)

    def connectionReallyMade(self):
        # Send the SOCKS reply, and set us up as the otherConn so that data
        # can be relayed
        self.socks_obj.makeReply(90, 0, port=self.port, ip=self.host)
        self.socks_obj.otherConn = self

    def outReceived(self, data):
        self.socks_obj.transport.write(data)

    def write(self, data):
        if _SSH_W_IS_FUCKED is False:
            self.transport.write(data)
        else:
            self.l_client.write(data)

    def errReceived(self, data):
        # Hmmm, got output from OpenSSH over stderr, either debug logging
        # is enabled or somethign went horribly wrong and OpenSSH is about
        # to die anyway.  Scrub IP addresses and log it for the user.
        data_scrubbed = re.sub(r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
                               lambda x: "[scrubbed]", data)
        data_scrubbed = data_scrubbed.strip()
        log.msg("SSH stderr: " + data_scrubbed)

    def inConnectionLost(self):
        pass

    def outConnectionLost(self):
        pass

    def errConnectionLost(self):
        pass

    def processExited(self, reason):
        if _SSH_W_IS_FUCKED is True:
            self.socks_obj.state_mgr.monitor.unwatch_pid(self.pid)

    def processEnded(self, reason):
        self.socks_obj.transport.loseConnection()

    def socksClosed(self):
        try:
            self.transport.signalProcess("KILL")
        except Exception:
            sys.exc_clear()

# Ugh, ssh -W is flakly on every single windows port of OpenSSH that I've
# managed to find.
class ducttape_l_client(Protocol):
    ducttape_obj = None

    def __init__(self, ducttape_obj):
        self.ducttape_obj = ducttape_obj

    def connectionMade(self):
        self.ducttape_obj.l_client = self
        self.ducttape_obj.connectionReallyMade()

    def dataReceived(self, data):
        self.ducttape_obj.outReceived(data)

    def write(self, data):
        self.transport.write(data)

    def connectionLost(self, reason):
        try:
            self.ducttape_obj.transport.signalProcess("KILL")
        except Exception:
            sys.exc_clear()
        self.ducttape_obj = None

def ducttape_l_client_errback(error, dt):
    dt.scheduleLocalConnect()
    return error

def new_ducttape(socks_obj, host, port, user, key, orport):
    # I *should* validate that I have a known_hosts entry for host and that the
    # key_file is valid.  Can't be bothered for now, and ssh will error out if
    # either of those conditons are not true.
    process_protocol = ducttape(socks_obj, host, port)

    args = list(_SSH_ARGS)
    if socks_obj.state_mgr.debug is True:
        args.append("-vvv")
    args.append("-F")
    args.append(_NULL_FILE)
    args.append('-o UserKnownHostsFile "' +
                socks_obj.state_mgr.known_hosts_path + '"')
    args.append('-o GlobalKnownHostsFile "' + _NULL_FILE + '"')
    if socks_obj.state_mgr.use_ecdsa is True:
        args.append(_SSH_ARGS_HKEY_ECDSA)
    else:
        args.append(_SSH_ARGS_HKEY_NO_ECDSA)
    args.append('-o IdentityFile "' + key + '"')
    args.append("-p " + str(port))

    if _SSH_W_IS_FUCKED is True:
        # Find a free unallocated port to listen on
        #
        # XXX: Yes, there is a race condition here.
        p = reactor.listenTCP(0, Factory())
        l_port = p.getHost().port
        args.append("-L localhost:" + str(l_port) + ":127.0.0.1:" + str(orport))
        args.append("-T")
        args.append("-N")
        process_protocol.l_port = l_port
        p.stopListening()
    else:
        args.append("-W 127.0.0.1:" + str(orport))

    args.append(user + "@" + host)
    reactor.spawnProcess(process_protocol, _SSH_EXECUTABLE, args, env=_SSH_ENV)

    return process_protocol

def init_ducttape(state):
    # Do the platform specific runtime setup

    global _SSH_EXECUTABLE
    global _SSH_ENV
    global _SSH_W_IS_FUCKED
    global _NULL_FILE
    frozen = getattr(sys, "frozen", "")

    if frozen == "console_exe":
        # We've been packaged with py2exe
        #
        # Note: If ssh.exe is cygwin's, then _NULL_FILE should be /dev/null, if
        # it is linked against mingw, NUL should be used instead.
        _SSH_EXECUTABLE = os.path.abspath(os.path.join(os.path.dirname(
            sys.executable), "ssh.exe"))
        _NULL_FILE = "NUL"
        _SSH_W_IS_FUCKED = True
        _SSH_ENV = {"CYGWIN": "nodosfilewarning"}
    else:
        _SSH_EXECUTABLE = "/usr/bin/ssh"
        _NULL_FILE = "/dev/null"

        # The tor browser bundle sets LD_LIBRARY_PATH, and ships with their own
        # version of OpenSSL.  Unset the enviornment variable so our children
        # pick up the OpenSSL they were linked against.
        if os.getenv("LD_LIBRARY_PATH") is not None:
            os.unsetenv("LD_LIBRARY_PATH")

    # Run ssh - V to ensure that the SSH excutable works, that it is OpenSSH,
    # and so that we can determine if it supports ECDSA or not.
    #
    # XXX: I *should* use utils.getProcessOutput, but it's a lot easier
    # to use subprocess since I want this to be blocking.
    version = None
    try:
        version = subprocess.check_output([_SSH_EXECUTABLE, "-V"],
                                          stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as err:
        log.msg("SSH: Failed check OpenSSH version " + str(e))
        return
    version = version.strip()
    log.msg("SSH Version: " + version)
    m = re.match(r"OpenSSH_(\d+\.\d+)", version)
    if m is None:
        log.msg("SSH: Failed to determine SSH client major/minor")
        return
    v = float(m.group(1))

    # OpenSSH got ECDSA support starting from v5.6
    #
    # Apple's OpenSSH/OpenSSL does not support ECDSA at least on
    # Mountain Lion despite being fairly recent, sucks to be them.
    if v < 5.6 or sys.platform == "darwin":
        log.msg("SSH: The installed OpenSSH version does not support ECDSA")
        state.use_ecdsa = False

    state.ssh_works = True

def term_ducttape():
    # Do any nasty platform specific cleanup here.
    pass

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4


text:
package user

import (
	api "code.gitea.io/sdk/gitea"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/context"
)

func responseAPIUsers(ctx *context.APIContext, users []*models.User) {
	apiUsers := make([]*api.User, len(users))
	for i := range users {
		apiUsers[i] = users[i].APIFormat()
	}
	ctx.JSON(200, &apiUsers)
}

func listUserFollowers(ctx *context.APIContext, u *models.User) {
	users, err := u.GetFollowers(ctx.QueryInt("page"))
	if err != nil {
		ctx.Error(500, "GetUserFollowers", err)
		return
	}
	responseAPIUsers(ctx, users)
}

// ListMyFollowers list the authenticated user's followers
func ListMyFollowers(ctx *context.APIContext) {
	// swagger:operation GET /user/followers user userCurrentListFollowers
	// ---
	// summary: List the authenticated user's followers
	// produces:
	// - application/json
	// responses:
	//   "200":
	//     "$ref": "#/responses/UserList"
	listUserFollowers(ctx, ctx.User)
}

// ListFollowers list the given user's followers
func ListFollowers(ctx *context.APIContext) {
	// swagger:operation GET /users/{username}/followers user userListFollowers
	// ---
	// summary: List the given user's followers
	// produces:
	// - application/json
	// parameters:
	// - name: username
	//   in: path
	//   description: username of user
	//   type: string
	//   required: true
	// responses:
	//   "200":
	//     "$ref": "#/responses/UserList"
	u := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}
	listUserFollowers(ctx, u)
}

func listUserFollowing(ctx *context.APIContext, u *models.User) {
	users, err := u.GetFollowing(ctx.QueryInt("page"))
	if err != nil {
		ctx.Error(500, "GetFollowing", err)
		return
	}
	responseAPIUsers(ctx, users)
}

// ListMyFollowing list the users that the authenticated user is following
func ListMyFollowing(ctx *context.APIContext) {
	// swagger:operation GET /user/following user userCurrentListFollowing
	// ---
	// summary: List the users that the authenticated user is following
	// produces:
	// - application/json
	// responses:
	//   "200":
	//     "$ref": "#/responses/UserList"
	listUserFollowing(ctx, ctx.User)
}

// ListFollowing list the users that the given user is following
func ListFollowing(ctx *context.APIContext) {
	// swagger:operation GET /users/{username}/following user userListFollowing
	// ---
	// summary: List the users that the given user is following
	// produces:
	// - application/json
	// parameters:
	// - name: username
	//   in: path
	//   description: username of user
	//   type: string
	//   required: true
	// responses:
	//   "200":
	//     "$ref": "#/responses/UserList"
	u := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}
	listUserFollowing(ctx, u)
}

func checkUserFollowing(ctx *context.APIContext, u *models.User, followID int64) {
	if u.IsFollowing(followID) {
		ctx.Status(204)
	} else {
		ctx.Status(404)
	}
}

// CheckMyFollowing whether the given user is followed by the authenticated user
func CheckMyFollowing(ctx *context.APIContext) {
	// swagger:operation GET /user/following/{username} user userCurrentCheckFollowing
	// ---
	// summary: Check whether a user is followed by the authenticated user
	// parameters:
	// - name: username
	//   in: path
	//   description: username of followed user
	//   type: string
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	//   "404":
	//     "$ref": "#/responses/notFound"
	target := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}
	checkUserFollowing(ctx, ctx.User, target.ID)
}

// CheckFollowing check if one user is following another user
func CheckFollowing(ctx *context.APIContext) {
	// swagger:operation GET /users/{follower}/following/{followee} user userCheckFollowing
	// ---
	// summary: Check if one user is following another user
	// parameters:
	// - name: follower
	//   in: path
	//   description: username of following user
	//   type: string
	//   required: true
	// - name: followee
	//   in: path
	//   description: username of followed user
	//   type: string
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	//   "404":
	//     "$ref": "#/responses/notFound"
	u := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}
	target := GetUserByParamsName(ctx, ":target")
	if ctx.Written() {
		return
	}
	checkUserFollowing(ctx, u, target.ID)
}

// Follow follow a user
func Follow(ctx *context.APIContext) {
	// swagger:operation PUT /user/following/{username} user userCurrentPutFollow
	// ---
	// summary: Follow a user
	// parameters:
	// - name: username
	//   in: path
	//   description: username of user to follow
	//   type: string
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	target := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}
	if err := models.FollowUser(ctx.User.ID, target.ID); err != nil {
		ctx.Error(500, "FollowUser", err)
		return
	}
	ctx.Status(204)
}

// Unfollow unfollow a user
func Unfollow(ctx *context.APIContext) {
	// swagger:operation DELETE /user/following/{username} user userCurrentDeleteFollow
	// ---
	// summary: Unfollow a user
	// parameters:
	// - name: username
	//   in: path
	//   description: username of user to unfollow
	//   type: string
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	target := GetUserByParams(ctx)
	if ctx.Written() {
		return
	}
	if err := models.UnfollowUser(ctx.User.ID, target.ID); err != nil {
		ctx.Error(500, "UnfollowUser", err)
		return
	}
	ctx.Status(204)
}


text:
//
//  HJCycleScrollView.h
//  HJCycleScrollView
//
//  Created by luo.h on 15/7/12.
//  Copyright (c) 2015年 l.h. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "NSTimer+Addition.h"
/**  开启定时器 */
static NSString * const HJCycleScrollViewOpenTimerNotiName   = @"BCycleScrollViewOpenTimer";

/**  关闭定时器*/
static NSString * const HJCycleScrollViewCloseTimerNotiName   = @"SBCycleScrollViewCloseTimer";

@class HJCycleScrollView;
@protocol HJCycleScrollViewDelegate <NSObject>
- (void)HJCycleScrollView:(HJCycleScrollView *)cycleScrollView didSelectIndex:(NSInteger)index;
@end

@interface HJCycleScrollView : UIView

-(id)initWithFrame:(CGRect)frame
          Duration:(NSTimeInterval)duration
  pageControlHeight:(NSInteger)height;

@property (nonatomic,weak) id<HJCycleScrollViewDelegate>delegate;

@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) NSArray *titleArray;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel      *titleLabel;

@end


text:
require 'spec_helper'
require 'fakefs/spec_helpers'

module Bosh::Director
  describe Jobs::Backup do
    describe 'DJ job class expectations' do
      let(:job_type) { :bosh_backup }
      let(:queue) { :normal }
      it_behaves_like 'a DJ job'
    end

    describe '#perform' do
      include FakeFS::SpecHelpers

      let(:backup_file) { '/dest_dir/backup.tgz' }
      let(:tmp_output_dir) { File.join('/tmp/random') }
      let(:tar_gzipper) { instance_double('Bosh::Director::Core::TarGzipper') }
      let(:db_adapter) { double('db adapter') }
      let(:task) { Models::Task.make(id: 42) }
      let(:task_writer) {Bosh::Director::TaskDBWriter.new(:event_output, task.id)}
      let(:event_log) {Bosh::Director::EventLog::Log.new(task_writer)}

      subject(:backup_task) do
        Jobs::Backup.new(backup_file, tar_gzipper: tar_gzipper, db_adapter: db_adapter)
      end

      before do
        FileUtils.mkdir_p(tmp_output_dir)
        allow(Dir).to receive(:mktmpdir).and_yield(tmp_output_dir)
        allow(tar_gzipper).to receive(:compress)
        allow(db_adapter).to receive(:export)
        allow(Config).to receive(:event_log).and_return(event_log)
      end

      it 'backs up the database' do
        expect(db_adapter).to receive(:export).with(File.join(tmp_output_dir, 'director_db.sql'))

        backup_task.perform
      end

      it 'combines the tarballs' do
        expect(tar_gzipper).to receive(:compress).with(tmp_output_dir, 'director_db.sql', backup_file)

        backup_task.perform
      end

      it 'returns the destination of the logs' do
        expect(backup_task.perform).to eq "Backup created at #{backup_file}"
      end
    end
  end
end


text:
package org.apache.spark.ml.feature

import org.apache.hadoop.fs.Path

import org.apache.spark.SparkException
import org.apache.spark.annotation.Since
import org.apache.spark.ml.{Estimator, Model}
import org.apache.spark.ml.attribute._
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.ml.param._
import org.apache.spark.ml.param.shared.{HasHandleInvalid, HasInputCol, HasInputCols, HasOutputCol, HasOutputCols}
import org.apache.spark.ml.util._
import org.apache.spark.sql.{DataFrame, Dataset}
import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.functions.{col, lit, udf}
import org.apache.spark.sql.types.{DoubleType, StructField, StructType}

/** Private trait for params and common methods for OneHotEncoder and OneHotEncoderModel */
private[ml] trait OneHotEncoderBase extends Params with HasHandleInvalid
  with HasInputCol with HasInputCols with HasOutputCol with HasOutputCols {

  /**
   * Param for how to handle invalid data during transform().
   * Options are 'keep' (invalid data presented as an extra categorical feature) or
   * 'error' (throw an error).
   * Note that this Param is only used during transform; during fitting, invalid data
   * will result in an error.
   * Default: "error"
   * @group param
   */
  @Since("2.3.0")
  override val handleInvalid: Param[String] = new Param[String](this, "handleInvalid",
    "How to handle invalid data during transform(). " +
    "Options are 'keep' (invalid data presented as an extra categorical feature) " +
    "or error (throw an error). Note that this Param is only used during transform; " +
    "during fitting, invalid data will result in an error.",
    ParamValidators.inArray(OneHotEncoder.supportedHandleInvalids))

  /**
   * Whether to drop the last category in the encoded vector (default: true)
   * @group param
   */
  @Since("2.3.0")
  final val dropLast: BooleanParam =
    new BooleanParam(this, "dropLast", "whether to drop the last category")

  /** @group getParam */
  @Since("2.3.0")
  def getDropLast: Boolean = $(dropLast)

  setDefault(handleInvalid -> OneHotEncoder.ERROR_INVALID, dropLast -> true)

  /** Returns the input and output column names corresponding in pair. */
  private[feature] def getInOutCols(): (Array[String], Array[String]) = {
    if (isSet(inputCol)) {
      (Array($(inputCol)), Array($(outputCol)))
    } else {
      ($(inputCols), $(outputCols))
    }
  }

  protected def validateAndTransformSchema(
      schema: StructType,
      dropLast: Boolean,
      keepInvalid: Boolean): StructType = {
    ParamValidators.checkSingleVsMultiColumnParams(this, Seq(outputCol), Seq(outputCols))
    val (inputColNames, outputColNames) = getInOutCols()

    require(inputColNames.length == outputColNames.length,
      s"The number of input columns ${inputColNames.length} must be the same as the number of " +
        s"output columns ${outputColNames.length}.")

    // Input columns must be NumericType.
    inputColNames.foreach(SchemaUtils.checkNumericType(schema, _))

    // Prepares output columns with proper attributes by examining input columns.
    val inputFields = inputColNames.map(schema(_))

    val outputFields = inputFields.zip(outputColNames).map { case (inputField, outputColName) =>
      OneHotEncoderCommon.transformOutputColumnSchema(
        inputField, outputColName, dropLast, keepInvalid)
    }
    outputFields.foldLeft(schema) { case (newSchema, outputField) =>
      SchemaUtils.appendColumn(newSchema, outputField)
    }
  }
}

/**
 * A one-hot encoder that maps a column of category indices to a column of binary vectors, with
 * at most a single one-value per row that indicates the input category index.
 * For example with 5 categories, an input value of 2.0 would map to an output vector of
 * `[0.0, 0.0, 1.0, 0.0]`.
 * The last category is not included by default (configurable via `dropLast`),
 * because it makes the vector entries sum up to one, and hence linearly dependent.
 * So an input value of 4.0 maps to `[0.0, 0.0, 0.0, 0.0]`.
 *
 * @note This is different from scikit-learn's OneHotEncoder, which keeps all categories.
 * The output vectors are sparse.
 *
 * When `handleInvalid` is configured to 'keep', an extra "category" indicating invalid values is
 * added as last category. So when `dropLast` is true, invalid values are encoded as all-zeros
 * vector.
 *
 * @note When encoding multi-column by using `inputCols` and `outputCols` params, input/output cols
 * come in pairs, specified by the order in the arrays, and each pair is treated independently.
 *
 * @see `StringIndexer` for converting categorical values into category indices
 */
@Since("3.0.0")
class OneHotEncoder @Since("3.0.0") (@Since("3.0.0") override val uid: String)
    extends Estimator[OneHotEncoderModel] with OneHotEncoderBase with DefaultParamsWritable {

  @Since("3.0.0")
  def this() = this(Identifiable.randomUID("oneHotEncoder"))

  /** @group setParam */
  @Since("3.0.0")
  def setInputCol(value: String): this.type = set(inputCol, value)

  /** @group setParam */
  @Since("3.0.0")
  def setOutputCol(value: String): this.type = set(outputCol, value)

  /** @group setParam */
  @Since("3.0.0")
  def setInputCols(values: Array[String]): this.type = set(inputCols, values)

  /** @group setParam */
  @Since("3.0.0")
  def setOutputCols(values: Array[String]): this.type = set(outputCols, values)

  /** @group setParam */
  @Since("3.0.0")
  def setDropLast(value: Boolean): this.type = set(dropLast, value)

  /** @group setParam */
  @Since("3.0.0")
  def setHandleInvalid(value: String): this.type = set(handleInvalid, value)

  @Since("3.0.0")
  override def transformSchema(schema: StructType): StructType = {
    val keepInvalid = $(handleInvalid) == OneHotEncoder.KEEP_INVALID
    validateAndTransformSchema(schema, dropLast = $(dropLast),
      keepInvalid = keepInvalid)
  }

  @Since("3.0.0")
  override def fit(dataset: Dataset[_]): OneHotEncoderModel = {
    transformSchema(dataset.schema)

    val (inputColumns, outputColumns) = getInOutCols()
    // Compute the plain number of categories without `handleInvalid` and
    // `dropLast` taken into account.
    val transformedSchema = validateAndTransformSchema(dataset.schema, dropLast = false,
      keepInvalid = false)
    val categorySizes = new Array[Int](outputColumns.length)

    val columnToScanIndices = outputColumns.zipWithIndex.flatMap { case (outputColName, idx) =>
      val numOfAttrs = AttributeGroup.fromStructField(
        transformedSchema(outputColName)).size
      if (numOfAttrs < 0) {
        Some(idx)
      } else {
        categorySizes(idx) = numOfAttrs
        None
      }
    }

    // Some input columns don't have attributes or their attributes don't have necessary info.
    // We need to scan the data to get the number of values for each column.
    if (columnToScanIndices.length > 0) {
      val inputColNames = columnToScanIndices.map(inputColumns(_))
      val outputColNames = columnToScanIndices.map(outputColumns(_))

      // When fitting data, we want the plain number of categories without `handleInvalid` and
      // `dropLast` taken into account.
      val attrGroups = OneHotEncoderCommon.getOutputAttrGroupFromData(
        dataset, inputColNames, outputColNames, dropLast = false)
      attrGroups.zip(columnToScanIndices).foreach { case (attrGroup, idx) =>
        categorySizes(idx) = attrGroup.size
      }
    }

    val model = new OneHotEncoderModel(uid, categorySizes).setParent(this)
    copyValues(model)
  }

  @Since("3.0.0")
  override def copy(extra: ParamMap): OneHotEncoder = defaultCopy(extra)
}

@Since("3.0.0")
object OneHotEncoder extends DefaultParamsReadable[OneHotEncoder] {

  private[feature] val KEEP_INVALID: String = "keep"
  private[feature] val ERROR_INVALID: String = "error"
  private[feature] val supportedHandleInvalids: Array[String] = Array(KEEP_INVALID, ERROR_INVALID)

  @Since("3.0.0")
  override def load(path: String): OneHotEncoder = super.load(path)
}

/**
 * @param categorySizes  Original number of categories for each feature being encoded.
 *                       The array contains one value for each input column, in order.
 */
@Since("3.0.0")
class OneHotEncoderModel private[ml] (
    @Since("3.0.0") override val uid: String,
    @Since("3.0.0") val categorySizes: Array[Int])
  extends Model[OneHotEncoderModel] with OneHotEncoderBase with MLWritable {

  import OneHotEncoderModel._

  // Returns the category size for each index with `dropLast` and `handleInvalid`
  // taken into account.
  private def getConfigedCategorySizes: Array[Int] = {
    val dropLast = getDropLast
    val keepInvalid = getHandleInvalid == OneHotEncoder.KEEP_INVALID

    if (!dropLast && keepInvalid) {
      // When `handleInvalid` is "keep", an extra category is added as last category
      // for invalid data.
      categorySizes.map(_ + 1)
    } else if (dropLast && !keepInvalid) {
      // When `dropLast` is true, the last category is removed.
      categorySizes.map(_ - 1)
    } else {
      // When `dropLast` is true and `handleInvalid` is "keep", the extra category for invalid
      // data is removed. Thus, it is the same as the plain number of categories.
      categorySizes
    }
  }

  private def encoder: UserDefinedFunction = {
    val keepInvalid = getHandleInvalid == OneHotEncoder.KEEP_INVALID
    val configedSizes = getConfigedCategorySizes
    val localCategorySizes = categorySizes

    // The udf performed on input data. The first parameter is the input value. The second
    // parameter is the index in inputCols of the column being encoded.
    udf { (label: Double, colIdx: Int) =>
      val origCategorySize = localCategorySizes(colIdx)
      // idx: index in vector of the single 1-valued element
      val idx = if (label >= 0 && label < origCategorySize) {
        label
      } else {
        if (keepInvalid) {
          origCategorySize
        } else {
          if (label < 0) {
            throw new SparkException(s"Negative value: $label. Input can't be negative. " +
              s"To handle invalid values, set Param handleInvalid to " +
              s"${OneHotEncoder.KEEP_INVALID}")
          } else {
            throw new SparkException(s"Unseen value: $label. To handle unseen values, " +
              s"set Param handleInvalid to ${OneHotEncoder.KEEP_INVALID}.")
          }
        }
      }

      val size = configedSizes(colIdx)
      if (idx < size) {
        Vectors.sparse(size, Array(idx.toInt), Array(1.0))
      } else {
        Vectors.sparse(size, Array.emptyIntArray, Array.emptyDoubleArray)
      }
    }
  }

  /** @group setParam */
  @Since("3.0.0")
  def setInputCol(value: String): this.type = set(inputCol, value)

  /** @group setParam */
  @Since("3.0.0")
  def setOutputCol(value: String): this.type = set(outputCol, value)

  /** @group setParam */
  @Since("3.0.0")
  def setInputCols(values: Array[String]): this.type = set(inputCols, values)

  /** @group setParam */
  @Since("3.0.0")
  def setOutputCols(values: Array[String]): this.type = set(outputCols, values)

  /** @group setParam */
  @Since("3.0.0")
  def setDropLast(value: Boolean): this.type = set(dropLast, value)

  /** @group setParam */
  @Since("3.0.0")
  def setHandleInvalid(value: String): this.type = set(handleInvalid, value)

  @Since("3.0.0")
  override def transformSchema(schema: StructType): StructType = {
    val (inputColNames, _) = getInOutCols()

    require(inputColNames.length == categorySizes.length,
      s"The number of input columns ${inputColNames.length} must be the same as the number of " +
        s"features ${categorySizes.length} during fitting.")

    val keepInvalid = $(handleInvalid) == OneHotEncoder.KEEP_INVALID
    val transformedSchema = validateAndTransformSchema(schema, dropLast = $(dropLast),
      keepInvalid = keepInvalid)
    verifyNumOfValues(transformedSchema)
  }

  /**
   * If the metadata of input columns also specifies the number of categories, we need to
   * compare with expected category number with `handleInvalid` and `dropLast` taken into
   * account. Mismatched numbers will cause exception.
   */
  private def verifyNumOfValues(schema: StructType): StructType = {
    val configedSizes = getConfigedCategorySizes
    val (inputColNames, outputColNames) = getInOutCols()
    outputColNames.zipWithIndex.foreach { case (outputColName, idx) =>
      val inputColName = inputColNames(idx)
      val attrGroup = AttributeGroup.fromStructField(schema(outputColName))

      // If the input metadata specifies number of category for output column,
      // comparing with expected category number with `handleInvalid` and
      // `dropLast` taken into account.
      if (attrGroup.attributes.nonEmpty) {
        val numCategories = configedSizes(idx)
        require(attrGroup.size == numCategories, "OneHotEncoderModel expected " +
          s"$numCategories categorical values for input column $inputColName, " +
            s"but the input column had metadata specifying ${attrGroup.size} values.")
      }
    }
    schema
  }

  @Since("3.0.0")
  override def transform(dataset: Dataset[_]): DataFrame = {
    val transformedSchema = transformSchema(dataset.schema, logging = true)
    val keepInvalid = $(handleInvalid) == OneHotEncoder.KEEP_INVALID
    val (inputColNames, outputColNames) = getInOutCols()

    val encodedColumns = inputColNames.indices.map { idx =>
      val inputColName = inputColNames(idx)
      val outputColName = outputColNames(idx)

      val outputAttrGroupFromSchema =
        AttributeGroup.fromStructField(transformedSchema(outputColName))

      val metadata = if (outputAttrGroupFromSchema.size < 0) {
        OneHotEncoderCommon.createAttrGroupForAttrNames(outputColName,
          categorySizes(idx), $(dropLast), keepInvalid).toMetadata()
      } else {
        outputAttrGroupFromSchema.toMetadata()
      }

      encoder(col(inputColName).cast(DoubleType), lit(idx))
        .as(outputColName, metadata)
    }
    dataset.withColumns(outputColNames, encodedColumns)
  }

  @Since("3.0.0")
  override def copy(extra: ParamMap): OneHotEncoderModel = {
    val copied = new OneHotEncoderModel(uid, categorySizes)
    copyValues(copied, extra).setParent(parent)
  }

  @Since("3.0.0")
  override def write: MLWriter = new OneHotEncoderModelWriter(this)

  @Since("3.0.0")
  override def toString: String = {
    s"OneHotEncoderModel: uid=$uid, dropLast=${$(dropLast)}, handleInvalid=${$(handleInvalid)}" +
      get(inputCols).map(c => s", numInputCols=${c.length}").getOrElse("") +
      get(outputCols).map(c => s", numOutputCols=${c.length}").getOrElse("")
  }
}

@Since("3.0.0")
object OneHotEncoderModel extends MLReadable[OneHotEncoderModel] {

  private[OneHotEncoderModel]
  class OneHotEncoderModelWriter(instance: OneHotEncoderModel) extends MLWriter {

    private case class Data(categorySizes: Array[Int])

    override protected def saveImpl(path: String): Unit = {
      DefaultParamsWriter.saveMetadata(instance, path, sc)
      val data = Data(instance.categorySizes)
      val dataPath = new Path(path, "data").toString
      sparkSession.createDataFrame(Seq(data)).repartition(1).write.parquet(dataPath)
    }
  }

  private class OneHotEncoderModelReader extends MLReader[OneHotEncoderModel] {

    private val className = classOf[OneHotEncoderModel].getName

    override def load(path: String): OneHotEncoderModel = {
      val metadata = DefaultParamsReader.loadMetadata(path, sc, className)
      val dataPath = new Path(path, "data").toString
      val data = sparkSession.read.parquet(dataPath)
        .select("categorySizes")
        .head()
      val categorySizes = data.getAs[Seq[Int]](0).toArray
      val model = new OneHotEncoderModel(metadata.uid, categorySizes)
      metadata.getAndSetParams(model)
      model
    }
  }

  @Since("3.0.0")
  override def read: MLReader[OneHotEncoderModel] = new OneHotEncoderModelReader

  @Since("3.0.0")
  override def load(path: String): OneHotEncoderModel = super.load(path)
}

/**
 * Provides some helper methods used by `OneHotEncoder`.
 */
private[feature] object OneHotEncoderCommon {

  private def genOutputAttrNames(inputCol: StructField): Option[Array[String]] = {
    val inputAttr = Attribute.fromStructField(inputCol)
    inputAttr match {
      case nominal: NominalAttribute =>
        if (nominal.values.isDefined) {
          nominal.values
        } else if (nominal.numValues.isDefined) {
          nominal.numValues.map(n => Array.tabulate(n)(_.toString))
        } else {
          None
        }
      case binary: BinaryAttribute =>
        if (binary.values.isDefined) {
          binary.values
        } else {
          Some(Array.tabulate(2)(_.toString))
        }
      case _: NumericAttribute =>
        throw new RuntimeException(
          s"The input column ${inputCol.name} cannot be continuous-value.")
      case _ =>
        None // optimistic about unknown attributes
    }
  }

  /** Creates an `AttributeGroup` filled by the `BinaryAttribute` named as required. */
  private def genOutputAttrGroup(
      outputAttrNames: Option[Array[String]],
      outputColName: String): AttributeGroup = {
    outputAttrNames.map { attrNames =>
      val attrs: Array[Attribute] = attrNames.map { name =>
        BinaryAttribute.defaultAttr.withName(name)
      }
      new AttributeGroup(outputColName, attrs)
    }.getOrElse{
      new AttributeGroup(outputColName)
    }
  }

  /**
   * Prepares the `StructField` with proper metadata for `OneHotEncoder`'s output column.
   */
  def transformOutputColumnSchema(
      inputCol: StructField,
      outputColName: String,
      dropLast: Boolean,
      keepInvalid: Boolean = false): StructField = {
    val outputAttrNames = genOutputAttrNames(inputCol)
    val filteredOutputAttrNames = outputAttrNames.map { names =>
      if (dropLast && !keepInvalid) {
        require(names.length > 1,
          s"The input column ${inputCol.name} should have at least two distinct values.")
        names.dropRight(1)
      } else if (!dropLast && keepInvalid) {
        names ++ Seq("invalidValues")
      } else {
        names
      }
    }

    genOutputAttrGroup(filteredOutputAttrNames, outputColName).toStructField()
  }

  /**
   * This method is called when we want to generate `AttributeGroup` from actual data for
   * one-hot encoder.
   */
  def getOutputAttrGroupFromData(
      dataset: Dataset[_],
      inputColNames: Seq[String],
      outputColNames: Seq[String],
      dropLast: Boolean): Seq[AttributeGroup] = {
    // The RDD approach has advantage of early-stop if any values are invalid. It seems that
    // DataFrame ops don't have equivalent functions.
    val columns = inputColNames.map { inputColName =>
      col(inputColName).cast(DoubleType)
    }
    val numOfColumns = columns.length

    val numAttrsArray = dataset.select(columns: _*).rdd.map { row =>
      (0 until numOfColumns).map(idx => row.getDouble(idx)).toArray
    }.treeAggregate(new Array[Double](numOfColumns))(
      (maxValues, curValues) => {
        (0 until numOfColumns).foreach { idx =>
          val x = curValues(idx)
          assert(x <= Int.MaxValue,
            s"OneHotEncoder only supports up to ${Int.MaxValue} indices, but got $x.")
          assert(x >= 0.0 && x == x.toInt,
            s"Values from column ${inputColNames(idx)} must be indices, but got $x.")
          maxValues(idx) = math.max(maxValues(idx), x)
        }
        maxValues
      },
      (m0, m1) => {
        (0 until numOfColumns).foreach { idx =>
          m0(idx) = math.max(m0(idx), m1(idx))
        }
        m0
      }
    ).map(_.toInt + 1)

    outputColNames.zip(numAttrsArray).map { case (outputColName, numAttrs) =>
      createAttrGroupForAttrNames(outputColName, numAttrs, dropLast, keepInvalid = false)
    }
  }

  /** Creates an `AttributeGroup` with the required number of `BinaryAttribute`. */
  def createAttrGroupForAttrNames(
      outputColName: String,
      numAttrs: Int,
      dropLast: Boolean,
      keepInvalid: Boolean): AttributeGroup = {
    val outputAttrNames = Array.tabulate(numAttrs)(_.toString)
    val filtered = if (dropLast && !keepInvalid) {
      outputAttrNames.dropRight(1)
    } else if (!dropLast && keepInvalid) {
      outputAttrNames ++ Seq("invalidValues")
    } else {
      outputAttrNames
    }
    genOutputAttrGroup(Some(filtered), outputColName)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Data.Items;
using Glass.Sitecore.Mapper.Configuration;
using Glass.Sitecore.Mapper.Configuration.Attributes;
using System.Reflection;

namespace Glass.Sitecore.Mapper.Data
{
    public abstract class AbstractSitecoreDataHandler : ICloneable
    {
        /// <summary>
        /// Sets the property on the target object using data from the Sitecore Item
        /// </summary>
        /// <param name="target">The object to set the value on</param>
        /// <param name="item">The item to pull the data from</param>
        /// <param name="context">The current instance context</param>
        public void SetProperty(object target, Item item, ISitecoreService service)
        {
            object value = null;

            value = this.GetValue(item, service);
            if(value != null)
                Property.SetValue(target, value, null);
        }
        /// <summary>
        /// Reads a property from an object and sets the value on the Sitecore Item
        /// </summary>
        /// <param name="target">The object to read the value from</param>
        /// <param name="item">The item to write the value to</param>
        /// <param name="context">The instance context operating on the target</param>
        public void ReadProperty(object target, Item item, ISitecoreService service)
        {

            object value = Property.GetValue(target, null);
            this.SetValue(item, value, service);
        }

        /// <summary>
        /// The class property the handler is setting
        /// </summary>
        internal PropertyInfo Property
        {
            get;
            set;
        }

        /// <summary>
        /// Reads settings from the property and sets up the data handler.
        /// </summary>
        internal virtual void ConfigureDataHandler(SitecoreProperty scProperty)
        {
            Property = scProperty.Property;
        }

        /// <summary>
        /// Determines if the Data Handler will handle the passed in Property
        /// </summary>
        /// <param name="property"></param>
        /// <param name="datas"></param>
        /// <param name="classes"></param>
        /// <returns></returns>
        public abstract bool WillHandle(SitecoreProperty property, IEnumerable<AbstractSitecoreDataHandler> datas, Dictionary<Type, SitecoreClassConfig> classes);

        /// <summary>
        /// Reads an item from the Sitecore item and returns it as the requested return type
        /// </summary>
        /// <param name="target">The object that the value will be set on</param>
        /// <param name="item">The Sitecore item to work on</param>
        /// <param name="context">The context used to load the target object</param>
        /// <returns></returns>
        public abstract object GetValue(Item item, ISitecoreService service);

        /// <summary>
        /// Sets a value on the Sitecore item
        /// </summary>
        /// <param name="target">The object that the value was read from</param>
        /// <param name="item">The Sitecore item to write the value to</param>
        /// <param name="value">The value to be set</param>
        /// <param name="context">The context used to load the target object</param>
        public abstract void SetValue(Item item, object value, ISitecoreService service);

        /// <summary>
        /// Indicates the data handler can be used to set a value on a Sitecore item.
        /// </summary>
        public abstract bool CanSetValue { get; }

        #region ICloneable Members

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        #endregion

    }
}


text:
CAbits=1024
SSLEAY="../apps/openssl"
CONF="-config ../apps/openssl.cnf"

# create pca request.
echo creating $CAbits bit PCA cert request
$SSLEAY req $CONF \
	-new -sha256 -newkey $CAbits \
	-keyout pca-key.pem \
	-out pca-req.pem -nodes >/dev/null <<EOF
AU
Queensland
.
CryptSoft Pty Ltd
.
Test PCA (1024 bit)

EOF

if [ $? != 0 ]; then
	echo problems generating PCA request
	exit 1
fi

#sign it.
echo
echo self signing PCA
$SSLEAY x509 -sha256 -days 36525 \
	-req -signkey pca-key.pem \
	-CAcreateserial -CAserial pca-cert.srl \
	-in pca-req.pem -out pca-cert.pem

if [ $? != 0 ]; then
	echo problems self signing PCA cert
	exit 1
fi
echo

# create ca request.
echo creating $CAbits bit CA cert request
$SSLEAY req $CONF \
	-new -sha256 -newkey $CAbits \
	-keyout ca-key.pem \
	-out ca-req.pem -nodes >/dev/null <<EOF
AU
Queensland
.
CryptSoft Pty Ltd
.
Test CA (1024 bit)

EOF

if [ $? != 0 ]; then
	echo problems generating CA request
	exit 1
fi

#sign it.
echo
echo signing CA
$SSLEAY x509 -sha256 -days 36525 \
	-req \
	-CAcreateserial -CAserial pca-cert.srl \
	-CA pca-cert.pem -CAkey pca-key.pem \
	-in ca-req.pem -out ca-cert.pem

if [ $? != 0 ]; then
	echo problems signing CA cert
	exit 1
fi
echo

# create server request.
echo creating 512 bit server cert request
$SSLEAY req $CONF \
	-new -sha256 -newkey 512 \
	-keyout s512-key.pem \
	-out s512-req.pem -nodes >/dev/null <<EOF
AU
Queensland
.
CryptSoft Pty Ltd
.
Server test cert (512 bit)

EOF

if [ $? != 0 ]; then
	echo problems generating 512 bit server cert request
	exit 1
fi

#sign it.
echo
echo signing 512 bit server cert
$SSLEAY x509 -sha256 -days 36525 \
	-req \
	-CAcreateserial -CAserial ca-cert.srl \
	-CA ca-cert.pem -CAkey ca-key.pem \
	-in s512-req.pem -out server.pem

if [ $? != 0 ]; then
	echo problems signing 512 bit server cert
	exit 1
fi
echo

# create 1024 bit server request.
echo creating 1024 bit server cert request
$SSLEAY req $CONF \
	-new -sha256 -newkey 1024 \
	-keyout s1024key.pem \
	-out s1024req.pem -nodes >/dev/null <<EOF
AU
Queensland
.
CryptSoft Pty Ltd
.
Server test cert (1024 bit)

EOF

if [ $? != 0 ]; then
	echo problems generating 1024 bit server cert request
	exit 1
fi

#sign it.
echo
echo signing 1024 bit server cert
$SSLEAY x509 -sha256 -days 36525 \
	-req \
	-CAcreateserial -CAserial ca-cert.srl \
	-CA ca-cert.pem -CAkey ca-key.pem \
	-in s1024req.pem -out server2.pem

if [ $? != 0 ]; then
	echo problems signing 1024 bit server cert
	exit 1
fi
echo

# create 512 bit client request.
echo creating 512 bit client cert request
$SSLEAY req $CONF \
	-new -sha256 -newkey 512 \
	-keyout c512-key.pem \
	-out c512-req.pem -nodes >/dev/null <<EOF
AU
Queensland
.
CryptSoft Pty Ltd
.
Client test cert (512 bit)

EOF

if [ $? != 0 ]; then
	echo problems generating 512 bit client cert request
	exit 1
fi

#sign it.
echo
echo signing 512 bit client cert
$SSLEAY x509 -sha256 -days 36525 \
	-req \
	-CAcreateserial -CAserial ca-cert.srl \
	-CA ca-cert.pem -CAkey ca-key.pem \
	-in c512-req.pem -out client.pem

if [ $? != 0 ]; then
	echo problems signing 512 bit client cert
	exit 1
fi

echo cleanup

cat pca-key.pem  >> pca-cert.pem
cat ca-key.pem   >> ca-cert.pem
cat s512-key.pem >> server.pem
cat s1024key.pem >> server2.pem
cat c512-key.pem >> client.pem

for i in pca-cert.pem ca-cert.pem server.pem server2.pem client.pem
do
$SSLEAY x509 -issuer -subject -in $i -noout >$$
cat $$
/bin/cat $i >>$$
/bin/mv $$ $i
done

#/bin/rm -f *key.pem *req.pem *.srl

echo Finished


text:
import { Component, OnInit, ChangeDetectorRef, ViewChild, AfterViewInit } from '@angular/core';
import { ProfileService } from '../../services/profile.service';
import { GroupingPlusName, GroupingSubheading, ReorderIndicator, AreaType } from '../../model/profile';
import { LightBoxConfig, LightBoxTypes } from '../../shared/component/light-box/light-box';
import { LightBoxIndicatorReorderConfig } from '../../shared/component/light-box-indicator-reorder/light-box-indicator-reorder.component';
import { forkJoin } from 'rxjs';
import { SpinnerComponent } from '../../shared/component/spinner/spinner.component';
// @ts-ignore: error TS2304: Cannot find name 'JQueryStatic'.
declare let $: JQueryStatic;

@Component({
  selector: 'app-indicators-reorder-view',
  templateUrl: './indicators-reorder-view.component.html',
  styleUrls: ['./indicators-reorder-view.component.css'],
  providers: [ProfileService]
})
export class IndicatorsReorderViewComponent implements OnInit {

  @ViewChild(SpinnerComponent, { static: true }) spinner;

  profileId: number;
  profileUrlKey: string;
  domainSequence: number;
  domainName: string;
  subheadingId: number;
  areaTypeId: number;
  areaTypeName: string;
  sequence: number;
  groupId: number;
  groupingPlusNames: GroupingPlusName[];
  groupingSubheadings: GroupingSubheading[];
  allgroupingSubheadings: GroupingSubheading[];
  areaTypes: AreaType[];
  reorderIndicators: ReorderIndicator[] = [];
  lightBoxConfig: LightBoxConfig;
  lightBoxIndicatorReorderConfig: LightBoxIndicatorReorderConfig;
  subheading: string;
  subheadingToEdit: string;
  errorMessage = '';

  currentLighBoxId: number;

  // The sequence will start negativaly and to add a subheading will be a decrease.
  // in this way it won't be any interferences with indicatorsIds
  readonly sequenceFistElementNegative = -2;
  readonly sequenceFirstElementIndicators = 1;

  constructor(private profileService: ProfileService, private ref: ChangeDetectorRef) { }

  ngOnInit() {

    // Read the attributes of the app-root tag and populate the local variables
    const appRootElement = $('#app-root');
    this.profileId = Number(appRootElement.attr('profile-id'));
    this.profileUrlKey = appRootElement.attr('profile-key');
    this.domainSequence = Number(appRootElement.attr('domain-seq'));
    this.areaTypeId = Number(appRootElement.attr('area-type-id'));
    this.groupId = Number(appRootElement.attr('group-id'));

    // Load indicators and subheadings data
    this.loadData();

    // Initialize lightBox count
    this.currentLighBoxId = this.sequenceFistElementNegative;
  }

  // Load the indicators and subheadings data from the database
  loadData() {
    const areaTypesObservable = this.profileService.getAllAreaTypes();
    const domainNameObservable = this.profileService.getDomainName(this.groupId, this.domainSequence);

    forkJoin([areaTypesObservable, domainNameObservable]).subscribe(results => {
      this.areaTypes = <AreaType[]>results[0];
      this.domainName = <string>results[1];

      this.areaTypeName = this.areaTypes.find(x => x.Id === this.areaTypeId).ShortName;
    });

    const groupingPlusNamesObservable = this.profileService.getGroupingPlusNames(this.profileUrlKey, this.domainSequence, this.areaTypeId);
    const groupingSubheadingsObservable = this.profileService.getGroupingSubheadingsForProfile(this.profileId);

    forkJoin([groupingPlusNamesObservable, groupingSubheadingsObservable]).subscribe(results => {
      this.groupingPlusNames = <GroupingPlusName[]>results[0];
      this.allgroupingSubheadings = <GroupingSubheading[]>results[1];

      this.groupingSubheadings = this.allgroupingSubheadings.filter(x => x.AreaTypeId === this.areaTypeId && x.GroupId === this.groupId);

      this.displayIndicatorsAndSubheadings();

      this.spinner.hide();
    });
  }

  // Display indicators and subheadings in a table
  displayIndicatorsAndSubheadings() {
    this.groupingPlusNames.forEach(groupingPlusName => {
      const groupingSubheadings = this.groupingSubheadings.filter(x => x.Sequence === groupingPlusName.Sequence);
      groupingSubheadings.forEach(groupingSubheading => {
        // Subheading
        this.addGroupingSubheadingToReorderIndicatorList(groupingSubheading, false);
      });

      // Indicator
      this.addGroupingPlusNameToReorderIndicatorList(groupingPlusName);
    });
  }

  // Add subheading to the reorder indicator list for display
  addGroupingSubheadingToReorderIndicatorList(groupingSubheading: GroupingSubheading, addToFirstPosition: boolean) {
    let reorderIndicator: ReorderIndicator;

    reorderIndicator = {
      IndicatorId: groupingSubheading.SubheadingId,
      IndicatorName: groupingSubheading.Subheading,
      Sequence: groupingSubheading.Sequence,
      SexId: -1,
      Sex: '',
      AgeId: -1,
      Age: '',
      IsSubheading: true
    }

    if (addToFirstPosition) {
      this.reorderIndicators.unshift(reorderIndicator);
    } else {
      this.reorderIndicators.push(reorderIndicator);
    }

    this.ref.detectChanges();
  }

  // Add indicator to the reorder indicator list for display
  addGroupingPlusNameToReorderIndicatorList(groupingPlusName: GroupingPlusName) {
    let reorderIndicator: ReorderIndicator;

    reorderIndicator = {
      IndicatorId: groupingPlusName.IndicatorId,
      IndicatorName: groupingPlusName.IndicatorName,
      Sequence: groupingPlusName.Sequence,
      SexId: groupingPlusName.SexId,
      Sex: groupingPlusName.Sex,
      AgeId: groupingPlusName.AgeId,
      Age: groupingPlusName.Age,
      IsSubheading: false
    }

    this.reorderIndicators.push(reorderIndicator);
  }

  // Save subheading details and indicators sequence changes to the database
  save() {
    // Define an array by reading all the rows displayed
    const rows = this.getindicatorsElementsFromTable();
    this.updateSequences(rows);

    // Save the details
    const formData: FormData = new FormData();
    formData.append('profileId', this.profileId.toString());
    formData.append('profileUrlKey', this.profileUrlKey);
    formData.append('domainSequence', this.domainSequence.toString());
    formData.append('areaTypeId', this.areaTypeId.toString());
    formData.append('groupId', this.groupId.toString());
    formData.append('groupingPlusNames', JSON.stringify(this.groupingPlusNames));
    formData.append('groupingSubheadings', JSON.stringify(this.groupingSubheadings));

    this.profileService.saveReorderedIndicators(formData)
      .subscribe(
        (response) => {
          // Saved successfully, go back to the previous page
          this.goToParentPage();
          this.currentLighBoxId = this.sequenceFistElementNegative;
        },
        (error) => {
          this.errorMessage = 'Unable to save the changes, please try again.
' +
            'If the issue persists then please contact the administrator.';
        }
      );
  }

  // Cancel button event
  cancel() {
    // Go back to the previous page
    this.goToParentPage();
  }

  // Function to redirect to the previous page
  goToParentPage() {
    window.location.href = 'profile/indicators/specific?ProfileKey=' +
      this.profileUrlKey +
      '&DomainSequence=' +
      this.domainSequence +
      '&SelectedAreaTypeId=' +
      this.areaTypeId;
  }

  // Add subheading button event, to show light box for add subheading confirmation
  addSubHeadingConfirmation() {
    // Get grouping subheadings associated with other area types
    const filteredGroupingSubheadings: GroupingSubheading[] = this.getGroupingSubheadingsOfOtherAreaTypes();

    // Show light box
    const config = new LightBoxIndicatorReorderConfig();
    config.Title = 'Add subheading';
    config.OkButtonText = 'Add';
    config.CancelButtonText = 'Cancel';
    config.InputBoxLabelName = 'Name';
    config.ActionType = 'ADD';
    config.Height = 400;

    if (filteredGroupingSubheadings.length > 0) {
      config.GroupingSubheadings = this.sortGroupingSubheadings(filteredGroupingSubheadings);
    }

    this.lightBoxIndicatorReorderConfig = config;
  }

  // Add subheading
  addSubheading() {
    let groupingSubheading: GroupingSubheading;

    groupingSubheading = {
      AreaTypeId: this.areaTypeId,
      GroupId: this.groupId,
      Sequence: 1,
      SubheadingId: this.currentLighBoxId,
      Subheading: this.subheading
    }

    this.groupingSubheadings.push(groupingSubheading);
    this.addGroupingSubheadingToReorderIndicatorList(groupingSubheading, true);

    // Adding one to the current number of lightboxes
    // It is decreasing to make differences between lightbox id that will be negative number
    // and indicators id that it will be positive always
    this.currentLighBoxId--;
  }

  // Show light box for edit subheading confirmation
  editSubheadingConfirmation(subheadingId: number) {
    this.subheadingId = subheadingId;

    const subheading = this.groupingSubheadings.find(x => x.SubheadingId === subheadingId).Subheading;
    this.subheading = subheading;
    this.subheadingToEdit = subheading;

    // Get grouping subheadings associated with other area types
    const filteredGroupingSubheadings: GroupingSubheading[] = this.getGroupingSubheadingsOfOtherAreaTypes();

    // Show light box
    const config = new LightBoxIndicatorReorderConfig();
    config.Title = 'Edit subheading';
    config.OkButtonText = 'Save';
    config.CancelButtonText = 'Cancel';
    config.InputBoxLabelName = 'Name';
    config.Height = 400;
    config.InputBoxText = this.subheading;
    config.ActionType = 'EDIT';

    if (filteredGroupingSubheadings.length > 0) {
      config.GroupingSubheadings = this.sortGroupingSubheadings(filteredGroupingSubheadings);
    }

    this.lightBoxIndicatorReorderConfig = config;
  }

  // Edit subheading
  editSubheading() {
    this.groupingSubheadings.find(x => x.SubheadingId === this.subheadingId).Subheading = this.subheading;
    this.reorderIndicators.find(x => x.IndicatorId === this.subheadingId && x.IsSubheading === true).IndicatorName = this.subheading;
    this.ref.detectChanges();
  }

  // Show light box for delete subheading confirmation
  deleteSubheadingConfirmation(subheadingId: number) {
    this.subheadingId = subheadingId;
    const subheading = this.groupingSubheadings.find(x => x.SubheadingId === subheadingId).Subheading;

    // Show light box
    const config = new LightBoxConfig();
    config.Type = LightBoxTypes.OkCancel;
    config.Title = 'Delete subheading';
    config.Html = 'Are you sure you want to delete the subheading ' + subheading + '?';
    config.OkButtonText = 'Delete';
    config.CancelButtonText = 'Cancel';
    config.ActionType = 'DELETE';
    this.lightBoxConfig = config;
  }

  // Delete subheading
  deleteSubheading() {
    const groupingSubheadingToDeleteIndex = this.groupingSubheadings.findIndex(x => x.SubheadingId === this.subheadingId);
    this.groupingSubheadings.splice(groupingSubheadingToDeleteIndex, 1);

    const reorderIndicatorToDeleteIndex = this.reorderIndicators.findIndex(x => x.IndicatorId === this.subheadingId);
    this.reorderIndicators.splice(reorderIndicatorToDeleteIndex, 1);

    this.ref.detectChanges();
  }

  // Sort grouping subheadings
  sortGroupingSubheadings(groupingSubheadings: GroupingSubheading[]): GroupingSubheading[] {
    let sortedGroupingSubheadings: GroupingSubheading[] = [];
    sortedGroupingSubheadings = groupingSubheadings.slice(0);

    sortedGroupingSubheadings.sort((a, b): number => {
      if (a.Subheading  b.Subheading) {
        return 1;
      } else {
        return 0;
      }
    });

    return sortedGroupingSubheadings;
  }

  getGroupingSubheadingsOfOtherAreaTypes(): GroupingSubheading[] {
    const groupingSubheadingsOfOtherAreaTypes = this.allgroupingSubheadings.filter(x => x.AreaTypeId !== this.areaTypeId);
    const filteredGroupingSubheadings: GroupingSubheading[] = [];

    groupingSubheadingsOfOtherAreaTypes.forEach(groupingSubheadingsOfOtherAreaType => {
      if (this.groupingSubheadings.findIndex(x => x.Subheading.toLowerCase() ===
        groupingSubheadingsOfOtherAreaType.Subheading.toLowerCase()) === -1) {

        if (filteredGroupingSubheadings.findIndex(x => x.Subheading.toLowerCase() ===
          groupingSubheadingsOfOtherAreaType.Subheading.toLowerCase()) === -1) {

          filteredGroupingSubheadings.push(groupingSubheadingsOfOtherAreaType);
        }
      }
    });

    return filteredGroupingSubheadings;
  }

  // Event emitter functions
  updateLightBoxInputText(subheading: string) {
    this.subheading = subheading;
  }

  updateLightBoxActionConfirmed(actionConfirmed: boolean) {
    if (actionConfirmed) {
      switch (this.lightBoxConfig.ActionType) {
        case 'DELETE':
          this.deleteSubheading();
          break;
      }
    }
  }

  updateLightBoxIndicatorReorderActionConfirmed(actionConfirmed: boolean) {
    if (actionConfirmed) {
      switch (this.lightBoxIndicatorReorderConfig.ActionType) {
        case 'ADD':
          this.addSubheading();
          break;
        case 'EDIT':
          this.editSubheading();
          break;
      }
    }
  }

  getindicatorsElementsFromTable(): HTMLElement[] {
    return Array.from($('.tablesorter-dataRow'));
  }

  // Add the proper sequence for elements into the table position
  updateSequences(rows: HTMLElement[]) {

    let sequenceIndicatorsCounter = this.sequenceFirstElementIndicators;
    rows.forEach(row => {

      const tds = (<HTMLTableRowElement>row).children;

      const isSubheading = tds[0].textContent;
      const sexId = Number(tds[1].textContent);
      const ageId = Number(tds[2].textContent);
      const contentId = Number(tds[4].textContent);

      if (isSubheading === 'false') {
        this.groupingPlusNames.find(x => x.IndicatorId === contentId &&
          x.SexId === sexId &&
          x.AgeId === ageId).Sequence = sequenceIndicatorsCounter;

        sequenceIndicatorsCounter++;
      } else {
        this.groupingSubheadings.find(x => x.SubheadingId === contentId).Sequence = sequenceIndicatorsCounter;
      }
    });
  }
}

$(function () {

  // JQuery UI methods should be cast to <any> to avoid compile time errors
  (<any>$('tbody')).sortable({
    items: '> tr',
    stop: function (event, ui) {
      // Define an array by reading all the rows displayed
      const rows = Array.from($('.tablesorter-dataRow'));

      // Update the sequence for indicators
      let sequenceCounter = 0;
      rows.forEach(row => {
        const tds = (<HTMLTableRowElement>row).children;
        const isSubheading = tds[0].textContent;
        if (isSubheading === 'false') {
          sequenceCounter++;
          tds[3].textContent = sequenceCounter.toString();
        }
      });

      // Update the sequence for subheadings
      let rowCounter = 0;
      rows.forEach(row => {
        const tds = (<HTMLTableRowElement>row).children;
        const isSubheading = tds[0].textContent;
        const td = tds[3];
        if (isSubheading === 'true') {
          $(td).addClass('white');

          const tdsNextRow = (<HTMLTableRowElement>rows[rowCounter + 1]).children;
          if (tdsNextRow[0].textContent === 'true') {
            td.textContent = '1';
          } else {
            td.textContent = tdsNextRow[3].textContent;
          }
        }

        rowCounter++;
      });
    }
  });
});


text:
package mobtown.domain;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * Converter which helps JPA persist java.time values
 * http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/
 */
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime date) {
        return date == null ? null : Timestamp.valueOf(date);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlDate) {
        return sqlDate == null ? null : sqlDate.toLocalDateTime();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/rl_school"
              android:layout_width="wrap_content"
              android:layout_height="58dp"
               android:background="@color/white"
                    android:paddingLeft="15dp"
            >

<com.woniukeji.jianmerchant.widget.CircleImageView
    android:id="@+id/circle_talk_head"
    android:layout_width="38dp"
    android:layout_height="38dp"
    android:layout_marginTop="10dp"

    android:src="@mipmap/ic_launcher"
    />
    <LinearLayout
        android:layout_toRightOf="@+id/circle_talk_head"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="10dp"
        android:layout_centerVertical="true"
        >
        <TextView
            android:id="@+id/tv_nick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="徐佳莹"
            android:textSize="14dp"
            android:textColor="@color/black"
            android:layout_marginTop="5dp"
            />
        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="还要找三个人呢"
            android:textSize="12dp"
            android:layout_marginTop="5dp"
            android:textColor="#9B9B9B"
            />
    </LinearLayout>
    <TextView
        android:id="@+id/tv_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#9B9B9B"
        android:textSize="12dp"
        android:layout_alignParentRight="true"
        android:text="3月2号"
        android:layout_marginTop="12dp"
        android:layout_marginRight="15dp"
        />
<TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/gray_btn_bg_color"
    android:layout_alignParentBottom="true"
    />
</RelativeLayout>


text:
set -e

logger -t devvm "Install started: $?"

help()
{
    echo "This script sets up a node, and configures pre-installed Splunk Enterprise"
    echo "Usage: "
    echo "Parameters:"
    echo "- s: Azure subscription ID"
    echo "- a: Storage account name"
    echo "- k: Storage account key (password)"
    echo "- l: MSI client id (principal id)"
    echo "- u: User account name"
    echo "- d: Ubuntu Desktop GUI"
    echo "- h: help"
}

# Log method to control log output
log()
{
    echo "`date`: $1"
}

# You must be root to run this script
if [ "${UID}" -ne 0 ];
then
    log "Script executed without root permissions"
    echo "You must be root to run this program." >&2
    exit 3
fi

# Arguments
while getopts :s:a:k:l:u:d: optname; do
  if [[ $optname != 'e' && $optname != 'k' ]]; then
    log "Option $optname set with value ${OPTARG}"
  fi
  case $optname in
    s) #azure subscription id
      SUBSCRIPTION_ID=${OPTARG}
      ;;
    a) #storage account name
      STORAGE_ACCOUNT_NAME=${OPTARG}
      ;;
    k) #storage account key
      STORAGE_ACCOUNT_KEY=${OPTARG}
      ;;
    l) #PrincipalId of the MSI identity
      MSI_PRINCIPAL_ID=${OPTARG}
      ;;
    u) #user account name
      USERNAME=${OPTARG}
      ;;
    d) #Desktop installation
      DESKTOPINSTALL=${OPTARG}
      ;;
    h) #Show help
      help
      exit 2
      ;;
    \?) #Unrecognized option - show help
      echo -e \\n"Option -${BOLD}$OPTARG${NORM} not allowed."
      help
      exit 2
      ;;
  esac
done

TEMPLATEFOLDER="/home/$USERNAME/tfTemplate"
REMOTESTATEFILE="$TEMPLATEFOLDER/remoteState.tf"
ACCESSKEYFILE="/home/$USERNAME/access_key"
TFENVFILE="/home/$USERNAME/tfEnv.sh"
CREDSFILE="$TEMPLATEFOLDER/azureProviderAndCreds.tf"

mkdir $TEMPLATEFOLDER

cp ./azureProviderAndCreds.tf $TEMPLATEFOLDER
chmod 666 $CREDSFILE

touch $REMOTESTATEFILE
echo "terraform {"                                          >> $REMOTESTATEFILE
echo " backend \"azurerm\" {"                               >> $REMOTESTATEFILE
echo "  storage_account_name = \"$STORAGE_ACCOUNT_NAME\""   >> $REMOTESTATEFILE
echo "  container_name       = \"terraform-state\""         >> $REMOTESTATEFILE
echo "  key                  = \"prod.terraform.tfstate\""  >> $REMOTESTATEFILE
echo "  }"                                                  >> $REMOTESTATEFILE
echo "}"                                                    >> $REMOTESTATEFILE
chmod 666 $REMOTESTATEFILE

chown -R $USERNAME:$USERNAME /home/$USERNAME/tfTemplate

touch $ACCESSKEYFILE
echo "access_key = \"$STORAGE_ACCOUNT_KEY\""                >> $ACCESSKEYFILE
chmod 666 $ACCESSKEYFILE
chown $USERNAME:$USERNAME $ACCESSKEYFILE

touch $TFENVFILE
echo "export ARM_SUBSCRIPTION_ID =\"$SUBSCRIPTION_ID\""     >> $TFENVFILE
echo "export ARM_CLIENT_ID       =\"$MSI_PRINCIPAL_ID\""    >> $TFENVFILE
chmod 755 $TFENVFILE
chown $USERNAME:$USERNAME $TFENVFILE

# create the container for remote state
logger -t devvm "Creating the container for remote state"
az login --msi
az storage container create -n terraform-state --account-name $STORAGE_ACCOUNT_NAME --account-key $STORAGE_ACCOUNT_KEY
logger -t devvm "Container for remote state created: $?"

if [[ -v DESKTOPINSTALL ]]; then
    echo "Installing Mate Desktop"
    bash ./desktop.sh
    echo "Desktop installed"
fi


text:
<?php namespace Tamayo\Stretchy\Index;

use Closure;
use Tamayo\Stretchy\Connection;
use Tamayo\Stretchy\Index\Grammar;

class Blueprint {

	/**
	 * Elastic Index Name.
	 *
	 * @var string
	 */
	protected $index;

	/**
	 * Shards quantity.
	 *
	 * @var integer
	 */
	protected $shards = 2;

	/**
	 * Replicas quantity.
	 *
	 * @var integer
	 */
	protected $replicas = 0;

	/**
	 * Index fields.
	 *
	 * @var array
	 */
	protected $fields = array();

	/**
	 * The command to run to Eslastic.
	 *
	 * @var string
	 */
	protected $command;

	/**
	 * Creation Date.
	 *
	 * @var integer
	 */
	protected $creationDate;

	/**
	 * Create a new Index Blueprint.
	 *
	 * @param string  $index
	 * @param Closure $callback
	 */
	public function __construct($index, Closure $callback = null)
	{
		$this->index = $index;

		if ( ! is_null($callback)) $callback($this);
	}

	/**
	 * Indicates that the index needs to be created.
	 *
	 * @return void
	 */
	public function create()
	{
		$this->command = 'indexCreate';
	}

	/**
	 * Indicates that the index needs to be deleted.
	 *
	 * @return void
	 */
	public function delete()
	{
		$this->command = 'indexDelete';
	}

	/**
	 * Specify number of index shards.
	 *
	 * @param  integer $quantity
	 * @return \Tamayo\Stretchy\Index\Builder
	 */
	public function shards($quantity)
	{
		$this->shards = $quantity;

		return $this;
	}

	/**
	 * Specify number of index replicas.
	 *
	 * @param  integer $quantity
	 * @return \Tamayo\Stretchy\Index\Builder
	 */
	public function replicas($quantity)
	{
		$this->replicas = $quantity;

		return $this;
	}

	/**
	 * Set Index creation timestamp.
	 *
	 * @param  integer $date
	 * @return \Tamayo\Stretchy\Index\Builder
	 */
	public function creationDate($date)
	{
		$this->creationDate = $date;

		return $this;
	}

	/**
	 * Execute the index operation to Elastic.
	 *
	 * @param  Connection $connection
	 * @param  Grammar    $grammar
	 * @return void
	 */
	public function build(Connection $connection, Grammar $grammar)
	{
		$method = $this->command;

		$connection->$method($this->toArray($connection, $grammar));
	}

	/**
	 * Get the raw json statements for the blueprint.
	 *
	 * @param  Connection $connection
	 * @param  Grammar    $grammar
	 * @return string
	 */
	public function toJson(Connection $connection, Grammar $grammar, $options = 0)
	{
		return json_encode($this->toArray($connection, $grammar), $options);
	}

	/**
	 * Get the raw array statements for the blueprint.
	 *
	 * @param  Connection $connection
	 * @param  Grammar    $grammar
	 * @return array
	 */
	public function toArray(Connection $connection, Grammar $grammar)
	{
		$method = 'compile'.ucfirst($this->command);

		return $grammar->$method($this, $connection);
	}

	/**
	 * Get the name of the index.
	 *
	 * @return string
	 */
	public function getIndex()
	{
		return $this->index;
	}

	/**
	 * Get the shards count.
	 *
	 * @return integer
	 */
	public function getShards()
	{
		return $this->shards;
	}

	/**
	 * Get the replicas count.
	 *
	 * @return integer
	 */
	public function getReplicas()
	{
		return $this->replicas;
	}

}


text:
class CommonTasks
{

    public:
       static void startUpdater(const QString& program, const QStringList& args);

    signals:

    public slots:
};

#endif // COMMONTASKS_H