text:
package com.viesis.viescraft.api.util;

import org.lwjgl.input.Keyboard;

import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.fml.client.registry.ClientRegistry;

public class Keybinds {

	public static KeyBinding[] keyBindings;

	public static KeyBinding vcForward;
	public static KeyBinding vcBack;
	public static KeyBinding vcLeft;
	public static KeyBinding vcRight;
	public static KeyBinding vcUp;
	public static KeyBinding vcDown;
	public static KeyBinding vcInventory;
	public static KeyBinding vcDropBomb;
	///public static KeyBinding vcModule;

	public static void init()
	{
		vcForward = new KeyBinding("vc.key.moveForward", Keyboard.KEY_W, "vc.key.viescraft");
		vcBack = new KeyBinding("vc.key.moveBack", Keyboard.KEY_S, "vc.key.viescraft");
		vcLeft = new KeyBinding("vc.key.moveLeft", Keyboard.KEY_A, "vc.key.viescraft");
		vcRight = new KeyBinding("vc.key.moveRight", Keyboard.KEY_D, "vc.key.viescraft");
		vcUp = new KeyBinding("vc.key.moveUp", Keyboard.KEY_SPACE, "vc.key.viescraft");
		vcDown = new KeyBinding("vc.key.moveDown", Keyboard.KEY_X, "vc.key.viescraft");
		vcInventory = new KeyBinding("vc.key.openInventory", Keyboard.KEY_R, "vc.key.viescraft");
		vcDropBomb = new KeyBinding("vc.key.dropbomb", Keyboard.KEY_C, "vc.key.viescraft");
		///vcModule = new KeyBinding("vc.key.useModule", Keyboard.KEY_C, "vc.key.viescraft");

		//Register KeyBingings
		ClientRegistry.registerKeyBinding(vcForward);
		ClientRegistry.registerKeyBinding(vcBack);
		ClientRegistry.registerKeyBinding(vcLeft);
		ClientRegistry.registerKeyBinding(vcRight);
		ClientRegistry.registerKeyBinding(vcUp);
		ClientRegistry.registerKeyBinding(vcDown);
		ClientRegistry.registerKeyBinding(vcInventory);
		ClientRegistry.registerKeyBinding(vcDropBomb);
		///ClientRegistry.registerKeyBinding(vcModule);
	}
}


text:
package io.minhasaude.msapi.exceptionhandler;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.apache.commons.lang3.exception.ExceptionUtils;

import io.minhasaude.msapi.service.exception.EnderecoInexistenteException;
import io.minhasaude.msapi.service.exception.TelefoneInexistenteException;

@ControllerAdvice
public class MsExceptionHandler extends ResponseEntityExceptionHandler {

	@Autowired
	private MessageSource messageSource;

	@Override
	protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
			HttpHeaders headers, HttpStatus status, WebRequest request) {

		String mensagemUsuario = messageSource.getMessage("mensagem.invalida", null, LocaleContextHolder.getLocale());
		String mensagemDesenvolvedor = ex.getCause().toString();
		List<Erro> erros = Arrays.asList(new Erro(mensagemUsuario, mensagemDesenvolvedor));
		return handleExceptionInternal(ex, erros, headers, HttpStatus.BAD_REQUEST, request);
	}

	@Override
	protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
			HttpHeaders headers, HttpStatus status, WebRequest request) {

		List<Erro> erros = criarListaDeErros(ex.getBindingResult());
		return handleExceptionInternal(ex, erros, headers, HttpStatus.BAD_REQUEST, request);
	}

	@ExceptionHandler({ TelefoneInexistenteException.class })
	public ResponseEntity<Object> handleTelefoneInexistenteException(TelefoneInexistenteException ex) {
		String mensagemUsuario = messageSource.getMessage("telefone.inexistente", null, LocaleContextHolder.getLocale());
		String mensagemDesenvolvedor = ex.toString();
		List<Erro> erros = Arrays.asList(new Erro(mensagemUsuario, mensagemDesenvolvedor));
		return ResponseEntity.badRequest().body(erros);
	}

	@ExceptionHandler({ EnderecoInexistenteException.class })
	public ResponseEntity<Object> handleTelefoneInexistenteException(EnderecoInexistenteException ex) {
		String mensagemUsuario = messageSource.getMessage("endereco.inexistente", null, LocaleContextHolder.getLocale());
		String mensagemDesenvolvedor = ex.toString();
		List<Erro> erros = Arrays.asList(new Erro(mensagemUsuario, mensagemDesenvolvedor));
		return ResponseEntity.badRequest().body(erros);
	}

	@ExceptionHandler({ EmptyResultDataAccessException.class })
	public ResponseEntity<Object> handleEmptyResultDataAccessException(EmptyResultDataAccessException ex,
			WebRequest request) {
		String mensagemUsuario = messageSource.getMessage("recurso.nao-encontrado", null,LocaleContextHolder.getLocale());
		String mensagemDesenvolvedor = ex.toString();
		List<Erro> erros = Arrays.asList(new Erro(mensagemUsuario, mensagemDesenvolvedor));
		return handleExceptionInternal(ex, erros, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
	}

	@ExceptionHandler({ DataIntegrityViolationException.class } )
 	public ResponseEntity<Object> handleDataIntegrityViolationException(DataIntegrityViolationException ex, WebRequest request) {
		String mensagemUsuario = messageSource.getMessage("recurso.operacao-nao-permitida", null, LocaleContextHolder.getLocale());
		String mensagemDesenvolvedor = ExceptionUtils.getRootCauseMessage(ex);
		List<Erro> erros = Arrays.asList(new Erro(mensagemUsuario, mensagemDesenvolvedor));
		return handleExceptionInternal(ex, erros, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
	}

	private List<Erro> criarListaDeErros(BindingResult bindingResult) {
		List<Erro> erros = new ArrayList<>();

		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			String mensagemUsuario = messageSource.getMessage(fieldError, LocaleContextHolder.getLocale());
			String mensagemDesenvolvedor = fieldError.toString();
			erros.add(new Erro(mensagemUsuario, mensagemDesenvolvedor));
		}

		return erros;
	}

	public static class Erro {

		private String mensagemUsuario;
		private String mensagemDesenvolvedor;

		public Erro(String mensagemUsuario, String mensagemDesenvolvedor) {
			this.mensagemUsuario = mensagemUsuario;
			this.mensagemDesenvolvedor = mensagemDesenvolvedor;
		}

		public String getMensagemUsuario() {
			return mensagemUsuario;
		}

		public String getMensagemDesenvolvedor() {
			return mensagemDesenvolvedor;
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
describe "Erector coexistence support", :type => :rails do
  uses_rails_with_template :erector_coexistence_system_spec, :additional_gemfile_modifier => Proc.new { |gemfile| gemfile.ensure_gem!("erector") }

  begin
    gem 'erector'
  rescue Gem::LoadError => le
    # ok
  end

  begin
    require 'erector'
  rescue LoadError => le
    # ok
  end

  if defined?(::Erector::Widget)
    it "should be able to render a Fortitude widget in app/views" do
      expect_match("fortitude_widget_in_app_views", /this is Fortitude: foo = bar/)
    end

    it "should be able to render a Fortitude widget in app/v/views" do
      expect_match("fortitude_widget_in_app_v_views", /this is Fortitude: foo = marph/)
    end

    it "should be able to render an Erector widget in app/views" do
      expect_match("erector_widget_in_app_views", /<p\s+class\s*=\s*"some_class"\s*>this is Erector: foo = baz<\/p>/)
    end

    it "should be able to render an Erector widget in app/v/views" do
      expect_match("erector_widget_in_app_v_views", /<p\s+class\s*=\s*"some_class"\s*>this is Erector: foo = quux<\/p>/)
    end

    it "should be able to render a Fortitude widget using render :widget" do
      expect_match("render_widget_fortitude", /this is a Fortitude widget/)
    end

    it "should be able to render an Erector widget using render :widget" do
      expect_match("render_widget_erector", /this is an Erector widget/, :no_layout => true)
    end

    it "should be able to render a Fortitude widget from ERb using #widget" do
      expect_match("widget_from_erb_fortitude", /this is a Fortitude widget, Josephine.*this is a Fortitude widget, Amanda/mi)
    end

    it "should be able to render an Erector widget from ERb using #widget" do
      expect_match("widget_from_erb_erector", /this is an Erector widget, Josephine.*this is an Erector widget, Amanda/mi)
    end

    it "should be able to render a Fortitude widget with just a class using render :widget" do
      expect_match("render_widget_fortitude_class", /this is a Fortitude widget/)
    end

    it "should be able to render an Erector widget with just a class using render :widget" do
      expect_match("render_widget_erector_class", /this is an Erector widget/, :no_layout => true)
    end

    it "should be able to render an Erector widget from a Fortitude widget using just 'widget'" do
      expect_match("render_erector_widget_from_fortitude_widget",
        %r{before erector widget: this is my_helper\!\s*inside erector widget: this is my_helper\!, passed_foo\s*after erector widget: this is my_helper\!}mi)
    end

    it "should be able to render an Erector widget from a Fortitude widget using just 'widget' with an instantiated widget" do
      expect_match("render_erector_widget_from_fortitude_widget?instantiate_widget=true",
        %r{before erector widget: this is my_helper\!\s*inside erector widget: this is my_helper\!, passed_foo\s*after erector widget: this is my_helper\!}mi)
    end

    it "should be able to render a Fortitude widget from an Erector widget using just 'widget'" do
      expect_match("render_fortitude_widget_from_erector_widget",
        %r{before fortitude widget: this is my_helper\!\s*inside fortitude widget: this is my_helper\!, passed_foo\s*after fortitude widget: this is my_helper\!}mi)
    end

    it "should be able to render a Fortitude widget from an Erector widget using just 'widget' with an instantiated widget" do
      expect_match("render_fortitude_widget_from_erector_widget?instantiate_widget=true",
        %r{before fortitude widget: this is my_helper\!\s*inside fortitude widget: this is my_helper\!, passed_foo\s*after fortitude widget: this is my_helper\!}mi)
    end
  end
end


text:
require 'cgi'

module Ruremai
  module Locator
    class Rurema < Base
      URI_BASE = 'https://docs.ruby-lang.org/ja/'
      major, minor, teeny = *RUBY_VERSION.split('.').map(&:to_i)
      PATH_VERSION_PART = [major, minor, major >= 2 ? 0 : teeny].join(".")

      def candidates
        method_owner.ancestors.inject([]) {|all, mod| all + candidates_for(mod) }
      end

      private

      def candidates_for(mod)
        uri_part    = [PATH_VERSION_PART, 'method', escape(mod.name)].join('/')
        method_name = escape(name.to_s)

        # s: singleton mehtod, m: module function, i: instance method
        ordered_types = receiver.is_a?(Module) ? %w(s m i) : %w(i m s)
        ordered_types.map {|type|
          URI.parse("#{URI_BASE}#{uri_part}/#{type}/#{method_name}.html")
        }
      end

      def escape(str)
        CGI.escape(str).gsub(/(%[\dA-Z]{2})/) {|s|
          %(=#{s[1..-1].downcase})
        }
      end
    end
  end
end


text:
using System;
using System.Linq;
using UnityEngine;

/**
	data structure for AssetBundle and Asset information.

    list
        └ target // human readable target platform name.
    	└ version // human readable version desc.
    	└ assetBundles // assetBundleInfo[]
    		└ assetBundleInfo
    			└ bundleName // bundle name.
    			└ assetNames // contained asset names. e,g, "Assets/Somewhere/texture.png"
    			└ dependsBundleNames // the bundle names which this assetBundle depends on.
    			└ crc // crc parameter. used for crc check.
    			└ hash // hash parameter. used for exchange same asset from old one to new one.
    			└ size // size of uncompressed AssetBundle.
 */
namespace AutoyaFramework.AssetBundles
{

    /// <summary>
    /// Asset bundle list type.
    /// </summary>
    [Serializable]
    public class AssetBundleList
    {
        [SerializeField] public string identity;
        [SerializeField] public string target;
        [SerializeField] public string version;
        [SerializeField] public AssetBundleInfo[] assetBundles;

        public AssetBundleList() { }

        public AssetBundleList(string identity, string target, string version, AssetBundleInfo[] assetBundles)
        {
            this.identity = identity;
            this.target = target;
            this.version = version;
            this.assetBundles = assetBundles;
        }

        public AssetBundleList(AssetBundleList baseList)
        {
            this.identity = baseList.identity;
            this.target = baseList.target;
            this.version = baseList.version;
            this.assetBundles = new AssetBundleInfo[baseList.assetBundles.Length];
            for (var i = 0; i < assetBundles.Length; i++)
            {
                assetBundles[i] = new AssetBundleInfo(baseList.assetBundles[i]);
            }
        }

        public bool Exists()
        {
            var exists = !(string.IsNullOrEmpty(this.identity) || string.IsNullOrEmpty(this.target) || string.IsNullOrEmpty(this.version) || this.assetBundles.Length == 0);
            return exists;
        }
    }

    [Serializable]
    public struct AssetBundleInfo
    {
        [SerializeField] public string bundleName;
        [SerializeField] public string[] assetNames;
        [SerializeField] public string[] dependsBundleNames;
        [SerializeField] public uint crc;
        [SerializeField] public string hash;
        [SerializeField] public long size;

        public AssetBundleInfo(string bundleName, string[] assetNames, string[] dependsBundleNames, uint crc, string hash, long size)
        {
            this.bundleName = bundleName;
            this.assetNames = assetNames;
            this.dependsBundleNames = dependsBundleNames;
            this.crc = crc;
            this.hash = hash;
            this.size = size;
        }

        public AssetBundleInfo(AssetBundleInfo baseAssetBundleInfo)
        {
            this.bundleName = baseAssetBundleInfo.bundleName;
            this.assetNames = new string[baseAssetBundleInfo.assetNames.Length];
            for (var i = 0; i < assetNames.Length; i++)
            {
                assetNames[i] = baseAssetBundleInfo.assetNames[i];
            }

            this.dependsBundleNames = new string[baseAssetBundleInfo.dependsBundleNames.Length];
            for (var i = 0; i < dependsBundleNames.Length; i++)
            {
                dependsBundleNames[i] = baseAssetBundleInfo.dependsBundleNames[i];
            }

            this.crc = baseAssetBundleInfo.crc;
            this.hash = baseAssetBundleInfo.hash;
            this.size = baseAssetBundleInfo.size;
        }

        public static bool IsEmpty(AssetBundleInfo target)
        {
            return target.size == 0 || target.assetNames.Length == 0 || string.IsNullOrEmpty(target.bundleName);
        }
    }
}


text:
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <linux/input.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/reboot.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include <sys/wait.h>
#include <sys/limits.h>
#include <dirent.h>
#include <sys/stat.h>

#include <signal.h>
#include <sys/wait.h>

#include "bootloader.h"
#include "common.h"
#include "cutils/properties.h"
#include "firmware.h"
#include "install.h"
#include "make_ext4fs.h"
#include "minui/minui.h"
#include "minzip/DirUtil.h"
#include "roots.h"
#include "recovery_ui.h"

#include "extendedcommands.h"
#include "nandroid.h"
#include "mounts.h"
#include "flashutils/flashutils.h"
#include "edify/expr.h"
#include <libgen.h>
#include "mtdutils/mtdutils.h"
#include "bmlutils/bmlutils.h"
#include "cutils/android_reboot.h"
#include "mmcutils/mmcutils.h"
#include "voldclient/voldclient.h"

#include "adb_install.h"

#ifdef ENABLE_LOKI
#include "compact_loki.h"
#endif

int signature_check_enabled = 1;
#ifdef ENABLE_LOKI
int loki_support_enabled = 1;
#endif
int script_assert_enabled = 1;

int
get_filtered_menu_selection(const char** headers, char** items, int menu_only, int initial_selection, int items_count) {
    int index;
    int offset = 0;
    int* translate_table = (int*)malloc(sizeof(int) * items_count);
    for (index = 0; index < items_count; index++) {
        if (items[index] == NULL)
            continue;
        char *item = items[index];
        items[index] = NULL;
        items[offset] = item;
        translate_table[offset] = index;
        offset++;
    }
    items[offset] = NULL;

    initial_selection = translate_table[initial_selection];
    int ret = get_menu_selection(headers, items, menu_only, initial_selection);
    if (ret < 0 || ret >= offset) {
        free(translate_table);
        return ret;
    }

    ret = translate_table[ret];
    free(translate_table);
    return ret;
}

void write_string_to_file(const char* filename, const char* string) {
    ensure_path_mounted(filename);
    char tmp[PATH_MAX];
    sprintf(tmp, "mkdir -p $(dirname %s)", filename);
    __system(tmp);
    FILE *file = fopen(filename, "w");
    if( file != NULL) {
        fprintf(file, "%s", string);
        fclose(file);
    }
}

void write_recovery_version() {
    char path[PATH_MAX];
    sprintf(path, "%s%sclockworkmod/.recovery_version", get_primary_storage_path(), (is_data_media() ? "/0/" : "/"));
    write_string_to_file(path,EXPAND(RECOVERY_VERSION) "\n" EXPAND(TARGET_DEVICE));
    // force unmount /data on /data/media devices as we call this on recovery start
    ignore_data_media_workaround(1);
    ensure_path_unmounted(path);
    ignore_data_media_workaround(0);
}

void
toggle_signature_check()
{
    signature_check_enabled = !signature_check_enabled;
    ui_print("Signature Check: %s\n", signature_check_enabled ? "Enabled" : "Disabled");
}

#ifdef ENABLE_LOKI
void
toggle_loki_support()
{
    loki_support_enabled = !loki_support_enabled;
    ui_print("Loki Support: %s\n", loki_support_enabled ? "Enabled" : "Disabled");
}
#endif

int install_zip(const char* packagefilepath)
{
    ui_print("\n-- Installing: %s\n", packagefilepath);
    if (device_flash_type() == MTD) {
        set_sdcard_update_bootloader_message();
    }
    int status = install_package(packagefilepath);
    ui_reset_progress();
    if (status != INSTALL_SUCCESS) {
        ui_set_background(BACKGROUND_ICON_ERROR);
        ui_print("Installation aborted.\n");
        return 1;
    }
#ifdef ENABLE_LOKI
    if(loki_support_enabled) {
       ui_print("Checking if loki-fying is needed");
       if (loki_check() != 0) {
           return 1;
       }
    }
#endif
    ui_set_background(BACKGROUND_ICON_NONE);
    ui_print("\nInstall from sdcard complete.\n");
    return 0;
}

#define ITEM_CHOOSE_ZIP       0
#define ITEM_APPLY_SIDELOAD   1
#define ITEM_SIG_CHECK        2
#define ITEM_CHOOSE_ZIP_INT   3

int show_install_update_menu()
{
    char buf[100];
    int i = 0, chosen_item = 0;
    static char* install_menu_items[MAX_NUM_MANAGED_VOLUMES + 3];

    char* primary_path = get_primary_storage_path();
    char** extra_paths = get_extra_storage_paths();
    int num_extra_volumes = get_num_extra_volumes();

    memset(install_menu_items, 0, MAX_NUM_MANAGED_VOLUMES + 3);

    static const char* headers[] = {  "Install update from zip file",
                                "",
                                NULL
    };

    sprintf(buf, "choose zip from %s", primary_path);
    install_menu_items[0] = strdup(buf);

    install_menu_items[1] = "install zip from sideload";

    install_menu_items[2] = "toggle signature verification";

    install_menu_items[3 + num_extra_volumes] = NULL;

    for (i = 0; i < num_extra_volumes; i++) {
        sprintf(buf, "choose zip from %s", extra_paths[i]);
        install_menu_items[3 + i] = strdup(buf);
    }

    for (;;)
    {
        chosen_item = get_menu_selection(headers, install_menu_items, 0, 0);
        switch (chosen_item)
        {
            case ITEM_SIG_CHECK:
                toggle_signature_check();
                break;
            case ITEM_CHOOSE_ZIP:
                show_choose_zip_menu(primary_path);
                break;
            case ITEM_APPLY_SIDELOAD:
                apply_from_adb();
                break;
            default:
                if (chosen_item >= ITEM_CHOOSE_ZIP_INT) {
                    show_choose_zip_menu(extra_paths[chosen_item - 3]);
                } else {
                    goto out;
                }
        }
    }
out:
    // free all the dynamic items
    free(install_menu_items[0]);
    if (extra_paths != NULL) {
        for (i = 0; i < num_extra_volumes; i++)
            free(install_menu_items[3 + i]);
    }
    return chosen_item;
}

void free_string_array(char** array)
{
    if (array == NULL)
        return;
    char* cursor = array[0];
    int i = 0;
    while (cursor != NULL)
    {
        free(cursor);
        cursor = array[++i];
    }
    free(array);
}

char** gather_files(const char* directory, const char* fileExtensionOrDirectory, int* numFiles)
{
    char path[PATH_MAX] = "";
    DIR *dir;
    struct dirent *de;
    int total = 0;
    int i;
    char** files = NULL;
    int pass;
    *numFiles = 0;
    int dirLen = strlen(directory);

    dir = opendir(directory);
    if (dir == NULL) {
        ui_print("Couldn't open directory.\n");
        return NULL;
    }

    unsigned int extension_length = 0;
    if (fileExtensionOrDirectory != NULL)
        extension_length = strlen(fileExtensionOrDirectory);

    int isCounting = 1;
    i = 0;
    for (pass = 0; pass < 2; pass++) {
        while ((de=readdir(dir)) != NULL) {
            // skip hidden files
            if (de->d_name[0] == '.')
                continue;

            // NULL means that we are gathering directories, so skip this
            if (fileExtensionOrDirectory != NULL)
            {
                // make sure that we can have the desired extension (prevent seg fault)
                if (strlen(de->d_name) < extension_length)
                    continue;
                // compare the extension
                if (strcmp(de->d_name + strlen(de->d_name) - extension_length, fileExtensionOrDirectory) != 0)
                    continue;
            }
            else
            {
                struct stat info;
                char fullFileName[PATH_MAX];
                strcpy(fullFileName, directory);
                strcat(fullFileName, de->d_name);
                lstat(fullFileName, &info);
                // make sure it is a directory
                if (!(S_ISDIR(info.st_mode)))
                    continue;
            }

            if (pass == 0)
            {
                total++;
                continue;
            }

            files[i] = (char*) malloc(dirLen + strlen(de->d_name) + 2);
            strcpy(files[i], directory);
            strcat(files[i], de->d_name);
            if (fileExtensionOrDirectory == NULL)
                strcat(files[i], "/");
            i++;
        }
        if (pass == 1)
            break;
        if (total == 0)
            break;
        rewinddir(dir);
        *numFiles = total;
        files = (char**) malloc((total+1)*sizeof(char*));
        files[total]=NULL;
    }

    if(closedir(dir) < 0) {
        LOGE("Failed to close directory.\n");
    }

    if (total==0) {
        return NULL;
    }

    // sort the result
    if (files != NULL) {
        for (i = 0; i < total; i++) {
            int curMax = -1;
            int j;
            for (j = 0; j < total - i; j++) {
                if (curMax == -1 || strcmp(files[curMax], files[j]) < 0)
                    curMax = j;
            }
            char* temp = files[curMax];
            files[curMax] = files[total - i - 1];
            files[total - i - 1] = temp;
        }
    }

    return files;
}

// pass in NULL for fileExtensionOrDirectory and you will get a directory chooser
char* choose_file_menu(const char* basedir, const char* fileExtensionOrDirectory, const char* headers[])
{
    static const char* fixed_headers[20];
    char path[PATH_MAX] = "";
    DIR *dir;
    struct dirent *de;
    int numFiles = 0;
    int numDirs = 0;
    int i;
    char* return_value = NULL;
    char directory[PATH_MAX];
    int dir_len = strlen(basedir);

    strcpy(directory, basedir);

    // Append a traiing slash if necessary
    if (directory[dir_len - 1] != '/') {
        strcat(directory, "/");
        dir_len++;
    }

    i = 0;
    while (headers[i]) {
        i++;
    }
    i = 0;
    while (headers[i]) {
        fixed_headers[i] = headers[i];
        i++;
    }
    fixed_headers[i] = directory;
    fixed_headers[i + 1] = "";
    fixed_headers[i + 2 ] = NULL;

    char** files = gather_files(directory, fileExtensionOrDirectory, &numFiles);
    char** dirs = NULL;
    if (fileExtensionOrDirectory != NULL)
        dirs = gather_files(directory, NULL, &numDirs);
    int total = numDirs + numFiles;
    if (total == 0)
    {
        ui_print("No files found.\n");
    }
    else
    {
        char** list = (char**) malloc((total + 1) * sizeof(char*));
        list[total] = NULL;

        for (i = 0 ; i < numDirs; i++)
        {
            list[i] = strdup(dirs[i] + dir_len);
        }

        for (i = 0 ; i < numFiles; i++)
        {
            list[numDirs + i] = strdup(files[i] + dir_len);
        }

        for (;;)
        {
            int chosen_item = get_menu_selection(fixed_headers, list, 0, 0);
            if (chosen_item == GO_BACK || chosen_item == REFRESH)
                break;
            static char ret[PATH_MAX];
            if (chosen_item < numDirs)
            {
                char* subret = choose_file_menu(dirs[chosen_item], fileExtensionOrDirectory, headers);
                if (subret != NULL)
                {
                    strcpy(ret, subret);
                    return_value = ret;
                    break;
                }
                continue;
            }
            strcpy(ret, files[chosen_item - numDirs]);
            return_value = ret;
            break;
        }
        free_string_array(list);
    }

    free_string_array(files);
    free_string_array(dirs);
    return return_value;
}

void show_choose_zip_menu(const char *mount_point)
{
    if (ensure_path_mounted(mount_point) != 0) {
        LOGE ("Can't mount %s\n", mount_point);
        return;
    }

    static const char* headers[] = {  "Choose a zip to apply",
                                "",
                                NULL
    };

    char* file = choose_file_menu(mount_point, ".zip", headers);
    if (file == NULL)
        return;
    static char* confirm_install  = "Confirm install?";
    static char confirm[PATH_MAX];
    sprintf(confirm, "Yes - Install %s", basename(file));
    if (confirm_selection(confirm_install, confirm))
        install_zip(file);
}

void show_nandroid_restore_menu(const char* path)
{
    if (ensure_path_mounted(path) != 0) {
        LOGE("Can't mount %s\n", path);
        return;
    }

    static const char* headers[] = {  "Choose an image to restore",
                                "",
                                NULL
    };

    char tmp[PATH_MAX];
    sprintf(tmp, "%s/clockworkmod/backup/", path);
    char* file = choose_file_menu(tmp, NULL, headers);
    if (file == NULL)
        return;

    if (confirm_selection("Confirm restore?", "Yes - Restore"))
        nandroid_restore(file, 1, 1, 1, 1, 1, 0);
}

void show_nandroid_delete_menu(const char* path)
{
    if (ensure_path_mounted(path) != 0) {
        LOGE("Can't mount %s\n", path);
        return;
    }

    static const char* headers[] = {  "Choose an image to delete",
                                "",
                                NULL
    };

    char tmp[PATH_MAX];
    sprintf(tmp, "%s/clockworkmod/backup/", path);
    char* file = choose_file_menu(tmp, NULL, headers);
    if (file == NULL)
        return;

    if (confirm_selection("Confirm delete?", "Yes - Delete")) {
        // nandroid_restore(file, 1, 1, 1, 1, 1, 0);
        sprintf(tmp, "rm -rf %s", file);
        __system(tmp);
    }
}

static int control_usb_storage(bool on)
{
    int i = 0;
    int num = 0;

    for (i = 0; i < get_num_volumes(); i++) {
        Volume *v = get_device_volumes() + i;
        if (fs_mgr_is_voldmanaged(v) && vold_is_volume_available(v->mount_point)) {
            if (on) {
                vold_share_volume(v->mount_point);
            } else {
                vold_unshare_volume(v->mount_point, 1);
            }
            property_set("sys.storage.ums_enabled", on ? "1" : "0");
            num++;
        }
    }
    return num;
}

void show_mount_usb_storage_menu()
{
    // Enable USB storage using vold
    if (!control_usb_storage(true))
        return;

    static const char* headers[] = {  "USB Mass Storage device",
                                "Leaving this menu unmounts",
                                "your SD card from your PC.",
                                "",
                                NULL
    };

    static char* list[] = { "Unmount", NULL };

    for (;;)
    {
        int chosen_item = get_menu_selection(headers, list, 0, 0);
        if (chosen_item == GO_BACK || chosen_item == 0)
            break;
    }

    // Disable USB storage
    control_usb_storage(false);
}

int confirm_selection(const char* title, const char* confirm)
{
    struct stat info;
    int ret = 0;

    if (0 == stat("/sdcard/clockworkmod/.no_confirm", &info))
        return 1;

    char* confirm_str = strdup(confirm);
    const char* confirm_headers[]  = {  title, "  THIS CAN NOT BE UNDONE.", "", NULL };
    int many_confirm = 0 == stat("/sdcard/clockworkmod/.many_confirm", &info);
    if (many_confirm) {
        char* items[] = { "No",
                        "No",
                        "No",
                        "No",
                        "No",
                        "No",
                        "No",
                        confirm_str, //" Yes -- wipe partition",   // [7]
                        "No",
                        "No",
                        "No",
                        NULL };
        int chosen_item = get_menu_selection(confirm_headers, items, 0, 0);
        ret = (chosen_item == 7);
    }
    else {
        char* items[] = { "No",
                        confirm_str, //" Yes -- wipe partition",   // [1]
                        NULL };
        int chosen_item = get_menu_selection(confirm_headers, items, 0, 0);
        ret = (chosen_item == 1);
    }
    free(confirm_str);
    return ret;
}

#define MKE2FS_BIN      "/sbin/mke2fs"
#define TUNE2FS_BIN     "/sbin/tune2fs"
#define E2FSCK_BIN      "/sbin/e2fsck"
extern void reset_ext4fs_info();

extern struct selabel_handle *sehandle;
int format_device(const char *device, const char *path, const char *fs_type) {
    Volume* v = volume_for_path(path);
    if (v == NULL) {
        // silent failure for sd-ext
        if (strcmp(path, "/sd-ext") == 0)
            return -1;
        LOGE("unknown volume \"%s\"\n", path);
        return -1;
    }
    if (is_data_media_volume_path(path)) {
        return format_unknown_device(NULL, path, NULL);
    }
    if (strstr(path, "/data") == path && is_data_media()) {
        return format_unknown_device(NULL, path, NULL);
    }
    if (strcmp(fs_type, "ramdisk") == 0) {
        // you can't format the ramdisk.
        LOGE("can't format_volume \"%s\"", path);
        return -1;
    }

    if (strcmp(fs_type, "rfs") == 0) {
        if (ensure_path_unmounted(path) != 0) {
            LOGE("format_volume failed to unmount \"%s\"\n", v->mount_point);
            return -1;
        }
        if (0 != format_rfs_device(device, path)) {
            LOGE("format_volume: format_rfs_device failed on %s\n", device);
            return -1;
        }
        return 0;
    }

    if (strcmp(v->mount_point, path) != 0) {
        return format_unknown_device(v->blk_device, path, NULL);
    }

    if (ensure_path_unmounted(path) != 0) {
        LOGE("format_volume failed to unmount \"%s\"\n", v->mount_point);
        return -1;
    }

    if (strcmp(fs_type, "yaffs2") == 0 || strcmp(fs_type, "mtd") == 0) {
        mtd_scan_partitions();
        const MtdPartition* partition = mtd_find_partition_by_name(device);
        if (partition == NULL) {
            LOGE("format_volume: no MTD partition \"%s\"\n", device);
            return -1;
        }

        MtdWriteContext *write = mtd_write_partition(partition);
        if (write == NULL) {
            LOGW("format_volume: can't open MTD \"%s\"\n", device);
            return -1;
        } else if (mtd_erase_blocks(write, -1) == (off_t) -1) {
            LOGW("format_volume: can't erase MTD \"%s\"\n", device);
            mtd_write_close(write);
            return -1;
        } else if (mtd_write_close(write)) {
            LOGW("format_volume: can't close MTD \"%s\"\n",device);
            return -1;
        }
        return 0;
    }

    if (strcmp(fs_type, "ext4") == 0) {
        int length = 0;
        if (strcmp(v->fs_type, "ext4") == 0) {
            // Our desired filesystem matches the one in fstab, respect v->length
            length = v->length;
        }
        reset_ext4fs_info();
        int result = make_ext4fs(device, length, v->mount_point, sehandle);
        if (result != 0) {
            LOGE("format_volume: make_ext4fs failed on %s\n", device);
            return -1;
        }
        return 0;
    }

#ifdef USE_F2FS
    if (strcmp(fs_type, "f2fs") == 0) {
        int result = make_f2fs_main(device, v->mount_point);
        if (result != 0) {
            LOGE("format_volume: mkfs.f2f2 failed on %s\n", device);
            return -1;
        }
        return 0;
    }
#endif
    return format_unknown_device(device, path, fs_type);
}

int format_unknown_device(const char *device, const char* path, const char *fs_type)
{
    LOGI("Formatting unknown device.\n");

    if (fs_type != NULL && get_flash_type(fs_type) != UNSUPPORTED)
        return erase_raw_partition(fs_type, device);

    // if this is SDEXT:, don't worry about it if it does not exist.
    if (0 == strcmp(path, "/sd-ext"))
    {
        struct stat st;
        Volume *vol = volume_for_path("/sd-ext");
        if (vol == NULL || 0 != stat(vol->blk_device, &st))
        {
            LOGI("No app2sd partition found. Skipping format of /sd-ext.\n");
            return 0;
        }
    }

    if (NULL != fs_type) {
        if (strcmp("ext3", fs_type) == 0) {
            LOGI("Formatting ext3 device.\n");
            if (0 != ensure_path_unmounted(path)) {
                LOGE("Error while unmounting %s.\n", path);
                return -12;
            }
            return format_ext3_device(device);
        }

        if (strcmp("ext2", fs_type) == 0) {
            LOGI("Formatting ext2 device.\n");
            if (0 != ensure_path_unmounted(path)) {
                LOGE("Error while unmounting %s.\n", path);
                return -12;
            }
            return format_ext2_device(device);
        }
    }

    if (0 != ensure_path_mounted(path))
    {
        ui_print("Error mounting %s!\n", path);
        ui_print("Skipping format...\n");
        return 0;
    }

    static char tmp[PATH_MAX];
    if (strcmp(path, "/data") == 0) {
        sprintf(tmp, "cd /data ; for f in $(ls -a | grep -v ^media$); do rm -rf $f; done");
        __system(tmp);
        // if the /data/media sdcard has already been migrated for android 4.2,
        // prevent the migration from happening again by writing the .layout_version
        struct stat st;
        if (0 == lstat("/data/media/0", &st)) {
            char* layout_version = "2";
            FILE* f = fopen("/data/.layout_version", "wb");
            if (NULL != f) {
                fwrite(layout_version, 1, 2, f);
                fclose(f);
            }
            else {
                LOGI("error opening /data/.layout_version for write.\n");
            }
        }
        else {
            LOGI("/data/media/0 not found. migration may occur.\n");
        }
    }
    else {
        sprintf(tmp, "rm -rf %s/*", path);
        __system(tmp);
        sprintf(tmp, "rm -rf %s/.*", path);
        __system(tmp);
    }

    ensure_path_unmounted(path);
    return 0;
}

//#define MOUNTABLE_COUNT 5
//#define DEVICE_COUNT 4
//#define MMC_COUNT 2

typedef struct {
    char mount[255];
    char unmount[255];
    char path[PATH_MAX];
} MountMenuEntry;

typedef struct {
    char txt[255];
    char path[PATH_MAX];
    char type[255];
} FormatMenuEntry;

int is_safe_to_format(char* name)
{
    char str[255];
    char* partition;
    property_get("ro.cwm.forbid_format", str, "/misc,/radio,/bootloader,/recovery,/efs,/wimax");

    partition = strtok(str, ", ");
    while (partition != NULL) {
        if (strcmp(name, partition) == 0) {
            return 0;
        }
        partition = strtok(NULL, ", ");
    }

    return 1;
}

int show_partition_menu()
{
    static const char* headers[] = {  "Mounts and Storage Menu",
                                "",
                                NULL
    };

    static char* confirm_format  = "Confirm format?";
    static char* confirm = "Yes - Format";
    char confirm_string[255];

    static MountMenuEntry* mount_menu = NULL;
    static FormatMenuEntry* format_menu = NULL;
    static char* list[256];

    int i, mountable_volumes, formatable_volumes;
    int num_volumes;
    int chosen_item = 0;

    num_volumes = get_num_volumes();

    if(!num_volumes)
        return 0;

    mountable_volumes = 0;
    formatable_volumes = 0;

    mount_menu = malloc(num_volumes * sizeof(MountMenuEntry));
    format_menu = malloc(num_volumes * sizeof(FormatMenuEntry));

    for (i = 0; i < num_volumes; i++) {
        Volume* v = get_device_volumes() + i;

        if (fs_mgr_is_voldmanaged(v) && !vold_is_volume_available(v->mount_point)) {
            continue;
        }

        if(strcmp("ramdisk", v->fs_type) != 0 && strcmp("mtd", v->fs_type) != 0 && strcmp("emmc", v->fs_type) != 0 && strcmp("bml", v->fs_type) != 0) {
            if (strcmp("datamedia", v->fs_type) != 0) {
                sprintf(mount_menu[mountable_volumes].mount, "mount %s", v->mount_point);
                sprintf(mount_menu[mountable_volumes].unmount, "unmount %s", v->mount_point);
                sprintf(mount_menu[mountable_volumes].path, "%s", v->mount_point);
                ++mountable_volumes;
            }
            if (is_safe_to_format(v->mount_point)) {
                sprintf(format_menu[formatable_volumes].txt, "format %s", v->mount_point);
                sprintf(format_menu[formatable_volumes].path, "%s", v->mount_point);
                sprintf(format_menu[formatable_volumes].type, "%s", v->fs_type);
                ++formatable_volumes;
            }
        }
        else if (strcmp("ramdisk", v->fs_type) != 0 && strcmp("mtd", v->fs_type) == 0 && is_safe_to_format(v->mount_point))
        {
            sprintf(format_menu[formatable_volumes].txt, "format %s", v->mount_point);
            sprintf(format_menu[formatable_volumes].path, "%s", v->mount_point);
            sprintf(format_menu[formatable_volumes].type, "%s", v->fs_type);
            ++formatable_volumes;
        }
    }

    for (;;)
    {
        for (i = 0; i < mountable_volumes; i++)
        {
            MountMenuEntry* e = &mount_menu[i];
            if(is_path_mounted(e->path))
                list[i] = e->unmount;
            else
                list[i] = e->mount;
        }

        for (i = 0; i < formatable_volumes; i++)
        {
            FormatMenuEntry* e = &format_menu[i];
            list[mountable_volumes+i] = e->txt;
        }

        if (!is_data_media()) {
            list[mountable_volumes + formatable_volumes] = "mount USB storage";
            list[mountable_volumes + formatable_volumes + 1] = '\0';
        } else {
            list[mountable_volumes + formatable_volumes] = "format /data and /data/media (/sdcard)";
            list[mountable_volumes + formatable_volumes + 1] = "mount USB storage";
            list[mountable_volumes + formatable_volumes + 2] = '\0';
        }

        chosen_item = get_menu_selection(headers, list, 0, 0);
        if (chosen_item == GO_BACK || chosen_item == REFRESH)
            break;
        if (chosen_item == (mountable_volumes+formatable_volumes)) {
            if (!is_data_media()) {
                show_mount_usb_storage_menu();
            }
            else {
                if (!confirm_selection("format /data and /data/media (/sdcard)", confirm))
                    continue;
                ignore_data_media_workaround(1);
                ui_print("Formatting /data...\n");
                if (0 != format_volume("/data"))
                    ui_print("Error formatting /data!\n");
                else
                    ui_print("Done.\n");
                ignore_data_media_workaround(0);
            }
        }
        else if (is_data_media() && chosen_item == (mountable_volumes+formatable_volumes+1)) {
            show_mount_usb_storage_menu();
        }
        else if (chosen_item < mountable_volumes) {
            MountMenuEntry* e = &mount_menu[chosen_item];

            if (is_path_mounted(e->path))
            {
                if (0 != ensure_path_unmounted(e->path))
                    ui_print("Error unmounting %s!\n", e->path);
            }
            else
            {
                if (0 != ensure_path_mounted(e->path))
                    ui_print("Error mounting %s!\n",  e->path);
            }
        }
        else if (chosen_item < (mountable_volumes + formatable_volumes))
        {
            chosen_item = chosen_item - mountable_volumes;
            FormatMenuEntry* e = &format_menu[chosen_item];

            sprintf(confirm_string, "%s - %s", e->path, confirm_format);

            // support user choice fstype when formatting external storage
            // ensure fstype==auto because most devices with internal vfat storage cannot be formatted to other types
            if (strcmp(e->type, "auto") == 0) {
                format_sdcard(e->path);
                continue;
            }

            if (!confirm_selection(confirm_string, confirm))
                continue;
            ui_print("Formatting %s...\n", e->path);
            if (0 != format_volume(e->path))
                ui_print("Error formatting %s!\n", e->path);
            else
                ui_print("Done.\n");
        }
    }

    free(mount_menu);
    free(format_menu);
    return chosen_item;
}

void show_nandroid_advanced_restore_menu(const char* path)
{
    if (ensure_path_mounted(path) != 0) {
        LOGE ("Can't mount sdcard\n");
        return;
    }

    static const char* advancedheaders[] = {  "Choose an image to restore",
                                "",
                                "Choose an image to restore",
                                "first. The next menu will",
                                "show you more options.",
                                "",
                                NULL
    };

    char tmp[PATH_MAX];
    sprintf(tmp, "%s/clockworkmod/backup/", path);
    char* file = choose_file_menu(tmp, NULL, advancedheaders);
    if (file == NULL)
        return;

    static const char* headers[] = {  "Advanced Restore",
                                "",
                                NULL
    };

    static char* list[] = { "Restore boot",
                            "Restore system",
                            "Restore data",
                            "Restore cache",
                            "Restore sd-ext",
                            "Restore wimax",
                            NULL
    };

    if (0 != get_partition_device("wimax", tmp)) {
        // disable wimax restore option
        list[5] = NULL;
    }

    static char* confirm_restore  = "Confirm restore?";

    int chosen_item = get_menu_selection(headers, list, 0, 0);
    switch (chosen_item)
    {
        case 0:
            if (confirm_selection(confirm_restore, "Yes - Restore boot"))
                nandroid_restore(file, 1, 0, 0, 0, 0, 0);
            break;
        case 1:
            if (confirm_selection(confirm_restore, "Yes - Restore system"))
                nandroid_restore(file, 0, 1, 0, 0, 0, 0);
            break;
        case 2:
            if (confirm_selection(confirm_restore, "Yes - Restore data"))
                nandroid_restore(file, 0, 0, 1, 0, 0, 0);
            break;
        case 3:
            if (confirm_selection(confirm_restore, "Yes - Restore cache"))
                nandroid_restore(file, 0, 0, 0, 1, 0, 0);
            break;
        case 4:
            if (confirm_selection(confirm_restore, "Yes - Restore sd-ext"))
                nandroid_restore(file, 0, 0, 0, 0, 1, 0);
            break;
        case 5:
            if (confirm_selection(confirm_restore, "Yes - Restore wimax"))
                nandroid_restore(file, 0, 0, 0, 0, 0, 1);
            break;
    }
}

static void run_dedupe_gc() {
    char path[PATH_MAX];
    char* fmt = "%s/clockworkmod/blobs";
    char* primary_path = get_primary_storage_path();
    char** extra_paths = get_extra_storage_paths();
    int i = 0;

    sprintf(path, fmt, primary_path);
    ensure_path_mounted(primary_path);
    nandroid_dedupe_gc(path);

    if (extra_paths != NULL) {
        for (i = 0; i < get_num_extra_volumes(); i++) {
            ensure_path_mounted(extra_paths[i]);
            sprintf(path, fmt, extra_paths[i]);
            nandroid_dedupe_gc(path);
        }
    }
}

static void choose_default_backup_format() {
    static const char* headers[] = {  "Default Backup Format",
                                "",
                                NULL
    };

    int fmt = nandroid_get_default_backup_format();

    char **list;
    char* list_tar_default[] = { "tar (default)",
        "dup",
        "tar + gzip",
        NULL
    };
    char* list_dup_default[] = { "tar",
        "dup (default)",
        "tar + gzip",
        NULL
    };
    char* list_tgz_default[] = { "tar",
        "dup",
        "tar + gzip (default)",
        NULL
    };
    if (fmt == NANDROID_BACKUP_FORMAT_DUP) {
        list = list_dup_default;
    } else if (fmt == NANDROID_BACKUP_FORMAT_TGZ) {
        list = list_tgz_default;
    } else {
        list = list_tar_default;
    }

    int chosen_item = get_menu_selection(headers, list, 0, 0);
    switch (chosen_item) {
        case 0:
            write_string_to_file(NANDROID_BACKUP_FORMAT_FILE, "tar");
            ui_print("Default backup format set to tar.\n");
            break;
        case 1:
            write_string_to_file(NANDROID_BACKUP_FORMAT_FILE, "dup");
            ui_print("Default backup format set to dedupe.\n");
            break;
        case 2:
            write_string_to_file(NANDROID_BACKUP_FORMAT_FILE, "tgz");
            ui_print("Default backup format set to tar + gzip.\n");
            break;
    }
}

static void add_nandroid_options_for_volume(char** menu, char* path, int offset)
{
    char buf[100];

    sprintf(buf, "backup to %s", path);
    menu[offset] = strdup(buf);

    sprintf(buf, "restore from %s", path);
    menu[offset + 1] = strdup(buf);

    sprintf(buf, "delete from %s", path);
    menu[offset + 2] = strdup(buf);

    sprintf(buf, "advanced restore from %s", path);
    menu[offset + 3] = strdup(buf);
}

int show_nandroid_menu()
{
    char* primary_path = get_primary_storage_path();
    char** extra_paths = get_extra_storage_paths();
    int num_extra_volumes = get_num_extra_volumes();
    int i = 0, offset = 0, chosen_item = 0;
    char* chosen_path = NULL;
    int max_backup_index = (num_extra_volumes + 1) * 4;

    static const char* headers[] = {  "Backup and Restore",
                                      "",
                                      NULL
    };

    static char* list[((MAX_NUM_MANAGED_VOLUMES + 1) * 4) + 2];

    add_nandroid_options_for_volume(list, primary_path, offset);
    offset += 4;

    if (extra_paths != NULL) {
        for (i = 0; i < num_extra_volumes; i++) {
            add_nandroid_options_for_volume(list, extra_paths[i], offset);
            offset += 4;
        }
    }

    list[offset] = "free unused backup data";
    offset++;
    list[offset] = "choose default backup format";
    offset++;

#ifdef RECOVERY_EXTEND_NANDROID_MENU
    extend_nandroid_menu(list, offset, sizeof(list) / sizeof(char*));
    offset++;
#endif

    list[offset] = NULL;

    for (;;) {
        chosen_item = get_filtered_menu_selection(headers, list, 0, 0, offset);
        if (chosen_item == GO_BACK || chosen_item == REFRESH)
            break;
        int chosen_subitem = chosen_item % 4;
        if (chosen_item == max_backup_index) {
            run_dedupe_gc();
        } else if (chosen_item == (max_backup_index + 1)) {
            choose_default_backup_format();
        } else if (chosen_item < max_backup_index){
            if (chosen_item < 4) {
                chosen_path = primary_path;
            } else if (extra_paths != NULL) {
                chosen_path = extra_paths[(chosen_item / 4) -1];
            }
            switch (chosen_subitem) {
            case 0:
                {
                    char backup_path[PATH_MAX];
                    time_t t = time(NULL);
                    struct tm *tmp = localtime(&t);
                    if (tmp == NULL)
                    {
                        struct timeval tp;
                        gettimeofday(&tp, NULL);
                        sprintf(backup_path, "%s/clockworkmod/backup/%ld", chosen_path, tp.tv_sec);
                    }
                    else
                    {
                        char path_fmt[PATH_MAX];
                        strftime(path_fmt, sizeof(path_fmt), "clockworkmod/backup/%F.%H.%M.%S", tmp);
                        // this sprintf results in:
                        // /emmc/clockworkmod/backup/%F.%H.%M.%S (time values are populated too)
                        sprintf(backup_path, "%s/%s", chosen_path, path_fmt);
                    }
                    nandroid_backup(backup_path);
                }
                break;
            case 1:
                show_nandroid_restore_menu(chosen_path);
                break;
            case 2:
                show_nandroid_delete_menu(chosen_path);
                break;
            case 3:
                show_nandroid_advanced_restore_menu(chosen_path);
                break;
            default:
                break;
            }
        } else {
#ifdef RECOVERY_EXTEND_NANDROID_MENU
                handle_nandroid_menu(10, chosen_item);
#endif
            goto out;
        }
    }
out:
    for (i = 0; i < max_backup_index; i++)
        free(list[i]);
    return chosen_item;
}

void format_sdcard(const char* volume) {
    if (is_data_media_volume_path(volume))
        return;

    Volume *vol = volume_for_path(volume);
    if (vol == NULL || strcmp(vol->fs_type, "auto") != 0)
        return;
    if (!fs_mgr_is_voldmanaged(vol) && !can_partition(volume))
        return;

    char* headers[] = {"Format device:", volume, "", NULL };

    static char* list[] = { "default",
                            "vfat",
                            "exfat",
                            "ntfs",
                            "ext4",
                            "ext3",
                            "ext2",
                            NULL
    };

    int ret = -1;
    char cmd[PATH_MAX];
    int chosen_item = get_menu_selection(headers, list, 0, 0);
    if (chosen_item < 0) // REFRESH or GO_BACK
        return;
    if (!confirm_selection( "Confirm formatting?", "Yes - Format device"))
        return;

    Volume *v = volume_for_path(volume);
    if (ensure_path_unmounted(v->mount_point) != 0)
        return;

    switch (chosen_item)
    {
        case 0:
            ret = format_volume(v->mount_point);
            break;
        case 1:
        case 2:
        case 3:
        case 4:
            if (fs_mgr_is_voldmanaged(v)) {
                ret = vold_custom_format_volume(v->mount_point, list[chosen_item], 1) == CommandOkay ? 0 : -1;
            } else if (strcmp(list[chosen_item], "vfat") == 0) {
                sprintf(cmd, "/sbin/newfs_msdos -F 32 -O android -c 8 %s", v->blk_device);
                ret = __system(cmd);
            } else if (strcmp(list[chosen_item], "exfat") == 0) {
                sprintf(cmd, "/sbin/mkfs.exfat %s", v->blk_device);
                ret = __system(cmd);
            } else if (strcmp(list[chosen_item], "ntfs") == 0) {
                sprintf(cmd, "/sbin/mkntfs -f %s", v->blk_device);
                ret = __system(cmd);
            } else if (strcmp(list[chosen_item], "ext4") == 0) {
                ret = make_ext4fs(v->blk_device, v->length, volume, sehandle);
            }
            break;
        case 5:
        case 6:
            {
                // workaround for new vold managed volumes that cannot be recognized by prebuilt ext2/ext3 bins
                const char *device = v->blk_device2;
                if (device == NULL)
                    device = v->blk_device;
                ret = format_unknown_device(device, v->mount_point, list[chosen_item]);
                break;
            }
    }

    if (ret)
        ui_print("Could not format %s (%s)\n", volume, list[chosen_item]);
    else
        ui_print("Done formatting %s (%s)\n", volume, list[chosen_item]);
}

static void partition_sdcard(const char* volume) {
    if (!can_partition(volume)) {
        ui_print("Can't partition device: %s\n", volume);
        return;
    }

    static char* ext_sizes[] = { "128M",
                                 "256M",
                                 "512M",
                                 "1024M",
                                 "2048M",
                                 "4096M",
                                 NULL };

    static char* swap_sizes[] = { "0M",
                                  "32M",
                                  "64M",
                                  "128M",
                                  "256M",
                                  NULL };

    static char* partition_types[] = { "ext3",
                                       "ext4",
                                       NULL
    };

    static const char* ext_headers[] = { "Ext Size", "", NULL };
    static const char* swap_headers[] = { "Swap Size", "", NULL };
    static const char* fstype_headers[] = {"Partition Type", "", NULL };

    int ext_size = get_menu_selection(ext_headers, ext_sizes, 0, 0);
    if (ext_size < 0)
        return;

    int swap_size = get_menu_selection(swap_headers, swap_sizes, 0, 0);
    if (swap_size < 0)
        return;

    int partition_type = get_menu_selection(fstype_headers, partition_types, 0, 0);
    if (partition_type < 0)
        return;

    char sddevice[256];
    Volume *vol = volume_for_path(volume);

    // can_partition() ensured either blk_device or blk_device2 has /dev/block/mmcblk format
    if (strstr(vol->blk_device, "/dev/block/mmcblk") != NULL)
        strcpy(sddevice, vol->blk_device);
    else strcpy(sddevice, vol->blk_device2);

    // we only want the mmcblk, not the partition
    sddevice[strlen("/dev/block/mmcblkX")] = '\0';
    char cmd[PATH_MAX];
    setenv("SDPATH", sddevice, 1);
    sprintf(cmd, "sdparted -es %s -ss %s -efs %s -s", ext_sizes[ext_size], swap_sizes[swap_size], partition_types[partition_type]);
    ui_print("Partitioning SD Card... please wait...\n");
    if (0 == __system(cmd))
        ui_print("Done!\n");
    else
        ui_print("An error occured while partitioning your SD Card. Please see /tmp/recovery.log for more details.\n");
}

int can_partition(const char* volume) {
    if (is_data_media_volume_path(volume))
        return 0;

    Volume *vol = volume_for_path(volume);
    if (vol == NULL) {
        LOGI("Can't format unknown volume: %s\n", volume);
        return 0;
    }
    if (strcmp(vol->fs_type, "auto") != 0) {
        LOGI("Can't partition non-vfat: %s (%s)\n", volume, vol->fs_type);
        return 0;
    }

    // do not allow partitioning of a device that isn't mmcblkX or mmcblkXp1
    // needed with new vold managed volumes and virtual device path links
    int vol_len;
    char *device = NULL;
    if (strstr(vol->blk_device, "/dev/block/mmcblk") != NULL) {
        device = vol->blk_device;
    } else if (vol->blk_device2 != NULL && strstr(vol->blk_device2, "/dev/block/mmcblk") != NULL) {
        device = vol->blk_device2;
    } else {
        LOGI("Can't partition non mmcblk device: %s\n", vol->blk_device);
        return 0;
    }

    vol_len = strlen(device);
    if (device[vol_len - 2] == 'p' && device[vol_len - 1] != '1') {
        LOGI("Can't partition unsafe device: %s\n", device);
        return 0;
    }

    return 1;
}

#ifdef ENABLE_LOKI
    #define FIXED_ADVANCED_ENTRIES 8
#else
    #define FIXED_ADVANCED_ENTRIES 7
#endif

int show_advanced_menu()
{
    char buf[80];
    int i = 0, j = 0, chosen_item = 0;
    /* Default number of entries if no compile-time extras are added */
    static char* list[MAX_NUM_MANAGED_VOLUMES + FIXED_ADVANCED_ENTRIES + 1];

    char* primary_path = get_primary_storage_path();
    char** extra_paths = get_extra_storage_paths();
    int num_extra_volumes = get_num_extra_volumes();

    static const char* headers[] = {  "Advanced Menu",
                                "",
                                NULL
    };

    memset(list, 0, MAX_NUM_MANAGED_VOLUMES + FIXED_ADVANCED_ENTRIES + 1);

    list[0] = "reboot recovery";

    char bootloader_mode[PROPERTY_VALUE_MAX];
    property_get("ro.bootloader.mode", bootloader_mode, "");
    if (!strcmp(bootloader_mode, "download")) {
        list[1] = "reboot to download mode";
    } else {
        list[1] = "reboot to bootloader";
    }

    list[2] = "power off";
    list[3] = "wipe dalvik cache";
    list[4] = "report error";
    list[5] = "key test";
    list[6] = "show log";
#ifdef ENABLE_LOKI
    list[7] = "toggle loki support";
#endif

    char list_prefix[] = "partition ";
    if (can_partition(primary_path)) {
        sprintf(buf, "%s%s", list_prefix, primary_path);
        list[FIXED_ADVANCED_ENTRIES] = strdup(buf);
        j++;
    }

    if (extra_paths != NULL) {
        for (i = 0; i < num_extra_volumes; i++) {
            if (can_partition(extra_paths[i])) {
                sprintf(buf, "%s%s", list_prefix, extra_paths[i]);
                list[FIXED_ADVANCED_ENTRIES + j] = strdup(buf);
                j++;
            }
        }
    }
    list[FIXED_ADVANCED_ENTRIES + j] = NULL;

    for (;;)
    {
        chosen_item = get_filtered_menu_selection(headers, list, 0, 0, sizeof(list) / sizeof(char*));
        if (chosen_item == GO_BACK || chosen_item == REFRESH)
            break;
        switch (chosen_item)
        {
            case 0:
            {
                ui_print("Rebooting recovery...\n");
                reboot_main_system(ANDROID_RB_RESTART2, 0, "recovery");
                break;
            }
            case 1:
            {
                if (!strcmp(bootloader_mode, "download")) {
                    ui_print("Rebooting to download mode...\n");
                    reboot_main_system(ANDROID_RB_RESTART2, 0, "download");
                } else {
                    ui_print("Rebooting to bootloader...\n");
                    reboot_main_system(ANDROID_RB_RESTART2, 0, "bootloader");
                }
                break;
            }
            case 2:
            {
                ui_print("Shutting down...\n");
                reboot_main_system(ANDROID_RB_POWEROFF, 0, 0);
                break;
            }
            case 3:
                if (0 != ensure_path_mounted("/data"))
                    break;
                ensure_path_mounted("/sd-ext");
                ensure_path_mounted("/cache");
                if (confirm_selection( "Confirm wipe?", "Yes - Wipe Dalvik Cache")) {
                    __system("rm -r /data/dalvik-cache");
                    __system("rm -r /cache/dalvik-cache");
                    __system("rm -r /sd-ext/dalvik-cache");
                    ui_print("Dalvik Cache wiped.\n");
                }
                ensure_path_unmounted("/data");
                break;
            case 4:
                handle_failure(1);
                break;
            case 5:
            {
                ui_print("Outputting key codes.\n");
                ui_print("Go back to end debugging.\n");
                int key;
                int action;
                do
                {
                    key = ui_wait_key();
                    action = device_handle_key(key, 1);
                    ui_print("Key: %d\n", key);
                }
                while (action != GO_BACK);
                break;
            }
            case 6:
                ui_printlogtail(12);
                break;
#ifdef ENABLE_LOKI
            case 7:
                toggle_loki_support();
                break;
#endif
            default:
                partition_sdcard(list[chosen_item] + strlen(list_prefix));
                break;
        }
    }

    for (; j > 0; --j) {
        free(list[FIXED_ADVANCED_ENTRIES + j - 1]);
    }
    return chosen_item;
}

void write_fstab_root(char *path, FILE *file)
{
    Volume *vol = volume_for_path(path);
    if (vol == NULL) {
        LOGW("Unable to get recovery.fstab info for %s during fstab generation!\n", path);
        return;
    }

    char device[200];
    if (vol->blk_device[0] != '/')
        get_partition_device(vol->blk_device, device);
    else
        strcpy(device, vol->blk_device);

    fprintf(file, "%s ", device);
    fprintf(file, "%s ", path);
    // special case rfs cause auto will mount it as vfat on samsung.
    fprintf(file, "%s rw\n", vol->fs_type2 != NULL && strcmp(vol->fs_type, "rfs") != 0 ? "auto" : vol->fs_type);
}

void create_fstab()
{
    struct stat info;
    __system("touch /etc/mtab");
    FILE *file = fopen("/etc/fstab", "w");
    if (file == NULL) {
        LOGW("Unable to create /etc/fstab!\n");
        return;
    }
    Volume *vol = volume_for_path("/boot");
    if (NULL != vol && strcmp(vol->fs_type, "mtd") != 0 && strcmp(vol->fs_type, "emmc") != 0 && strcmp(vol->fs_type, "bml") != 0)
         write_fstab_root("/boot", file);
    write_fstab_root("/cache", file);
    write_fstab_root("/data", file);
    write_fstab_root("/datadata", file);
    write_fstab_root("/emmc", file);
    write_fstab_root("/system", file);
    write_fstab_root("/sdcard", file);
    write_fstab_root("/sd-ext", file);
    write_fstab_root("/external_sd", file);
    fclose(file);
    LOGI("Completed outputting fstab.\n");
}

int bml_check_volume(const char *path) {
    ui_print("Checking %s...\n", path);
    ensure_path_unmounted(path);
    if (0 == ensure_path_mounted(path)) {
        ensure_path_unmounted(path);
        return 0;
    }

    Volume *vol = volume_for_path(path);
    if (vol == NULL) {
        LOGE("Unable process volume! Skipping...\n");
        return 0;
    }

    ui_print("%s may be rfs. Checking...\n", path);
    char tmp[PATH_MAX];
    sprintf(tmp, "mount -t rfs %s %s", vol->blk_device, path);
    int ret = __system(tmp);
    printf("%d\n", ret);
    return ret == 0 ? 1 : 0;
}

void process_volumes() {
    create_fstab();

    if (is_data_media()) {
        setup_data_media();
    }

    return;

    // dead code.
    if (device_flash_type() != BML)
        return;

    ui_print("Checking for ext4 partitions...\n");
    int ret = 0;
    ret = bml_check_volume("/system");
    ret |= bml_check_volume("/data");
    if (has_datadata())
        ret |= bml_check_volume("/datadata");
    ret |= bml_check_volume("/cache");

    if (ret == 0) {
        ui_print("Done!\n");
        return;
    }

    char backup_path[PATH_MAX];
    time_t t = time(NULL);
    char backup_name[PATH_MAX];
    struct timeval tp;
    gettimeofday(&tp, NULL);
    sprintf(backup_name, "before-ext4-convert-%ld", tp.tv_sec);
    sprintf(backup_path, "%s/clockworkmod/backup/%s", get_primary_storage_path(), backup_name);

    ui_set_show_text(1);
    ui_print("Filesystems need to be converted to ext4.\n");
    ui_print("A backup and restore will now take place.\n");
    ui_print("If anything goes wrong, your backup will be\n");
    ui_print("named %s. Try restoring it\n", backup_name);
    ui_print("in case of error.\n");

    nandroid_backup(backup_path);
    nandroid_restore(backup_path, 1, 1, 1, 1, 1, 0);
    ui_set_show_text(0);
}

void handle_failure(int ret)
{
    if (ret == 0)
        return;
    if (0 != ensure_path_mounted(get_primary_storage_path()))
        return;
    mkdir("/sdcard/clockworkmod", S_IRWXU | S_IRWXG | S_IRWXO);
    __system("cp /tmp/recovery.log /sdcard/clockworkmod/recovery.log");
    ui_print("/tmp/recovery.log was copied to /sdcard/clockworkmod/recovery.log. Please open ROM Manager to report the issue.\n");
}

static int is_path_mounted(const char* path) {
    Volume* v = volume_for_path(path);
    if (v == NULL) {
        return 0;
    }
    if (strcmp(v->fs_type, "ramdisk") == 0) {
        // the ramdisk is always mounted.
        return 1;
    }

    if (scan_mounted_volumes() < 0)
        return 0;

    const MountedVolume* mv =
        find_mounted_volume_by_mount_point(v->mount_point);
    if (mv) {
        // volume is already mounted
        return 1;
    }
    return 0;
}

int has_datadata() {
    Volume *vol = volume_for_path("/datadata");
    return vol != NULL;
}

int volume_main(int argc, char **argv) {
    load_volume_table();
    return 0;
}

int verify_root_and_recovery() {
    write_recovery_version();

    if (ensure_path_mounted("/system") != 0)
        return 0;

    int ret = 0;
    struct stat st;
    // check to see if install-recovery.sh is going to clobber recovery
    // install-recovery.sh is also used to run the su daemon on stock rom for 4.3+
    // so verify that doesn't exist...
    if (0 != lstat("/system/etc/.installed_su_daemon", &st)) {
        // check install-recovery.sh exists and is executable
        if (0 == lstat("/system/etc/install-recovery.sh", &st)) {
            if (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
                ui_show_text(1);
                ret = 1;
                if (confirm_selection("ROM may flash stock recovery on boot. Fix?", "Yes - Disable recovery flash")) {
                    __system("chmod -x /system/etc/install-recovery.sh");
                }
            }
        }
    }

    int exists = 0;
    if (0 == lstat("/system/bin/su", &st)) {
        exists = 1;
        if (S_ISREG(st.st_mode)) {
            if ((st.st_mode & (S_ISUID | S_ISGID)) != (S_ISUID | S_ISGID)) {
                ui_show_text(1);
                ret = 1;
                if (confirm_selection("Root access possibly lost. Fix?", "Yes - Fix root (/system/bin/su)")) {
                    __system("chmod 6755 /system/bin/su");
                }
            }
        }
    }

    if (0 == lstat("/system/xbin/su", &st)) {
        exists = 1;
        if (S_ISREG(st.st_mode)) {
            if ((st.st_mode & (S_ISUID | S_ISGID)) != (S_ISUID | S_ISGID)) {
                ui_show_text(1);
                ret = 1;
                if (confirm_selection("Root access possibly lost. Fix?", "Yes - Fix root (/system/xbin/su)")) {
                    __system("chmod 6755 /system/xbin/su");
                }
            }
        }
    }

    if (!exists) {
        ui_show_text(1);
        ret = 1;
        if (confirm_selection("Root access is missing. Root device?", "Yes - Root device (/system/xbin/su)")) {
            __system("/sbin/install-su.sh");
        }
    }

    ensure_path_unmounted("/system");
    return ret;
}


text:
import loadScript from 'simple-load-script'
import { all, take, put, call, fork } from 'redux-saga/effects'
import * as actions from './actions'

export function* track(type, { gtm } = {}) {
  const payload = { event: type, label: gtm }
  try {
    // istanbul ignore next
    window.dataLayer = window.dataLayer || []
    window.dataLayer.push(payload)
    yield payload
  } catch (e) {
    yield put(actions.gtmFailure(e, payload))
  }
}

export function* startGTM({ gtmId }) {
  try {
    // istanbul ignore next
    window.dataLayer = window.dataLayer || []
    window.dataLayer.push({
      event: 'gtm.js',
      'gtm.start': new Date().getTime(),
    })
    yield call(loadScript, `//www.googletagmanager.com/gtm.js?id=${gtmId}`)
  } catch (e) {
    yield put(actions.gtmFailure(e, { gtmId }))
  }
}

export function* watchAllActions() {
  while (true) {
    const { type, meta } = yield take('*')
    yield call(track, type, meta)
  }
}

export function* watchGTMStart() {
  const { payload } = yield take(actions.GTM_START)
  yield all([
    call(startGTM, payload),
    call(watchAllActions),
  ])
}

export default function* () {
  yield fork(watchGTMStart)
}


text:
from __future__ import division, print_function, absolute_import

from os.path import join, dirname
import glob

def pre_build_hook(build_ext, ext):
    from scipy._build_utils.compiler_helper import get_cxx_std_flag
    std_flag = get_cxx_std_flag(build_ext._cxx_compiler)
    if std_flag is not None:
        ext.extra_compile_args.append(std_flag)

def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
    from numpy.distutils.misc_util import get_info as get_misc_info
    from scipy._build_utils.system_info import get_info as get_sys_info
    from distutils.sysconfig import get_python_inc

    config = Configuration('spatial', parent_package, top_path)

    config.add_data_dir('tests')

    # spatial.transform
    config.add_subpackage('transform')

    # qhull
    qhull_src = sorted(glob.glob(join(dirname(__file__), 'qhull_src',
                                    'src', '*.c')))

    inc_dirs = [get_python_inc()]
    if inc_dirs[0] != get_python_inc(plat_specific=1):
        inc_dirs.append(get_python_inc(plat_specific=1))
    inc_dirs.append(get_numpy_include_dirs())
    inc_dirs.append(join(dirname(dirname(__file__)), '_lib'))

    cfg = dict(get_sys_info('lapack_opt'))
    cfg.setdefault('include_dirs', []).extend(inc_dirs)
    config.add_extension('qhull',
                         sources=['qhull.c', 'qhull_misc.c'] + qhull_src,
                         **cfg)

    # cKDTree
    ckdtree_src = ['query.cxx',
                   'build.cxx',
                   'query_pairs.cxx',
                   'count_neighbors.cxx',
                   'query_ball_point.cxx',
                   'query_ball_tree.cxx',
                   'sparse_distances.cxx']

    ckdtree_src = [join('ckdtree', 'src', x) for x in ckdtree_src]

    ckdtree_headers = ['ckdtree_decl.h',
                       'coo_entries.h',
                       'distance_base.h',
                       'distance.h',
                       'ordered_pair.h',
                       'partial_sort.h',
                       'rectangle.h']

    ckdtree_headers = [join('ckdtree', 'src', x) for x in ckdtree_headers]

    ckdtree_dep = ['ckdtree.cxx'] + ckdtree_headers + ckdtree_src
    ext = config.add_extension('ckdtree',
                         sources=['ckdtree.cxx'] + ckdtree_src,
                         depends=ckdtree_dep,
                         include_dirs=inc_dirs + [join('ckdtree', 'src')])
    ext._pre_build_hook = pre_build_hook

    # _distance_wrap
    config.add_extension('_distance_wrap',
                         sources=[join('src', 'distance_wrap.c')],
                         depends=[join('src', 'distance_impl.h')],
                         include_dirs=[get_numpy_include_dirs()],
                         extra_info=get_misc_info("npymath"))

    config.add_extension('_voronoi',
                         sources=['_voronoi.c'])

    config.add_extension('_hausdorff',
                         sources=['_hausdorff.c'])

    # Add license files
    config.add_data_files('qhull_src/COPYING.txt')

    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())


text:
/**
 * Created by yong.liu on 2015/9/19.
 */
;
"use strict";
if("undefined" == jQuery){
    throw new Error("requires jQuery!");
}
+function($,w){
    $.extend({
        asyncAjax: asyncAjax
    });

    /**
     * 异步ajax
     */
    function asyncAjax(args){
        var configs = {
            method: "GET",
            url: "",
            data:"",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            dataType: "json",
            beforeSend: function(xhr){}
        };
        var params = $.extend(true,{},configs,args);
        var deferred = $.ajax({
            method: params.method,
            url: params.url,
            data: params.data,
            contentType: params.contentType,
            dataType: params.dataType,
            beforeSend: params.beforeSend
        });
        return deferred;
    }

}(jQuery,window);


text:
<?php

declare(strict_types=1);

namespace Phoenix\Tests\Database\QueryBuilder\PgsqlQueryBuilder;

use Phoenix\Database\Adapter\PgsqlAdapter;
use Phoenix\Database\Element\MigrationTable;
use Phoenix\Database\QueryBuilder\PgsqlQueryBuilder;
use Phoenix\Tests\Helpers\Pdo\PgsqlPdo;
use PHPUnit\Framework\TestCase;

final class CopyTableTest extends TestCase
{
    private PgsqlAdapter $adapter;

    protected function setUp(): void
    {
        $pdo = new PgsqlPdo(getenv('PHOENIX_PGSQL_DATABASE'));
        $this->adapter = new PgsqlAdapter($pdo);
    }

    public function testCopyDefault(): void
    {
        $table = new MigrationTable('copy_default');
        $table->copy('new_copy_default');

        $queryBuilder = new PgsqlQueryBuilder($this->adapter);
        $expectedQueries = [
            'CREATE TABLE "new_copy_default" AS TABLE "copy_default" WITH NO DATA;',
        ];
        $this->assertEquals($expectedQueries, $queryBuilder->copyTable($table));
    }

    public function testCopyOnlyStructure(): void
    {
        $table = new MigrationTable('copy_only_structure');
        $table->copy('new_copy_only_structure', MigrationTable::COPY_ONLY_STRUCTURE);

        $queryBuilder = new PgsqlQueryBuilder($this->adapter);
        $expectedQueries = [
            'CREATE TABLE "new_copy_only_structure" AS TABLE "copy_only_structure" WITH NO DATA;',
        ];
        $this->assertEquals($expectedQueries, $queryBuilder->copyTable($table));
    }

    public function testCopyOnlyData(): void
    {
        $table = new MigrationTable('copy_only_data');
        $table->copy('new_copy_only_data', MigrationTable::COPY_ONLY_DATA);

        $queryBuilder = new PgsqlQueryBuilder($this->adapter);
        $expectedQueries = [
            'INSERT INTO "new_copy_only_data" SELECT * FROM "copy_only_data";',
        ];
        $this->assertEquals($expectedQueries, $queryBuilder->copyTable($table));
    }

    public function testCopyStructureAndData(): void
    {
        $table = new MigrationTable('copy_structure_and_data');
        $table->copy('new_copy_structure_and_data', MigrationTable::COPY_STRUCTURE_AND_DATA);

        $queryBuilder = new PgsqlQueryBuilder($this->adapter);
        $expectedQueries = [
            'CREATE TABLE "new_copy_structure_and_data" AS TABLE "copy_structure_and_data" WITH DATA;',
        ];
        $this->assertEquals($expectedQueries, $queryBuilder->copyTable($table));
    }
}


text:
package org.demis.comics.data.dto;

public class AbstractDTO {
    private Long id;

    public Long getId() {
        return id;
    }

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


text:
sudo service postgresql start
#Connect to the service
sudo sudo -u postgres psql
#Create a PostgreSQL database
#Make sure you have logged into the PostgreSQL terminal and then you can just run:

sudo sudo -u postgres psql
postgres=# CREATE DATABASE "groceries";
#List all databases
sudo sudo -u postgres psql
postgres=# \list
#Connecting with your language of choice
#First you must set a password for the postgres user.

sudo sudo -u postgres psql
postgres-# \password postgres
#Enter new password:
#Then you can connect with username "postgres" and the password you set. Here's an example in PHP:

<?php
$link = pg_connect("host=localhost dbname=groceries user=postgres password=cloud9isawesome");
?>

#Note:
#The DATABASE_URL for the Heroku Postgres add-on follows the below convention
postgres://<username>:<password>@<host>:<port>/<dbname>
#However the Postgres JDBC driver uses the following convention:
jdbc:postgresql://<host>:<port>/<dbname>?user=<username>&password=<password>
#Notice the additional ql at the end of the URL scheme. Due to this difference, for Postgres, you may need to hardcode the scheme to postgresql in your Java class or your Spring XML configuration.


text:
Partial Plates
==============

An alternative to microplate formulations of tectonic geodesy.

## Introduction
In areas of distributed deformation, the rigid plate model of tectonics appears
to break down, or at least become insufficient for completely describing
deformation. This has driven many workers towards increasing the number of
small plates, microplates, or 'blocks' in an orogen. These microplates
represent geodetically cohesive regions of the crust that are completely
bounded and defined by faults, and have minimal internal deformation (possibly
some amount of homogeneous strain).

This is not always consistent with observations of faults in deformation zones:
Faults tend not to connect with other faults on the surface, and definitely do
not completely encompass and separate internally-rigid rotating blocks.

Instead, the decadal velocity field in many deforming regions seems to be
transitional in between the velocity fields of the major tectonic plates that
surround an orogen. Within the deformation zone, the velocity vectors can be
constructed as the sum of partial plate velocity vectors:

> Vsite = C1 * Vplate1 + C2 * Vplate2

where C1 and C2 are the coefficients of plate motion (i.e. of the total
plate velocity magnitude at that point).

For example, the velocity of a GPS site in northern Honduras near the North
American-Caribbean plate boundary may be moving 40% with North America and
60% with the Caribbean plates. Near triple junctions, a site may be
'influenced' by 3 plates.

By defining site velocities in terms of 'partial plates', or coefficients of
rigid macroplate motion, we can accomplish several things:

1. *Redefine strain as changes in plate coefficients:* Even though a velocity
   gradient exists between any two points on a rotating plate (i.e. the east or
   north velocities will change even if the magnitude does not), as long as
   those points are moving with the plate, there is no strain between them.
   However, changes in plate coefficients (e.g. C1 in the above equation)
   indicate that strain is occurring. Changes in coefficents along a radius
   (from the Euler pole) indicate simple shear (i.e. strike-slip faulting),
   while changes along a circumference indicate pure shear (shortening or
   extension). The sum of coefficient changes from all plates involved is the
   total strain in the region (it is possible that some changes will cancel
   out).

2. *Calculate fault slip rates independently of block motion*: In block models,
   the self-consistency constraints necessitate that the relative motion
   between any two adjacent blocks is completely taken up by slip on the
   intervening fault. However, by modeling a site velocity as a sum of partial
   plate velocities, we can come up with a complete description of the
   orogenic velocity and strain fields without specifying that all strain is
   accommodated on faults. Then, the faults can be modeled independently and
   the components of deformation that are directly attributable to the faults
   can be determined, and the regions of distributed strain (with no obvious
   major faults) can be delineated as well. (I am not sure exactly how this
   will play out... It's quite possible that I won't be able to make a nice,
   internally consistent package out of all of this. But it's my major
   motivation.)

3. *Identify areas of anomalous or independent motion:* There will certainly
   be some sites or areas with some component of the velocity field that cannot
   be matched by the surrounding plates. The identification and
   characterization of these areas may shed a lot of light onto the forces that
   cause deformation in orogens.

This is very much a scientific experiment in progress.  We'll see where it
goes.

![Central American partial plates](./c_am_tricolor.png)
*Plate motion coefficients in the Caribbean-North America-Cocos triple junction
region, shown as RGB colors. Note that the Central American forearc moves with
North America even into northern Costa Rica. This is data from the Global
Strain Rate Model v.2.1, with no correction for fault locking.*

## Aims and scope

Partial Plates aims to be an extension of rigid plate theory that allows for
distributed deformation, and serve as a framework for quantifying fault and
off-fault strain rates.

Partial Plates will probably never be as neat and self-consistent as microplate
or block models--as it stands, it requires external derivation of Euler
rotation parameters (poles, rates) for each plate. It's also not clear how
cleanly faults will fit into the theory. I hope very cleanly, but my hope is
in vain as often as anyone's...

## Progress

Basic Python module and testing w/ Central America is WIP.


text:
.. _serve-rllib-tutorial:

RLlib Tutorial
=============================

In this guide, we will train and deploy a simple Ray RLlib PPO model.
In particular, we show:

- How to load the model from checkpoint
- How to parse the JSON request and evaluate payload in RLlib

Please see the :doc:`../core-apis` to learn more general information about Ray Serve.

Let's import Ray Serve and some other helpers.

.. literalinclude:: ../../../../python/ray/serve/examples/doc/tutorial_rllib.py
    :start-after: __doc_import_begin__
    :end-before: __doc_import_end__

We will train and checkpoint a simple PPO model with ``CartPole-v0`` environment.
We are just writing to local disk for now. In production, you might want to consider
loading the weights from a cloud storage (S3) or shared file system.

.. literalinclude:: ../../../../python/ray/serve/examples/doc/tutorial_rllib.py
    :start-after: __doc_train_model_begin__
    :end-before: __doc_train_model_end__

Services are just defined as normal classes with ``__init__`` and ``__call__`` methods.
The ``__call__`` method will be invoked per request. For each request, the method
retrieves the ``request.json()["observation"]`` as input.

.. tip::

    Although we used a single input and ``trainer.compute_action(...)`` here, you
    can process a batch of input using Ray Serve's :ref:`batching<serve-batching>` feature
    and use ``trainer.compute_actions(...)`` (notice the plural!) to process a
    batch.

.. literalinclude:: ../../../../python/ray/serve/examples/doc/tutorial_rllib.py
    :start-after: __doc_define_servable_begin__
    :end-before: __doc_define_servable_end__

Now that we've defined our services, let's deploy the model to Ray Serve. We will
define an endpoint for the route representing the ppo model, a
backend correspond the physical implementation, and connect them together.

.. literalinclude:: ../../../../python/ray/serve/examples/doc/tutorial_rllib.py
    :start-after: __doc_deploy_begin__
    :end-before: __doc_deploy_end__

Let's query it!

.. literalinclude:: ../../../../python/ray/serve/examples/doc/tutorial_rllib.py
    :start-after: __doc_query_begin__
    :end-before: __doc_query_end__


text:
<?php

namespace Drupal\Tests\user\Kernel;

use Drupal\Core\Database\Database;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\user\Entity\User;

/**
 * Tests deleting of user accounts.
 *
 * @group user
 */
class UserDeleteTest extends KernelTestBase {

  use UserCreationTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'system',
    'user',
  ];

  /**
   * Tests deleting multiple users.
   */
  public function testUserDeleteMultiple() {
    $this->installSchema('system', ['sequences']);
    $this->installSchema('user', ['users_data']);
    $this->installEntitySchema('user');

    // Create a few users with permissions, so roles will be created.
    $user_a = $this->createUser(['access user profiles']);
    $user_b = $this->createUser(['access user profiles']);
    $user_c = $this->createUser(['access user profiles']);

    $uids = [$user_a->id(), $user_b->id(), $user_c->id()];

    // These users should have a role
    $connection = Database::getConnection();
    $query = $connection->select('user__roles', 'r');
    $roles_created = $query
      ->fields('r', ['entity_id'])
      ->condition('entity_id', $uids, 'IN')
      ->countQuery()
      ->execute()
      ->fetchField();

    $this->assertGreaterThan(0, $roles_created);
    // We should be able to load one of the users.
    $this->assertNotNull(User::load($user_a->id()));
    // Delete the users.
    $storage = $this->container->get('entity_type.manager')->getStorage('user');
    $users = $storage->loadMultiple($uids);
    $storage->delete($users);
    // Test if the roles assignments are deleted.
    $query = $connection->select('user__roles', 'r');
    $roles_after_deletion = $query
      ->fields('r', ['entity_id'])
      ->condition('entity_id', $uids, 'IN')
      ->countQuery()
      ->execute()
      ->fetchField();
    $this->assertEquals(0, $roles_after_deletion);
    // Test if the users are deleted, User::load() will return NULL.
    $this->assertNull(User::load($user_a->id()));
    $this->assertNull(User::load($user_b->id()));
    $this->assertNull(User::load($user_c->id()));
  }

}


text:
"""
fip_to_gateway creates an uplink subnet on VSG/VRS-G gateway to access FIP subnet inside Shared Resource Domain

--- Author ---
Michael Kashin <michael.kashin@nokia.com>

--- Version history ---
2016-10-06 - 1.0 - First version
2016-10-08 - 1.1 - Variable name changes and failure handling
2020-07-06 - 1.2 - Migrate to v6 API

--- Usage ---
run 'python fip_to_gateway.py -h' for an overview

--- Documentation ---
http://github.com/nuagenetworks/vspk-examples/blob/master/docs/fip_to_gateway.md

--- Example ---
python fip_to_gateway.py -E csp -H 10.6.132.43 -p csproot -u csproot -S \
       --address 10.6.132.160 --mask 255.255.255.224 --gw 10.6.132.190 \
       --ip 10.6.132.161 --mac f4:cc:55:e0:14:00 --fip 10.6.132.192 \
       --vsg 10.6.132.47 --port eth0 --vlan 205
"""

from builtins import str
from builtins import range
import argparse
import getpass
import logging
import requests

from vspk import v5_0 as vsdk

UPLINK_TYPE = 'UPLINK_SUBNET'

def get_args():
    """
    Supports the command-line arguments listed below.
    """

    parser = argparse.ArgumentParser(description="Tool to create an uplink subnet for FIP access via VSG/VRS-G gateway.")
    parser.add_argument('-d', '--debug', required=False, help='Enable debug output', dest='debug', action='store_true')
    parser.add_argument('-l', '--log-file', required=False, help='File to log to (default = stdout)', dest='logfile', type=str)
    parser.add_argument('-E', '--nuage-enterprise', required=True, help='The enterprise with which to connect to the Nuage VSD/SDK host', dest='nuage_enterprise', type=str)
    parser.add_argument('-H', '--nuage-host', required=True, help='The Nuage VSD/SDK endpoint to connect to', dest='nuage_host', type=str)
    parser.add_argument('-P', '--nuage-port', required=False, help='The Nuage VSD/SDK server port to connect to (default = 8443)', dest='nuage_port', type=int, default=8443)
    parser.add_argument('-p', '--nuage-password', required=False, help='The password with which to connect to the Nuage VSD/SDK host. If not specified, the user is prompted at runtime for a password', dest='nuage_password', type=str)
    parser.add_argument('-u', '--nuage-user', required=True, help='The username with which to connect to the Nuage VSD/SDK host', dest='nuage_username', type=str)
    parser.add_argument('-S', '--disable-SSL-certificate-verification', required=False, help='Disable SSL certificate verification on connect (deprecated)', dest='nosslcheck', action='store_true')
    parser.add_argument('-v', '--verbose', required=False, help='Enable verbose output', dest='verbose', action='store_true')
    parser.add_argument('--fip', required=True, help='FIP subnet CIDR', dest='fip_net')
    parser.add_argument('--address', required=True, help='Uplink network address', dest='uplink_addr')
    parser.add_argument('--mask', required=True, help='Uplink network netmask', dest='uplink_mask')
    parser.add_argument('--gw', required=True, help='Uplink network gateway', dest='uplink_gw')
    parser.add_argument('--ip', required=True, help='Uplink interface IP', dest='uplink_ip')
    parser.add_argument('--mac', required=True, help='Uplink interface MAC', dest='uplink_mac')
    parser.add_argument('--vsg', required=True, help='VSG/VRS-G name as it appears in your infrastructure (defaults to IP if you have not changed it)', dest='gw_name')
    parser.add_argument('--port', required=True, help='VSG/VRS-G Network Interface Name', dest='gw_port')
    parser.add_argument('--vlan', required=True, help='VSG/VRS-G Network Interface Vlan ID', dest='gw_vlan')
    args = parser.parse_args()
    return args

def main():
    """
    Main function to create Uplink subnet via REST API
    """

    # Handling arguments
    args                = get_args()
    debug               = args.debug
    log_file            = None
    if args.logfile:
        log_file        = args.logfile
    nuage_enterprise    = args.nuage_enterprise
    nuage_host          = args.nuage_host
    nuage_port          = args.nuage_port
    nuage_password      = None
    if args.nuage_password:
        nuage_password  = args.nuage_password
    nuage_username      = args.nuage_username
#    nosslcheck          = args.nosslcheck
    verbose             = args.verbose
    fip_net             = args.fip_net
    uplink_addr         = args.uplink_addr
    uplink_mask         = args.uplink_mask
    uplink_gw           = args.uplink_gw
    uplink_ip           = args.uplink_ip
    uplink_mac          = args.uplink_mac
    gw_name              = args.gw_name
    gw_port            = args.gw_port
    gw_vlan            = args.gw_vlan

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level)
    logger = logging.getLogger(__name__)

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug('No command line Nuage password received, requesting Nuage password from user')
        nuage_password = getpass.getpass(prompt='Enter password for Nuage host %s for user %s: ' % (nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' % (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username, password=nuage_password, enterprise=nuage_enterprise, api_url="https://%s:%s" % (nuage_host, nuage_port))
        nc.start()

    except Exception as e:
        logger.error('Could not connect to Nuage host %s with user %s and specified password' % (nuage_host, nuage_username))
        logger.critical('Caught exception: %s' % str(e))
        return 1

    nuage_user = nc.user

    # Getting the parentID of FIP subnet
    logger.debug('Getting FIP subnet parent ID')
    fip_obj = nuage_user.subnets.get_first(filter="address == '{0}'".format(fip_net))

    # Fail if FIP subnet object was not found
    if not fip_obj:
        logger.critical('FIP subnet {0} was not found'.format(fip_net))
        return 1

    shared_resource_id = fip_obj.parent_id
    logger.debug('FIP parent ID is: {0}'.format(shared_resource_id))

    # Locating a gateway port and creating a new VLAN
    logger.debug('Creating a new VLAN on Gateway port')
    new_vlan = vsdk.NUVLAN(value=gw_vlan)
    gw = nuage_user.gateways.get_first(filter="name == '{0}'".format(gw_name))

    # Fail if Gateway was not found
    if not gw:
        logger.critical('Gateway {0} was not found'.format(gw_name))
        return 1

    port = gw.ports.get_first(filter="name == '{0}'".format(gw_port))

    # Fail if Port requirements are not met
    if not port:
        logger.critical('Port {0} was not found on Gateway {1}'.format(gw_port, gw_name))
        return 1
    elif not port.port_type == 'ACCESS':
        logger.critical('Port {0} is not an ACCESS port type'.format(gw_port))
        return 1
    elif not int(gw_vlan) in range(*[int(x) for x in port.vlan_range.split('-')]):
        logger.critical('Vlan {0} is not part of the port vlan range: {1}'.format(gw_vlan, port.vlan_range))
        return 1
    elif port.vlans.get_first(filter="value == {0}".format(gw_vlan)):
        logger.critical('Vlan {0} already exists on port {1}'.format(gw_vlan, gw_port))
        return 1

    port.create_child(new_vlan)
    vlan_id = new_vlan.id
    logger.debug('New VLAN ID is: {0}'.format(vlan_id))

    # Constructing an Uplink Subnet object
    logger.debug('Creating an Uplink Subnet')
    shared_subnet = vsdk.NUSharedNetworkResource(name='uplink subnet {0}'.format(uplink_addr.replace('.','-')), \
        description='Uplink subnet to Gateway {0}'.format(gw_name.replace('.','-')), \
        address=uplink_addr, \
        netmask=uplink_mask, \
        gateway=uplink_gw, \
        type=UPLINK_TYPE, \
        uplink_interface_ip=uplink_ip, \
        uplink_interface_mac=uplink_mac, \
        uplink_gw_vlan_attachment_id=vlan_id, \
        shared_resource_parent_id=shared_resource_id, \
        uplink_vport_name = 'uplink vport {0} Vlan{1}'.format(gw_port, gw_vlan))

    # Creating a subnet on VSD
    nuage_user.create_child(shared_subnet)

    logger.info('Uplink Subnet is created')
    return 0

# Start program
if __name__ == "__main__":
    main()


text:
package de.iweinzierl.easyprofiles.util.time;

import android.content.Context;
import android.content.Intent;

import de.iweinzierl.easyprofiles.domain.BaseTrigger;
import de.iweinzierl.easyprofiles.receiver.TimeBasedTriggerReceiver;

public class TriggerActivationServiceIntent extends Intent {

    public TriggerActivationServiceIntent(Context packageContext, BaseTrigger trigger) {
        super(packageContext, TimeBasedTriggerReceiver.class);
        putExtra(TimeBasedTriggerReceiver.EXTRA_TRIGGER_ID, trigger.getId());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diaporthe sechalinensis Sacc.

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toast_background"
        android:paddingBottom="@dimen/global_padding"
        android:paddingLeft="16.0dip"
        android:paddingRight="16.0dip"
        android:paddingTop="@dimen/global_padding" >

        <ImageView
            android:id="@+id/icon_iv"
            android:layout_width="wrap_content"
            android:layout_height="40.0dip"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/global_padding"
            android:scaleType="fitCenter"
            android:visibility="gone" />

        <TextView
            android:id="@+id/action_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:shadowColor="@android:color/black"
            android:shadowDx="0.0"
            android:shadowDy="-1.0"
            android:shadowRadius="1.0"
            android:textColor="@android:color/white"
            android:textSize="14.0dip"
            android:textStyle="bold"
            android:visibility="gone" />

        <TextView
            android:id="@+id/title_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignWithParentIfMissing="true"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/action_tv"
            android:layout_toRightOf="@id/icon_iv"
            android:shadowColor="@android:color/black"
            android:shadowDx="0.0"
            android:shadowDy="-1.0"
            android:shadowRadius="1.0"
            android:textColor="@android:color/white"
            android:textSize="14.0dip"
            android:textStyle="bold" />
    </RelativeLayout>

</merge>