/**
 * Copyright (C) 2011 Whisper Systems
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.smssecure.smssecure.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;

import org.smssecure.smssecure.DatabaseUpgradeActivity;
import org.smssecure.smssecure.contacts.ContactsDatabase;
import org.smssecure.smssecure.crypto.DecryptingPartInputStream;
import org.smssecure.smssecure.crypto.MasterCipher;
import org.smssecure.smssecure.crypto.MasterSecret;
import org.smssecure.smssecure.crypto.MasterSecretUtil;
import org.smssecure.smssecure.notifications.MessageNotifier;
import org.smssecure.smssecure.util.Base64;
import org.smssecure.smssecure.util.MediaUtil;
import org.smssecure.smssecure.util.Util;
import org.whispersystems.libsignal.IdentityKey;
import org.whispersystems.libsignal.InvalidMessageException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class DatabaseFactory {
  private static final String TAG = DatabaseFactory.class.getSimpleName();

  private static final int INTRODUCED_IDENTITIES_VERSION                   = 2;
  private static final int INTRODUCED_INDEXES_VERSION                      = 3;
  private static final int INTRODUCED_DATE_SENT_VERSION                    = 4;
  private static final int INTRODUCED_DRAFTS_VERSION                       = 5;
  private static final int INTRODUCED_NEW_TYPES_VERSION                    = 6;
  private static final int INTRODUCED_MMS_BODY_VERSION                     = 7;
  private static final int INTRODUCED_MMS_FROM_VERSION                     = 8;
  private static final int INTRODUCED_TOFU_IDENTITY_VERSION                = 9;
  private static final int INTRODUCED_PUSH_DATABASE_VERSION                = 10;
  private static final int INTRODUCED_GROUP_DATABASE_VERSION               = 11;
  private static final int INTRODUCED_DELIVERY_RECEIPTS                    = 13;
  private static final int INTRODUCED_PART_DATA_SIZE_VERSION               = 14;
  private static final int INTRODUCED_THUMBNAILS_VERSION                   = 15;
  private static final int INTRODUCED_IDENTITY_COLUMN_VERSION              = 16;
  private static final int INTRODUCED_UNIQUE_PART_IDS_VERSION              = 17;
  private static final int INTRODUCED_RECIPIENT_PREFS_DB                   = 18;
  private static final int INTRODUCED_COLOR_PREFERENCE_VERSION             = 20;
  private static final int INTRODUCED_DELIVERY_DATE                        = 21;
  private static final int INTRODUCED_DB_OPTIMIZATIONS_VERSION             = 22;
  private static final int INTRODUCED_CONVERSATION_LIST_THUMBNAILS_VERSION = 23;
  private static final int INTRODUCED_ARCHIVE_VERSION                      = 24;
  private static final int INTRODUCED_CONVERSATION_LIST_STATUS_VERSION     = 25;
  private static final int MIGRATED_CONVERSATION_LIST_STATUS_VERSION       = 26;
  private static final int INTRODUCED_SUBSCRIPTION_ID_VERSION              = 28;
  private static final int INTRODUCED_LAST_SEEN                            = 29;
  private static final int INTRODUCED_NOTIFIED                             = 30;
  private static final int INTRODUCED_DIGEST                               = 31;

  /*
   * Yes, INTRODUCED_XMPP_TRANSPORT > DATABASE_VERSION to allow database
   * downgrade when XMPP transport will be included in unstable branch.
   */
  private static final int INTRODUCED_XMPP_TRANSPORT                       = 32;
  private static final int DATABASE_VERSION                                = 31;

  private static final String DATABASE_NAME    = "messages.db";
  private static final Object lock             = new Object();

  private static DatabaseFactory instance;

  private DatabaseHelper databaseHelper;

  private final SmsDatabase sms;
  private final EncryptingSmsDatabase encryptingSms;
  private final MmsDatabase mms;
  private final AttachmentDatabase attachments;
  private final MediaDatabase media;
  private final ThreadDatabase thread;
  private final CanonicalAddressDatabase address;
  private final MmsAddressDatabase mmsAddress;
  private final MmsSmsDatabase mmsSmsDatabase;
  private final IdentityDatabase identityDatabase;
  private final DraftDatabase draftDatabase;
  private final RecipientPreferenceDatabase recipientPreferenceDatabase;
  private final ContactsDatabase contactsDatabase;

  public static DatabaseFactory getInstance(Context context) {
    synchronized (lock) {
      if (instance == null)
        instance = new DatabaseFactory(context.getApplicationContext());

      return instance;
    }
  }

  public static MmsSmsDatabase getMmsSmsDatabase(Context context) {
    return getInstance(context).mmsSmsDatabase;
  }

  public static ThreadDatabase getThreadDatabase(Context context) {
    return getInstance(context).thread;
  }

  public static SmsDatabase getSmsDatabase(Context context) {
    return getInstance(context).sms;
  }

  public static MmsDatabase getMmsDatabase(Context context) {
    return getInstance(context).mms;
  }

  public static CanonicalAddressDatabase getAddressDatabase(Context context) {
    return getInstance(context).address;
  }

  public static EncryptingSmsDatabase getEncryptingSmsDatabase(Context context) {
    return getInstance(context).encryptingSms;
  }

  public static AttachmentDatabase getAttachmentDatabase(Context context) {
    return getInstance(context).attachments;
  }

  public static MediaDatabase getMediaDatabase(Context context) {
    return getInstance(context).media;
  }

  public static MmsAddressDatabase getMmsAddressDatabase(Context context) {
    return getInstance(context).mmsAddress;
  }

  public static IdentityDatabase getIdentityDatabase(Context context) {
    return getInstance(context).identityDatabase;
  }

  public static DraftDatabase getDraftDatabase(Context context) {
    return getInstance(context).draftDatabase;
  }

  public static RecipientPreferenceDatabase getRecipientPreferenceDatabase(Context context) {
    return getInstance(context).recipientPreferenceDatabase;
  }

  public static ContactsDatabase getContactsDatabase(Context context) {
    return getInstance(context).contactsDatabase;
  }

  private DatabaseFactory(Context context) {
    this.databaseHelper              = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.sms                         = new SmsDatabase(context, databaseHelper);
    this.encryptingSms               = new EncryptingSmsDatabase(context, databaseHelper);
    this.mms                         = new MmsDatabase(context, databaseHelper);
    this.attachments                 = new AttachmentDatabase(context, databaseHelper);
    this.media                       = new MediaDatabase(context, databaseHelper);
    this.thread                      = new ThreadDatabase(context, databaseHelper);
    this.address                     = CanonicalAddressDatabase.getInstance(context);
    this.mmsAddress                  = new MmsAddressDatabase(context, databaseHelper);
    this.mmsSmsDatabase              = new MmsSmsDatabase(context, databaseHelper);
    this.identityDatabase            = new IdentityDatabase(context, databaseHelper);
    this.draftDatabase               = new DraftDatabase(context, databaseHelper);
    this.recipientPreferenceDatabase = new RecipientPreferenceDatabase(context, databaseHelper);
    this.contactsDatabase            = new ContactsDatabase(context);
  }

  public void reset(Context context) {
    DatabaseHelper old = this.databaseHelper;
    this.databaseHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);

    this.sms.reset(databaseHelper);
    this.encryptingSms.reset(databaseHelper);
    this.mms.reset(databaseHelper);
    this.attachments.reset(databaseHelper);
    this.thread.reset(databaseHelper);
    this.mmsAddress.reset(databaseHelper);
    this.mmsSmsDatabase.reset(databaseHelper);
    this.identityDatabase.reset(databaseHelper);
    this.draftDatabase.reset(databaseHelper);
    this.recipientPreferenceDatabase.reset(databaseHelper);
    old.close();

    this.address.reset(context);
  }

  public void onApplicationLevelUpgrade(Context context, MasterSecret masterSecret, int fromVersion,
                                        DatabaseUpgradeActivity.DatabaseUpgradeListener listener)
  {
    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    db.beginTransaction();

    // Do stuff here

    db.setTransactionSuccessful();
    db.endTransaction();

//    DecryptingQueue.schedulePendingDecrypts(context, masterSecret);
    MessageNotifier.updateNotification(context, masterSecret);
  }

  private static class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
      super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      db.execSQL(SmsDatabase.CREATE_TABLE);
      db.execSQL(MmsDatabase.CREATE_TABLE);
      db.execSQL(AttachmentDatabase.CREATE_TABLE);
      db.execSQL(ThreadDatabase.CREATE_TABLE);
      db.execSQL(MmsAddressDatabase.CREATE_TABLE);
      db.execSQL(IdentityDatabase.CREATE_TABLE);
      db.execSQL(DraftDatabase.CREATE_TABLE);
      db.execSQL(RecipientPreferenceDatabase.CREATE_TABLE);

      executeStatements(db, SmsDatabase.CREATE_INDEXS);
      executeStatements(db, MmsDatabase.CREATE_INDEXS);
      executeStatements(db, AttachmentDatabase.CREATE_INDEXS);
      executeStatements(db, ThreadDatabase.CREATE_INDEXS);
      executeStatements(db, MmsAddressDatabase.CREATE_INDEXS);
      executeStatements(db, DraftDatabase.CREATE_INDEXS);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.beginTransaction();

      if (newVersion < INTRODUCED_XMPP_TRANSPORT) {}

      db.setTransactionSuccessful();
      db.endTransaction();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.beginTransaction();

      if (oldVersion < INTRODUCED_IDENTITIES_VERSION) {
        db.execSQL("CREATE TABLE identities (_id INTEGER PRIMARY KEY, key TEXT UNIQUE, name TEXT UNIQUE, mac TEXT);");
      }

      if (oldVersion < INTRODUCED_INDEXES_VERSION) {
        executeStatements(db, new String[] {
            "CREATE INDEX IF NOT EXISTS sms_thread_id_index ON sms (thread_id);",
            "CREATE INDEX IF NOT EXISTS sms_read_index ON sms (read);",
            "CREATE INDEX IF NOT EXISTS sms_read_and_thread_id_index ON sms (read,thread_id);",
            "CREATE INDEX IF NOT EXISTS sms_type_index ON sms (type);"
        });
        executeStatements(db, new String[] {
            "CREATE INDEX IF NOT EXISTS mms_thread_id_index ON mms (thread_id);",
            "CREATE INDEX IF NOT EXISTS mms_read_index ON mms (read);",
            "CREATE INDEX IF NOT EXISTS mms_read_and_thread_id_index ON mms (read,thread_id);",
            "CREATE INDEX IF NOT EXISTS mms_message_box_index ON mms (msg_box);"
        });
        executeStatements(db, new String[] {
            "CREATE INDEX IF NOT EXISTS part_mms_id_index ON part (mid);"
        });
        executeStatements(db, new String[] {
            "CREATE INDEX IF NOT EXISTS thread_recipient_ids_index ON thread (recipient_ids);",
        });
        executeStatements(db, new String[] {
            "CREATE INDEX IF NOT EXISTS mms_addresses_mms_id_index ON mms_addresses (mms_id);",
        });
      }

      if (oldVersion < INTRODUCED_DATE_SENT_VERSION) {
        db.execSQL("ALTER TABLE sms ADD COLUMN date_sent INTEGER;");
        db.execSQL("UPDATE sms SET date_sent = date;");

        db.execSQL("ALTER TABLE mms ADD COLUMN date_received INTEGER;");
        db.execSQL("UPDATE mms SET date_received = date;");
      }

      if (oldVersion < INTRODUCED_DRAFTS_VERSION) {
        db.execSQL("CREATE TABLE drafts (_id INTEGER PRIMARY KEY, thread_id INTEGER, type TEXT, value TEXT);");
        executeStatements(db, new String[] {
            "CREATE INDEX IF NOT EXISTS draft_thread_index ON drafts (thread_id);",
        });
      }

      if (oldVersion < INTRODUCED_NEW_TYPES_VERSION) {
        String KEY_EXCHANGE             = "?SilenceKeyExchange";
        String SYMMETRIC_ENCRYPT        = "?SilenceLocalEncrypt";
        String ASYMMETRIC_ENCRYPT       = "?SilenceAsymmetricEncrypt";
        String ASYMMETRIC_LOCAL_ENCRYPT = "?SilenceAsymmetricLocalEncrypt";
        String PROCESSED_KEY_EXCHANGE   = "?SilenceKeyExchangd";
        String STALE_KEY_EXCHANGE       = "?SilenceKeyExchangs";

        // SMS Updates
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {20L+"", 1L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {21L+"", 43L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {22L+"", 4L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {23L+"", 2L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {24L+"", 5L+""});

        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(21L | 0x800000L)+"", 42L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(23L | 0x800000L)+"", 44L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L | 0x800000L)+"", 45L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L | 0x800000L | 0x10000000L)+"", 46L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L)+"", 47L+""});
        db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L | 0x800000L | 0x08000000L)+"", 48L+""});

        db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
                   new String[] {(SYMMETRIC_ENCRYPT.length()+1)+"",
                                  0x80000000L+"",
                                  SYMMETRIC_ENCRYPT + "%"});

        db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
                   new String[] {(ASYMMETRIC_LOCAL_ENCRYPT.length()+1)+"",
                                  0x40000000L+"",
                                  ASYMMETRIC_LOCAL_ENCRYPT + "%"});

        db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
                   new String[] {(ASYMMETRIC_ENCRYPT.length()+1)+"",
                                 (0x800000L | 0x20000000L)+"",
                                 ASYMMETRIC_ENCRYPT + "%"});

        db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
                   new String[] {(KEY_EXCHANGE.length()+1)+"",
                                  0x8000L+"",
                                  KEY_EXCHANGE + "%"});

        db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
                   new String[] {(PROCESSED_KEY_EXCHANGE.length()+1)+"",
                                  (0x8000L | 0x2000L)+"",
                                  PROCESSED_KEY_EXCHANGE + "%"});

        db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
                   new String[] {(STALE_KEY_EXCHANGE.length()+1)+"",
                                 (0x8000L | 0x4000L)+"",
                                 STALE_KEY_EXCHANGE + "%"});

        // MMS Updates

        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x80000000L)+"", 1+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(23L | 0x80000000L)+"", 2+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(21L | 0x80000000L)+"", 4+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(24L | 0x80000000L)+"", 12+""});

        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(21L | 0x80000000L | 0x800000L) +"", 5+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(23L | 0x80000000L | 0x800000L) +"", 6+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x20000000L | 0x800000L) +"", 7+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x80000000L | 0x800000L) +"", 8+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x08000000L | 0x800000L) +"", 9+""});
        db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x10000000L | 0x800000L) +"", 10+""});

        // Thread Updates

        db.execSQL("ALTER TABLE thread ADD COLUMN snippet_type INTEGER;");

        db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
                   "snippet_type = ? WHERE snippet LIKE ?",
                   new String[] {(SYMMETRIC_ENCRYPT.length()+1)+"",
                                 0x80000000L+"",
                                 SYMMETRIC_ENCRYPT + "%"});

        db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
                   "snippet_type = ? WHERE snippet LIKE ?",
                   new String[] {(ASYMMETRIC_LOCAL_ENCRYPT.length()+1)+"",
                                  0x40000000L+"",
                                  ASYMMETRIC_LOCAL_ENCRYPT + "%"});

        db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
                   "snippet_type = ? WHERE snippet LIKE ?",
                   new String[] {(ASYMMETRIC_ENCRYPT.length()+1)+"",
                                 (0x800000L | 0x20000000L)+"",
                                 ASYMMETRIC_ENCRYPT + "%"});

        db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
                   "snippet_type = ? WHERE snippet LIKE ?",
                   new String[] {(KEY_EXCHANGE.length()+1)+"",
                       0x8000L+"",
                       KEY_EXCHANGE + "%"});

        db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
                   "snippet_type = ? WHERE snippet LIKE ?",
                   new String[] {(STALE_KEY_EXCHANGE.length()+1)+"",
                                 (0x8000L | 0x4000L)+"",
                                 STALE_KEY_EXCHANGE + "%"});

        db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
                   "snippet_type = ? WHERE snippet LIKE ?",
                   new String[] {(PROCESSED_KEY_EXCHANGE.length()+1)+"",
                                 (0x8000L | 0x2000L)+"",
                                 PROCESSED_KEY_EXCHANGE + "%"});
      }

      if (oldVersion < INTRODUCED_MMS_BODY_VERSION) {
        db.execSQL("ALTER TABLE mms ADD COLUMN body TEXT");
        db.execSQL("ALTER TABLE mms ADD COLUMN part_count INTEGER");
      }

      if (oldVersion < INTRODUCED_MMS_FROM_VERSION) {
        db.execSQL("ALTER TABLE mms ADD COLUMN address TEXT");

        Cursor cursor = db.query("mms_addresses", null, "type = ?", new String[] {0x89+""},
                                 null, null, null);

        while (cursor != null && cursor.moveToNext()) {
          long mmsId     = cursor.getLong(cursor.getColumnIndexOrThrow("mms_id"));
          String address = cursor.getString(cursor.getColumnIndexOrThrow("address"));

          if (!TextUtils.isEmpty(address)) {
            db.execSQL("UPDATE mms SET address = ? WHERE _id = ?", new String[]{address, mmsId+""});
          }
        }

        if (cursor != null)
          cursor.close();
      }

      if (oldVersion < INTRODUCED_TOFU_IDENTITY_VERSION) {
        db.execSQL("DROP TABLE identities");
        db.execSQL("CREATE TABLE identities (_id INTEGER PRIMARY KEY, recipient INTEGER UNIQUE, key TEXT, mac TEXT);");
      }

      if (oldVersion < INTRODUCED_PUSH_DATABASE_VERSION) {
        db.execSQL("ALTER TABLE part ADD COLUMN pending_push INTEGER;");
        db.execSQL("CREATE INDEX IF NOT EXISTS pending_push_index ON part (pending_push);");
      }

      if (oldVersion < INTRODUCED_GROUP_DATABASE_VERSION) {
        db.execSQL("ALTER TABLE sms ADD COLUMN address_device_id INTEGER DEFAULT 1;");
        db.execSQL("ALTER TABLE mms ADD COLUMN address_device_id INTEGER DEFAULT 1;");
      }

      if (oldVersion < INTRODUCED_DELIVERY_RECEIPTS) {
        db.execSQL("ALTER TABLE sms ADD COLUMN delivery_receipt_count INTEGER DEFAULT 0;");
        db.execSQL("ALTER TABLE mms ADD COLUMN delivery_receipt_count INTEGER DEFAULT 0;");
        db.execSQL("CREATE INDEX IF NOT EXISTS sms_date_sent_index ON sms (date_sent);");
        db.execSQL("CREATE INDEX IF NOT EXISTS mms_date_sent_index ON mms (date);");
      }

      if (oldVersion < INTRODUCED_PART_DATA_SIZE_VERSION) {
        db.execSQL("ALTER TABLE part ADD COLUMN data_size INTEGER DEFAULT 0;");
      }

      if (oldVersion < INTRODUCED_THUMBNAILS_VERSION) {
        db.execSQL("ALTER TABLE part ADD COLUMN thumbnail TEXT;");
        db.execSQL("ALTER TABLE part ADD COLUMN aspect_ratio REAL;");
      }

      if (oldVersion < INTRODUCED_IDENTITY_COLUMN_VERSION) {
        db.execSQL("ALTER TABLE sms ADD COLUMN mismatched_identities TEXT");
        db.execSQL("ALTER TABLE mms ADD COLUMN mismatched_identities TEXT");
        db.execSQL("ALTER TABLE mms ADD COLUMN network_failures TEXT");
      }

      if (oldVersion < INTRODUCED_UNIQUE_PART_IDS_VERSION) {
        db.execSQL("ALTER TABLE part ADD COLUMN unique_id INTEGER NOT NULL DEFAULT 0");
      }

      if (oldVersion < INTRODUCED_RECIPIENT_PREFS_DB) {
        db.execSQL("CREATE TABLE recipient_preferences " +
                   "(_id INTEGER PRIMARY KEY, recipient_ids TEXT UNIQUE, block INTEGER DEFAULT 0, " +
                   "notification TEXT DEFAULT NULL, vibrate INTEGER DEFAULT 0, mute_until INTEGER DEFAULT 0)");
      }

      if (oldVersion < INTRODUCED_COLOR_PREFERENCE_VERSION) {
        db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN color TEXT DEFAULT NULL");
      }

      if (oldVersion < INTRODUCED_DELIVERY_DATE) {
        db.execSQL("ALTER TABLE sms ADD COLUMN date_delivery_received INTEGER DEFAULT 0");
        db.execSQL("ALTER TABLE mms ADD COLUMN date_delivery_received INTEGER DEFAULT 0");
      }

      if (oldVersion < INTRODUCED_DB_OPTIMIZATIONS_VERSION) {
        db.execSQL("UPDATE mms SET date_received = (date_received * 1000), date = (date * 1000);");
        db.execSQL("CREATE INDEX IF NOT EXISTS sms_thread_date_index ON sms (thread_id, date);");
        db.execSQL("CREATE INDEX IF NOT EXISTS mms_thread_date_index ON mms (thread_id, date_received);");
      }

      if (oldVersion < INTRODUCED_CONVERSATION_LIST_THUMBNAILS_VERSION) {
        db.execSQL("ALTER TABLE thread ADD COLUMN snippet_uri TEXT DEFAULT NULL");
      }

      if (oldVersion < INTRODUCED_ARCHIVE_VERSION) {
        db.execSQL("ALTER TABLE thread ADD COLUMN archived INTEGER DEFAULT 0");
        db.execSQL("CREATE INDEX IF NOT EXISTS archived_index ON thread (archived)");
      }

      if (oldVersion < INTRODUCED_CONVERSATION_LIST_STATUS_VERSION) {
        db.execSQL("ALTER TABLE thread ADD COLUMN status INTEGER DEFAULT -1");
      }

      if (oldVersion < MIGRATED_CONVERSATION_LIST_STATUS_VERSION) {
        List<Long> threads = new ArrayList<Long>();
        Cursor threadCursor = null;

        try {
          threadCursor = db.query("thread", new String[] {"_id"}, null, null, null, null, null);

          while (threadCursor != null && threadCursor.moveToNext()) {
            long threadId = threadCursor.getLong(threadCursor.getColumnIndexOrThrow("_id"));
            threads.add(threadId);
          }
        } catch (Exception e) {
          Log.w(TAG, e);
        } finally {
          if (threadCursor != null) threadCursor.close();
        }

        for (long thread : threads) {
          Cursor cursor = null;

          try {
            cursor = db.rawQuery("SELECT DISTINCT date AS date_received, status " +
            "FROM sms WHERE (thread_id = ?1) " +
            "UNION ALL SELECT DISTINCT date_received, -1 AS status " +
            "FROM mms WHERE (thread_id = ?1) " +
            "ORDER BY date_received DESC LIMIT 1", new String[]{thread + ""});

            if (cursor != null && cursor.moveToNext()) {
              int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));

              db.execSQL("UPDATE thread SET status = ? WHERE _id = ?",
              new String[]{status + "", thread + ""});
              Log.w(TAG, "Thread " + thread + " updated!");
            }
          } catch (Exception e) {
            Log.w(TAG, e);
          } finally {
            if (cursor != null) cursor.close();
          }
        }
      }

      if (oldVersion < INTRODUCED_SUBSCRIPTION_ID_VERSION) {
        db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN default_subscription_id INTEGER DEFAULT -1");
        db.execSQL("ALTER TABLE sms ADD COLUMN subscription_id INTEGER DEFAULT -1");
        db.execSQL("ALTER TABLE mms ADD COLUMN subscription_id INTEGER DEFAULT -1");
      }

      if (oldVersion < INTRODUCED_LAST_SEEN) {
        db.execSQL("ALTER TABLE thread ADD COLUMN last_seen INTEGER DEFAULT 0");
      }

      if (oldVersion < INTRODUCED_NOTIFIED) {
        db.execSQL("ALTER TABLE sms ADD COLUMN notified INTEGER DEFAULT 0");
        db.execSQL("ALTER TABLE mms ADD COLUMN notified INTEGER DEFAULT 0");

        db.execSQL("DROP INDEX sms_read_and_thread_id_index");
        db.execSQL("CREATE INDEX IF NOT EXISTS sms_read_and_notified_and_thread_id_index ON sms(read,notified,thread_id)");

        db.execSQL("DROP INDEX mms_read_and_thread_id_index");
        db.execSQL("CREATE INDEX IF NOT EXISTS mms_read_and_notified_and_thread_id_index ON mms(read,notified,thread_id)");
      }

      if (oldVersion < INTRODUCED_DIGEST) {
        db.execSQL("ALTER TABLE part ADD COLUMN digest BLOB");
      }

      db.setTransactionSuccessful();
      db.endTransaction();
    }

    private void executeStatements(SQLiteDatabase db, String[] statements) {
      for (String statement : statements)
        db.execSQL(statement);
    }

  }
}

{'repo_name': 'SilenceIM/Silence', 'stars': '1011', 'repo_language': 'Java', 'file_name': 'HexTest.java', 'mime_type': 'text/x-java', 'hash': -1028909237013154770, 'source_dataset': 'data'}


/**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2006 Sun Microsystems Inc. All Rights Reserved
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License). You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the License at
 * https://opensso.dev.java.net/public/CDDLv1.0.html or
 * opensso/legal/CDDLv1.0.txt
 * See the License for the specific language governing
 * permission and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at opensso/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * $Id: DiscoUtils.java,v 1.5 2008/06/25 05:47:12 qcheng Exp $
 *
 */

package com.sun.identity.liberty.ws.disco.common;

import java.security.cert.X509Certificate;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.BitSet;

import com.sun.identity.saml.assertion.NameIdentifier;
import com.sun.identity.saml.assertion.Statement;
import com.sun.identity.liberty.ws.disco.DiscoveryException;
import com.sun.identity.liberty.ws.disco.EncryptedResourceID;
import com.sun.identity.liberty.ws.disco.ResourceOffering;
import com.sun.identity.liberty.ws.disco.ResourceID;
import com.sun.identity.liberty.ws.disco.Description;
import com.sun.identity.liberty.ws.disco.jaxb.*;
import com.sun.identity.liberty.ws.disco.jaxb11.*;
import com.sun.identity.liberty.ws.disco.plugins.NameIdentifierMapper;
import com.sun.identity.liberty.ws.disco.plugins.jaxb.*;
import com.sun.identity.liberty.ws.interfaces.Authorizer;
import com.sun.identity.liberty.ws.meta.jaxb.SPDescriptorType;
import com.sun.identity.liberty.ws.security.*;
import com.sun.identity.liberty.ws.soapbinding.Message;
import com.sun.identity.liberty.ws.soapbinding.ProviderHeader;
import com.sun.identity.liberty.ws.soapbinding.Utils;
import com.sun.identity.liberty.ws.util.ProviderManager;
import com.sun.identity.liberty.ws.util.ProviderUtil;
import com.sun.identity.federation.message.common.EncryptedNameIdentifier;
import com.sun.identity.federation.message.common.IDPProvidedNameIdentifier;

/**
 * Provides utility methods to discovery service.
 */
public class DiscoUtils extends DiscoSDKUtils {

    /**
     * Constructor
     * iPlanet-PRIVATE-DEFAULT-CONSTRUCTOR
     */
    private DiscoUtils() {
    }

    /**
     * Checks policy and returns resource offerings and credentials.
     * @param userDN user DN
     * @param message soap request Message received.
     * @param results Collection of InsertEntryType
     *  objects.
     * @param authorizer Authorizer object.
     * @param invoSession SessionContext
     * @param wscID web service client ID.
     * @param token token of this soap session.
     * @return Map of following key value pairs:
     *

     *  Key: OFFERINGS
     *  Value: List of ResourceOfferings
     *  Key: CREDENTIALS
     *  Value: List of credentials (Assertions)
     *

     */
    public static Map checkPolicyAndHandleDirectives(
                                String userDN, Message message,
                                Collection results, Authorizer authorizer,
                                SessionContext invoSession, String wscID,
                                Object token)
    {
        DiscoUtils.debug.message("DiscoService.checkPolicyAndHandleDirectives");

        List offerings = new LinkedList();
        List credentials = new LinkedList();
        Map env = null;
        Iterator k = results.iterator();
        while (k.hasNext()) {
            InsertEntryType entry = (InsertEntryType) k.next();
            if (authorizer != null) {
                if (env == null) {
                    env = new HashMap();
                    env.put(Authorizer.USER_ID, userDN);
                    env.put(Authorizer.AUTH_TYPE,
                        message.getAuthenticationMechanism());
                    env.put(Authorizer.MESSAGE, message);
                }
                if (!authorizer.isAuthorized(message.getToken(),
                        DiscoConstants.ACTION_LOOKUP,
                        entry.getResourceOffering(),
                        env))
                {
                    DiscoUtils.debug.error("DiscoveryService.checkPolicyAndHan"
                        +"dleDirectives: WSC is not authorized to do lookup");
                    continue;
                }
            }
            ResourceOffering current = null;
            try {
                current = new ResourceOffering(
                Utils.convertJAXBToElement(entry.getResourceOffering(), false));
            } catch (Exception ex) {
                DiscoUtils.debug.error("DiscoveryService.checkPolicyAndHandle"
                    +"Directives:exception when constructing ResourceOffering:",
                    ex);
                continue;
            }
            List directives = entry.getAny();
            if ((directives == null) || directives.isEmpty()) {
                DiscoUtils.debug.message("DiscoService: no directives.");
                offerings.add(current);
            } else {
                DiscoUtils.debug.message("DiscoService: has directives.");
                handleDirectives(current, directives, userDN, message,
                        invoSession, wscID, token, offerings, credentials);
            }
        }

        Map returnMap = new HashMap();
        returnMap.put(OFFERINGS, offerings);
        returnMap.put(CREDENTIALS, credentials);
        return returnMap;
    }

    private static String ALL = "all";
    private static int AUTHN = 0;
    private static int AUTHO = 1;
    private static int SESSION = 2;
    private static int BEARER = 3;
    private static int LOGOUT = 4;
    private static int SIZE = 5;
    private static BitSet EMPTY_BITSET = new BitSet(SIZE);
    private static void handleDirectives(ResourceOffering current,
                                        List directives,
                                        String userDN,
                                        Message message,
                                        SessionContext invoSession,
                                        String wscID,
                                        Object token,
                                        List offerings,
                                        List credentials)
    {
        Map descIDDirectiveMap = new HashMap();
        BitSet all = new BitSet(SIZE);
        if (invoSession != null) {
            if (DiscoServiceManager.needSessionContextStatement()) {
                all.set(SESSION);
            }
        }
        Iterator iter0 = directives.iterator();
        while(iter0.hasNext()) {
            Object directive = iter0.next();
            List descIDRefs =
                ((DirectiveType) directive).getDescriptionIDRefs();
            if (directive instanceof EncryptResourceIDElement) {
                debug.message("DiscoService: has encrypt D");
                current = doEncryption(current);
            } else if
                (directive instanceof AuthenticateRequesterElement)
            {
                setMap(descIDRefs, AUTHN, descIDDirectiveMap, all);
            } else if
                (directive instanceof AuthorizeRequesterElement)
            {
                setMap(descIDRefs, AUTHO, descIDDirectiveMap, all);
            } else if
                (directive instanceof AuthenticateSessionContextElement)
            {
                setMap(descIDRefs, SESSION, descIDDirectiveMap, all);
            } else if
                (directive instanceof GenerateBearerTokenElement)
            {
                setMap(descIDRefs, BEARER, descIDDirectiveMap, all);
            } else {
                if (debug.messageEnabled()) {
                    debug.message("DiscoUtils.handleDirective: directive not "
                        + "supported.");
                }
                continue;
            }
        }

        Map directiveCredIDMap = new HashMap();
        Map descIDCredIDMap = new HashMap();
        Iterator iter2 = descIDDirectiveMap.keySet().iterator();
        while (iter2.hasNext()) {
            String descID = (String) iter2.next();
            BitSet dirs = (BitSet) descIDDirectiveMap.get(descID);
            dirs.or(all);
            if (directiveCredIDMap.containsKey(dirs)) {
                descIDCredIDMap.put(descID,
                        (String) directiveCredIDMap.get(dirs));
            } else {
                String ref = generateCredential(dirs, current, message, userDN,
                                credentials, invoSession, wscID, token);
                if (ref != null) {
                    directiveCredIDMap.put(dirs, ref);
                    descIDCredIDMap.put(descID, ref);
                }
            }
        }

        // loop though each description to add credIDRefs
        Iterator descIter =
                current.getServiceInstance().getDescription().iterator();
        List credIDs = null;
        while (descIter.hasNext()) {
            credIDs = new ArrayList();
            Description desc = (Description) descIter.next();
            String id = desc.getId();
            if ((id != null) && (id.length() != 0) &&
                (descIDCredIDMap.containsKey(id)))
            {
                if (debug.messageEnabled()) {
                    debug.message("DiscoUtils.handleDirective: containsKey:"
                                + id);
                }
                credIDs.add((String) descIDCredIDMap.get(id));
            } else {
                debug.message("DiscoUtils.handleDirective:  not containsKey");
                String allCred = (String) descIDCredIDMap.get("all");
                if (allCred == null) {
                    if (directiveCredIDMap.containsKey(all)) {
                        allCred = (String) directiveCredIDMap.get(all);
                        descIDCredIDMap.put("all", allCred);
                        credIDs.add(allCred);
                    } else {
                        if (!all.equals(EMPTY_BITSET)) {
                            allCred = generateCredential(all, current, message,
                                userDN, credentials, invoSession, wscID,token);
                            if (allCred != null) {
                                descIDCredIDMap.put("all", allCred);
                                credIDs.add(allCred);
                            }
                        }
                    }
                } else {
                    credIDs.add(allCred);
                }
            }
            if (!credIDs.isEmpty()) {
                desc.setCredentialRef(credIDs);
            }
        }

        // everything is done, add current to offerings
        offerings.add(current);

    }

    private static ResourceOffering doEncryption(ResourceOffering current) {
        ResourceID ri = current.getResourceID();
        if (ri == null) {
            return current;
        }
        try {
            EncryptedResourceID eri =
                        EncryptedResourceID.getEncryptedResourceID(
                                ri,
                                current.getServiceInstance().getProviderID());
            current.setResourceID(null);
            current.setEncryptedResourceID(eri);
        } catch (Exception e) {
            debug.error("DiscoUtils.doEncryption: exception:", e);
        }
        return current;
    }

    private static void setMap(List descIDRefs,
                                int type,
                                Map descIDDirectiveMap,
                                BitSet all)
    {
        if ((descIDRefs == null) || (descIDRefs.size() ==0)) {
            all.set(type);
        } else {
            Iterator iter1 = descIDRefs.iterator();
            while (iter1.hasNext()) {
                String descID = ((DescriptionType) iter1.next()).getId();
                BitSet cur = (BitSet) descIDDirectiveMap.get(descID);
                if (cur == null) {
                    cur = new BitSet(SIZE);
                }
                cur.set(type);
                descIDDirectiveMap.put(descID, cur);
            }
        }
    }

    private static SessionContext getSessionContext(SecurityAssertion assertion)
    {
        if (assertion == null) {
            return null;
        }
        Iterator iter = assertion.getStatement().iterator();
        SessionContext context = null;
        while (iter.hasNext()) {
            Statement st = (Statement) iter.next();
            int type = st.getStatementType();
            if (type == ResourceAccessStatement.RESOURCEACCESS_STATEMENT) {
                context = ((ResourceAccessStatement) st).getSessionContext();
                if (context != null) {
                    return context;
                }
            } else if (type == SessionContextStatement.SESSIONCONTEXT_STATEMENT)
            {
                context = ((SessionContextStatement) st).getSessionContext();
                if (context != null) {
                    return context;
                }
            }
        }
        return null;
    }

    private static String generateCredential(BitSet dirs,
                                                ResourceOffering current,
                                                Message message,
                                                String userDN,
                                                List credentials,
                                                SessionContext invoSession,
                                                String wscID,
                                                Object token)
    {
        SecurityAssertion assertion = null;
        try {
            SecurityTokenManager secuMgr = new SecurityTokenManager(token);

            NameIdentifier senderIdentity = null;
            String providerID = wscID;
            if ((providerID == null) || (providerID.length() == 0)) {
                ProviderHeader ph = message.getProviderHeader();
                if (ph != null) {
                    providerID = ph.getProviderID();
                }
            }

            SessionContext invocatorSession = invoSession;
            if (invocatorSession == null) {
                invocatorSession = getSessionContext(message.getAssertion());
            }

            String tproviderID = current.getServiceInstance().getProviderID();
            if (invocatorSession != null) {
                try {
                    ProviderManager pm = ProviderUtil.getProviderManager();
                    SessionSubject sub = invocatorSession.getSessionSubject();
                    NameIdentifier ni = sub.getNameIdentifier();
                    if ((ni.getFormat() != null) && (ni.getFormat().equals(
                        "urn:liberty:iff:nameid:encrypted")))
                    {
                        ni =EncryptedNameIdentifier.getDecryptedNameIdentifier(
                            ni, pm.getDecryptionKey(
                            DiscoServiceManager.getDiscoProviderID()));
                    }

                    NameIdentifier newNi = null;
                    NameIdentifierMapper niMapper =
                        DiscoServiceManager.getNameIdentifierMapper();
                    if (niMapper != null) {
                        String discoEntityID =
                            DiscoServiceManager.getDiscoProviderID();
                        newNi = niMapper.getNameIdentifier(
                            tproviderID, discoEntityID, ni, userDN);
                    }
                    if ((newNi != null) && !newNi.equals(ni)) {
                         sub.setNameIdentifier(newNi);
                         // modify IDPProvidedNameIdentifier, this should be
                         // a EncryptedIDPProvidedNameIdentifier, but not
                         // defined by specification.
                         // Or set this to null once we make it optional
                         // in SessionSubject class implementation
                         IDPProvidedNameIdentifier idpNi =
                             sub.getIDPProvidedNameIdentifier();
                         if (idpNi != null) {
                             IDPProvidedNameIdentifier newIdpNi =
                                 new IDPProvidedNameIdentifier(
                                     newNi.getName(),
                                     newNi.getNameQualifier(),
                                     newNi.getFormat());
                             sub.setIDPProvidedNameIdentifier(newIdpNi);
                         }
		    } else if (pm.isNameIDEncryptionEnabled(tproviderID)){
                        sub.setNameIdentifier(
                            EncryptedNameIdentifier.getEncryptedNameIdentifier(
                            ni, tproviderID,
                            pm.getEncryptionKey(tproviderID),
                            pm.getEncryptionKeyAlgorithm(tproviderID),
                            pm.getEncryptionKeyStrength(tproviderID)));
                    } else {
                        sub.setNameIdentifier(ni);
                    }
                    invocatorSession.setSessionSubject(sub);
                } catch (Exception ex) {
                    debug.error("DiscoUtils.handleDirective: En/Decryption"
                        + " Exception:", ex);
                    return null;
                }
            }

            Object resourceID = current.getEncryptedResourceID();
            if (resourceID == null) {
                resourceID = current.getResourceID();
                if (resourceID == null) {
                    resourceID = (String) DiscoConstants.IMPLIED_RESOURCE;
                } else {
                    resourceID = ((ResourceID) resourceID).getResourceID();
                }
            }
            if (dirs.get(BEARER)) {
                if (dirs.get(AUTHN) || dirs.get(AUTHO) || dirs.get(SESSION)) {
                    if ((providerID != null) && (providerID.length() != 0)) {
                        senderIdentity = new NameIdentifier(
                                    providerID,
                                    null,
                                    DiscoConstants.PROVIDER_ID_FORMAT);
                    } else {
                        senderIdentity = new NameIdentifier(userDN);
                    }
                    if (resourceID instanceof String) {
                        assertion = secuMgr.getSAMLBearerToken(
                                        senderIdentity,
                                        invocatorSession,
                                        (String) resourceID,
                                        dirs.get(AUTHN),
                                        dirs.get(AUTHO),
                                        tproviderID);
                    } else {
                        assertion = secuMgr.getSAMLBearerToken(
                                        senderIdentity,
                                        invocatorSession,
                                        (EncryptedResourceID) resourceID,
                                        dirs.get(AUTHN),
                                        dirs.get(AUTHO),
                                        tproviderID);
                    }
                }
            } else {
                if ((providerID != null) && (providerID.length() != 0)) {
                    senderIdentity = new NameIdentifier(
                                providerID,
                                null,
                                DiscoConstants.PROVIDER_ID_FORMAT);
                } else {
                    senderIdentity = new NameIdentifier(userDN);
                }
                if (providerID != null) {
                    secuMgr.setCertAlias(ProviderUtil.getProviderManager()
                        .getSigningKeyAlias(providerID));
                } else {
                    X509Certificate wscCert = message.getPeerCertificate();
                    if (wscCert == null) {
                        wscCert = message.getMessageCertificate();
                        if (wscCert == null) {
                            if (debug.messageEnabled()) {
                                debug.message("DiscoUtils.generateCredential:"
                                    + "client cert is null. Cannot generate "
                                    + "credential.");
                            }
                            return null;
                        }
                    }
                    secuMgr.setCertificate(wscCert);
                }

                if (resourceID instanceof String) {
                    assertion = secuMgr.getSAMLAuthorizationToken(
                                        senderIdentity,
                                        invocatorSession,
                                        (String) resourceID,
                                        dirs.get(AUTHN),
                                        dirs.get(AUTHO),
                                        tproviderID);
                } else {
                    assertion = secuMgr.getSAMLAuthorizationToken(
                                        senderIdentity,
                                        invocatorSession,
                                        (EncryptedResourceID) resourceID,
                                        dirs.get(AUTHN),
                                        dirs.get(AUTHO),
                                        tproviderID);
                }
            }
        } catch (Exception ex) {
            debug.error("DiscoUtils.generateCredential:"
                            + "cannot generate credential: ", ex);
        }
        if (assertion == null) {
            debug.error("DiscoUtils.generateCredential: "
                            + "cannot generate credential.");

            return null;
        } else {
            credentials.add(assertion);
            return assertion.getAssertionID();
        }
    }

}

{'repo_name': 'OpenRock/OpenAM', 'stars': '136', 'repo_language': 'Java', 'file_name': 'FSAccountManager.java', 'mime_type': 'text/x-java', 'hash': 7005023753864796245, 'source_dataset': 'data'}


# frozen_string_literal: true

json.cache! [I18n.locale, @shipment] do
  json.(@shipment, *shipment_attributes)
  json.order_id(@shipment.order.number)
  json.stock_location_name(@shipment.stock_location.name)
  json.shipping_rates(@shipment.shipping_rates) do |shipping_rate|
    json.partial!("spree/api/shipping_rates/shipping_rate", shipping_rate: shipping_rate)
  end
  json.selected_shipping_rate do
    if @shipment.selected_shipping_rate
      json.partial!("spree/api/shipping_rates/shipping_rate", shipping_rate: @shipment.selected_shipping_rate)
    else
      json.nil!
    end
  end
  json.shipping_methods(@shipment.shipping_methods) do |shipping_method|
    json.(shipping_method, :id, :name)
    json.zones(shipping_method.zones) do |zone|
      json.(zone, :id, :name, :description)
    end
    json.shipping_categories(shipping_method.shipping_categories) do |shipping_category|
      json.(shipping_category, :id, :name)
    end
  end
  json.manifest(@shipment.manifest) do |manifest_item|
    json.variant do
      json.partial!("spree/api/variants/small", variant: manifest_item.variant)
    end
    json.quantity(manifest_item.quantity)
    json.states(manifest_item.states)
  end
end

{'repo_name': 'solidusio/solidus', 'stars': '3197', 'repo_language': 'Ruby', 'file_name': 'halt-for-doc-only-changes.sh', 'mime_type': 'text/x-shellscript', 'hash': -3213400463112903564, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
  <xsl:template match="/">
    <root xmlns="urn:A" xmlns:b="urn:B" xmlns:a="urn:A">
      <Product a:ID="1001"/>
    </root>
  </xsl:template>
</xsl:stylesheet>

{'repo_name': 'trevorlinton/webkit.js', 'stars': '1804', 'repo_language': 'None', 'file_name': 'ProgramBinary.cpp', 'mime_type': 'text/x-c++', 'hash': -1035935738337980428, 'source_dataset': 'data'}


<?php
/**
 * This file is part of a FireGento e.V. module.
 *
 * This FireGento e.V. module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This script is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * PHP version 5
 *
 * @category  FireGento
 * @package   FireGento_MageMonitoring
 * @author    FireGento Team <team@firegento.com>
 * @copyright 2015 FireGento Team (http://www.firegento.com)
 * @license   http://opensource.org/licenses/gpl-3.0 GNU General Public License, version 3 (GPLv3)
 */

/**
 * class Hackathon_MageMonitoring_Model_Widget_HealthCheck_ProductComposition
 *
 * @category FireGento
 * @package  FireGento_MageMonitoring
 * @author   FireGento Team <team@firegento.com>
 */
class Hackathon_MageMonitoring_Model_Widget_HealthCheck_ProductComposition
    extends Hackathon_MageMonitoring_Model_Widget_Abstract
    implements Hackathon_MageMonitoring_Model_Widget
{
    /**
     * Returns name
     *
     * @see Hackathon_MageMonitoring_Model_Widget::getName()
     */
    public function getName()
    {
        return 'Product Composition Check';
    }

    /**
     * Returns version
     *
     * @see Hackathon_MageMonitoring_Model_Widget::getVersion()
     */
    public function getVersion()
    {
        return '1.0';
    }

    /**
     * Returns isActive flag
     *
     * @see Hackathon_MageMonitoring_Model_Widget::isActive()
     */
    public function isActive()
    {
        return true;
    }

    /**
     * Gets data row
     *
     * @param  array $simples array like "sku => connected product count"
     * @return array avg, biggest, etc data array
     */
    private function getDataRow($simples)
    {
        $avgSimplePerConfig = number_format(array_sum($simples) / count(array_keys($simples)), 2);
        $biggestConfigurableVal = max($simples);
        $biggestConfigurableSku = implode(', ', array_keys($simples, max($simples)));

        return array($avgSimplePerConfig, $biggestConfigurableSku, $biggestConfigurableVal);
    }

    /**
     * somewhat redundant BundleRow and ConfigurableRow - still beta though
     *
     * @return array
     * @see getDataRow
     */
    private function getBundleRow()
    {
        $simples = array();

        Varien_Profiler::start('HEALTHCHECK BUNDLES');

        $resourceModel = Mage::getResourceModel('catalog/product');
        $connection = $resourceModel->getReadConnection();
        $sql = $connection
            ->select()
            ->from(array('cp' => $resourceModel->getTable('catalog/product')))
            ->join(array('cpb' => $resourceModel->getTable('bundle/selection')),
                'cp.entity_id = cpb.parent_product_id',
                array('children_count' => 'count(cpb.parent_product_id)'))
            ->where("type_id = 'bundle'")
            ->group('cp.entity_id');

        $items = $connection->fetchAll($sql);

        if (count($items)) {
            foreach ($items as $bundle) {
                $simples[$bundle['sku']] = 0;
                if (!empty($bundle['children_count'])) {
                    $simples[$bundle['sku']] = $bundle['children_count'];
                }
            }

            Varien_Profiler::stop('HEALTHCHECK BUNDLES');
            return $this->getDataRow($simples);
        } else {
            return false;
        }
    }

    /**
     * somewhat redundant BundleRow and ConfigurableRow - still beta though - event this comment ;)
     *
     * @return array
     * @see getDataRow
     */
    private function getConfigurableRow()
    {
        $simples = array();

        Varien_Profiler::start('HEALTHCHECK CONFIGURABLE');

        $resourceModel = Mage::getResourceModel('catalog/product');
        $connection = $resourceModel->getReadConnection();
        $sql = $connection
            ->select()
            ->from(array('cp' => $resourceModel->getTable('catalog/product')))
            ->join(array('cpc' => $resourceModel->getTable('catalog/product_super_link')),
                'cp.entity_id = cpc.parent_id',
                array('children_count' => 'count(cpc.parent_id)'))
            ->where("type_id = 'configurable'")
            ->group('cp.entity_id');

        $items = $connection->fetchAll($sql);

        if (count($items)) {
            foreach ($items as $configurable) {
                $simples[$configurable['sku']] = 0;
                if (!empty($configurable['children_count'])) {
                    $simples[$configurable['sku']] = $configurable['children_count'];
                }
            }

            Varien_Profiler::stop('HEALTHCHECK CONFIGURABLE');
            return $this->getDataRow($simples);
        } else {
            return false;
        }
    }

    /**
     * Fetches and returns output
     *
     * @return array
     */
    public function getOutput()
    {
        $configurables = $this->getConfigurableRow();
        $bundles = $this->getBundleRow();

        $helper = Mage::helper('magemonitoring');
        $block = $this->newMultiBlock();
        /** @var Hackathon_MageMonitoring_Block_Widget_Multi_Renderer_Table $renderer */
        $renderer = $block->newContentRenderer('table');

        $header = array(
            $helper->__('Avg. connected product count'),
            $helper->__('Most complex product (SKU)'),
            $helper->__('Most simples attached'),
        );

        $renderer->setHeaderRow($header);

        if ($configurables) {
            $renderer->addRow(array('Configurables', 'Configurables', 'Configurables'));
            $renderer->addRow($configurables);
        }

        if ($bundles) {
            $renderer->addRow(array('Bundles', 'Bundles', 'Bundles'));
            $renderer->addRow($bundles);
        }

        if (!$configurables && !$bundles) {
            $noDataText = $helper->__('No data available');
            $renderer->addRow(array($noDataText, $noDataText, $noDataText));
        }

        $this->_output[] = $block;

        return $this->_output;
    }

    /**
     * Returns node name
     */
    protected function _getNodeName()
    {
        // TODO: Implement _getNodeName() method.
    }
}

{'repo_name': 'magento-hackathon/Hackathon_MageMonitoring', 'stars': '136', 'repo_language': 'PHP', 'file_name': 'jquery.jsontotable.js', 'mime_type': 'text/html', 'hash': 1716234673609614357, 'source_dataset': 'data'}


// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.PSharp;

namespace ReplicatingStorage
{
    internal class NodeManager : Machine
    {
        #region events

        /// <summary>
        /// Used to configure the node manager.
        /// </summary>
        public class ConfigureEvent : Event
        {
            public MachineId Environment;
            public int NumberOfReplicas;

            public ConfigureEvent(MachineId env, int numOfReplicas)
                : base()
            {
                this.Environment = env;
                this.NumberOfReplicas = numOfReplicas;
            }
        }

        public class NotifyFailure : Event
        {
            public MachineId Node;

            public NotifyFailure(MachineId node)
                : base()
            {
                this.Node = node;
            }
        }

        internal class ShutDown : Event { }
        private class LocalEvent : Event { }

        #endregion

        #region fields

        /// <summary>
        /// The environment.
        /// </summary>
        private MachineId Environment;

        /// <summary>
        /// The storage nodes.
        /// </summary>
        private List<MachineId> StorageNodes;

        /// <summary>
        /// The number of storage replicas that must
        /// be sustained.
        /// </summary>
        private int NumberOfReplicas;

        /// <summary>
        /// Map from storage node ids to a boolean value that
        /// denotes if the node is alive or not.
        /// </summary>
        private Dictionary<int, bool> StorageNodeMap;

        /// <summary>
        /// Map from storage node ids to data they contain.
        /// </summary>
        private Dictionary<int, int> DataMap;

        /// <summary>
        /// The repair timer.
        /// </summary>
        private MachineId RepairTimer;

        /// <summary>
        /// The client who sent the latest request.
        /// </summary>
        private MachineId Client;

        #endregion

        #region states

        [Start]
        [OnEntry(nameof(EntryOnInit))]
        [OnEventDoAction(typeof(ConfigureEvent), nameof(Configure))]
        [OnEventGotoState(typeof(LocalEvent), typeof(Active))]
        [DeferEvents(typeof(Client.Request), typeof(RepairTimer.TimeoutEvent))]
        class Init : MachineState { }

        void EntryOnInit()
        {
            this.StorageNodes = new List<MachineId>();
            this.StorageNodeMap = new Dictionary<int, bool>();
            this.DataMap = new Dictionary<int, int>();

            this.RepairTimer = this.CreateMachine(typeof(RepairTimer));
            this.Send(this.RepairTimer, new RepairTimer.ConfigureEvent(this.Id));
        }

        void Configure()
        {
            this.Environment = (this.ReceivedEvent as ConfigureEvent).Environment;
            this.NumberOfReplicas = (this.ReceivedEvent as ConfigureEvent).NumberOfReplicas;

            for (int idx = 0; idx < this.NumberOfReplicas; idx++)
            {
                this.CreateNewNode();
            }

            this.Raise(new LocalEvent());
        }

        void CreateNewNode()
        {
            var idx = this.StorageNodes.Count;
            var node = this.CreateMachine(typeof(StorageNode));
            this.StorageNodes.Add(node);
            this.StorageNodeMap.Add(idx, true);
            this.Send(node, new StorageNode.ConfigureEvent(this.Environment, this.Id, idx));
        }

        [OnEventDoAction(typeof(Client.Request), nameof(ProcessClientRequest))]
        [OnEventDoAction(typeof(RepairTimer.TimeoutEvent), nameof(RepairNodes))]
        [OnEventDoAction(typeof(StorageNode.SyncReport), nameof(ProcessSyncReport))]
        [OnEventDoAction(typeof(NotifyFailure), nameof(ProcessFailure))]
        class Active : MachineState { }

        void ProcessClientRequest()
        {
            this.Client = (this.ReceivedEvent as Client.Request).Client;
            var command = (this.ReceivedEvent as Client.Request).Command;

            var aliveNodeIds = this.StorageNodeMap.Where(n => n.Value).Select(n => n.Key);
            foreach (var nodeId in aliveNodeIds)
            {
                this.Send(this.StorageNodes[nodeId], new StorageNode.StoreRequest(command));
            }
        }

        void RepairNodes()
        {
            if (this.DataMap.Count == 0)
            {
                return;
            }

            var latestData = this.DataMap.Values.Max();
            var numOfReplicas = this.DataMap.Count(kvp => kvp.Value == latestData);
            if (numOfReplicas >= this.NumberOfReplicas)
            {
                return;
            }

            foreach (var node in this.DataMap)
            {
                if (node.Value != latestData)
                {
                    this.Logger.WriteLine("\n [NodeManager] repairing storage node {0}.\n", node.Key);
                    this.Send(this.StorageNodes[node.Key], new StorageNode.SyncRequest(latestData));
                    numOfReplicas++;
                }

                if (numOfReplicas == this.NumberOfReplicas)
                {
                    break;
                }
            }
        }

        void ProcessSyncReport()
        {
            var nodeId = (this.ReceivedEvent as StorageNode.SyncReport).NodeId;
            var data = (this.ReceivedEvent as StorageNode.SyncReport).Data;

            // LIVENESS BUG: can fail to ever repair again as it thinks there
            // are enough replicas. Enable to introduce a bug fix.
            //if (!this.StorageNodeMap.ContainsKey(nodeId))
            //{
            //    return;
            //}

            if (!this.DataMap.ContainsKey(nodeId))
            {
                this.DataMap.Add(nodeId, 0);
            }

            this.DataMap[nodeId] = data;
        }

        void ProcessFailure()
        {
            var node = (this.ReceivedEvent as NotifyFailure).Node;
            var nodeId = this.StorageNodes.IndexOf(node);
            this.StorageNodeMap.Remove(nodeId);
            this.DataMap.Remove(nodeId);

            this.Logger.WriteLine("\n [NodeManager] storage node {0} failed.\n", nodeId);

            this.CreateNewNode();
        }

        #endregion
    }
}

{'repo_name': 'p-org/PSharp', 'stars': '370', 'repo_language': 'C#', 'file_name': 'NoMemoryLeakAfterHaltTest.cs', 'mime_type': 'text/plain', 'hash': -7225081978510208367, 'source_dataset': 'data'}


/*
 * Copyright (c) 2002-2020 "Neo4j,"
 * Neo4j Sweden AB [http://neo4j.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.kernel.impl.util.collection;

import org.eclipse.collections.api.iterator.IntIterator;

import java.util.Arrays;
import java.util.concurrent.locks.StampedLock;

/**
 * A basic bitset.
 *

 * Represented using an automatically expanding long array, with one bit per key.
 *

 * Performance:
 * * put, remove, contains, size: O(1)
 * * clear: O(size/64)
 *

 * Concurrency semantics:
 * * Concurrent writes synchronise and is thread-safe
 * * Concurrent reads are thread-safe and will not observe torn writes, but may become
 * out of date as soon as the operation returns
 * * Concurrent reads during write is thread-safe
 * * Bulk operations appear atomic to concurrent readers
 * * Only caveat being that the iterator is not thread-safe
 */
public class SimpleBitSet extends StampedLock
{
    private long lastCheckPointKey;
    private long[] data;

    public SimpleBitSet( int size )
    {
        int initialCapacity = size / 64;
        int capacity = 1;
        while ( capacity < initialCapacity )
        {
            capacity <<= 1;
        }
        long stamp = writeLock();
        data = new long[capacity];
        unlockWrite( stamp );
    }

    public boolean contains( int key )
    {
        int idx = key >>> 6;
        boolean result;
        long stamp;
        do
        {
            stamp = tryOptimisticRead();
            result = data.length > idx && (data[idx] & ((1L << (key & 63)))) != 0;
        }
        while ( !validate( stamp ) );
        return result;
    }

    public void put( int key )
    {
        long stamp = writeLock();
        int idx = key >>> 6;
        ensureCapacity( idx );
        data[idx] = data[idx] | (1L << (key & 63));
        unlockWrite( stamp );
    }

    public void put( SimpleBitSet other )
    {
        long stamp = writeLock();
        ensureCapacity( other.data.length - 1 );
        for ( int i = 0; i < data.length && i < other.data.length; i++ )
        {
            data[i] = data[i] | other.data[i];
        }
        unlockWrite( stamp );
    }

    public void remove( int key )
    {
        long stamp = writeLock();
        int idx = key >>> 6;
        if ( data.length > idx )
        {
            data[idx] = data[idx] & ~(1L << (key & 63));
        }
        unlockWrite( stamp );
    }

    public void remove( SimpleBitSet other )
    {
        long stamp = writeLock();
        for ( int i = 0; i < data.length; i++ )
        {
            data[i] = data[i] & ~other.data[i];
        }
        unlockWrite( stamp );
    }

    public long checkPointAndPut( long checkPoint, int key )
    {
        // We only need to clear the bit set if it was modified since the last check point
        if ( !validate( checkPoint ) || key != lastCheckPointKey )
        {
            long stamp = writeLock();
            int idx = key >>> 6;
            if ( idx < data.length )
            {
                Arrays.fill( data, 0 );
            }
            else
            {
                int len = data.length;
                len = findNewLength( idx, len );
                data = new long[len];
            }
            data[idx] = data[idx] | (1L << (key & 63));
            lastCheckPointKey = key;
            checkPoint = tryConvertToOptimisticRead( stamp );
        }
        return checkPoint;
    }

    private static int findNewLength( int idx, int len )
    {
        while ( len <= idx )
        {
            len *= 2;
        }
        return len;
    }

    public int size()
    {
        int size = 0;
        for ( long s : data )
        {
            size += Long.bitCount( s );
        }
        return size;
    }

    private void ensureCapacity( int arrayIndex )
    {
        data = Arrays.copyOf( data, findNewLength( arrayIndex, data.length ) );
    }

    //
    // Views
    //

    public IntIterator iterator()
    {
        return new IntIterator()
        {
            private int next;
            private final int size = data.length * 64;

            {
                // Prefetch first
                while ( next < size && !contains( next ) )
                {
                    next++;
                }
            }

            @Override
            public boolean hasNext()
            {
                return next < size;
            }

            @Override
            public int next()
            {
                int current = next;
                next++;
                while ( next < size && !contains( next ) )
                {
                    next++;
                }
                return current;
            }
        };
    }
}

{'repo_name': 'neo4j/neo4j', 'stars': '7961', 'repo_language': 'Java', 'file_name': 'checkstyle.xml', 'mime_type': 'text/xml', 'hash': 6600439913477230830, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Filter Include="Quelldateien">
      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
    </Filter>
    <Filter Include="Headerdateien">
      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
    </Filter>
    <Filter Include="Ressourcendateien">
      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
    </Filter>
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="dllmain.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="HTTPAction.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="HTTPClient.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="HTTPFile.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="HTTPProxy.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="HTTPService.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="IndexFiles.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="MIMEType.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="..\stringtools.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
    <ClCompile Include="HTTPSocket.cpp">
      <Filter>Quelldateien</Filter>
    </ClCompile>
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="HTTPAction.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="HTTPClient.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="HTTPFile.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="HTTPProxy.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="HTTPService.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="IndexFiles.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="MIMEType.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="..\stringtools.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
    <ClInclude Include="HTTPSocket.h">
      <Filter>Headerdateien</Filter>
    </ClInclude>
  </ItemGroup>
</Project>

{'repo_name': 'uroni/urbackup_backend', 'stars': '292', 'repo_language': 'C', 'file_name': 'SQLGen.vcxproj.filters', 'mime_type': 'text/xml', 'hash': -8837818262597572190, 'source_dataset': 'data'}


#ifndef _BOOTSECTOR_H
#define _BOOTSECTOR_H

/** @file
 *
 * x86 bootsector image format
 */

FILE_LICENCE ( GPL2_OR_LATER );

extern int call_bootsector ( unsigned int segment, unsigned int offset,
			     unsigned int drive );

#endif /* _BOOTSECTOR_H */

{'repo_name': 'thalium/icebox', 'stars': '373', 'repo_language': 'C++', 'file_name': 'randr.h', 'mime_type': 'text/x-c', 'hash': 4983082329680373041, 'source_dataset': 'data'}


  it('should toggle readonly attr', function() {
    expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
    element(by.model('checked')).click();
    expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  });

{'repo_name': 'angular/code.angularjs.org', 'stars': '152', 'repo_language': 'None', 'file_name': 'bootstrap.js', 'mime_type': 'text/html', 'hash': 4749969876031632188, 'source_dataset': 'data'}


/* pdt.c: OF PROM device tree support code.
 *
 * Paul Mackerras	August 1996.
 * Copyright (C) 1996-2005 Paul Mackerras.
 *
 *  Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner.
 *    {engebret|bergner}@us.ibm.com
 *
 *  Adapted for sparc by David S. Miller davem@davemloft.net
 *  Adapted for multiple architectures by Andres Salomon <dilinger@queued.net>
 *
 *      This program is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU General Public License
 *      as published by the Free Software Foundation; either version
 *      2 of the License, or (at your option) any later version.
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_pdt.h>

static struct of_pdt_ops *of_pdt_prom_ops __initdata;

void __initdata (*of_pdt_build_more)(struct device_node *dp,
		struct device_node ***nextp);

#if defined(CONFIG_SPARC)
unsigned int of_pdt_unique_id __initdata;

#define of_pdt_incr_unique_id(p) do { \
	(p)->unique_id = of_pdt_unique_id++; \
} while (0)

static char * __init of_pdt_build_full_name(struct device_node *dp)
{
	int len, ourlen, plen;
	char *n;

	dp->path_component_name = build_path_component(dp);

	plen = strlen(dp->parent->full_name);
	ourlen = strlen(dp->path_component_name);
	len = ourlen + plen + 2;

	n = prom_early_alloc(len);
	strcpy(n, dp->parent->full_name);
	if (!of_node_is_root(dp->parent)) {
		strcpy(n + plen, "/");
		plen++;
	}
	strcpy(n + plen, dp->path_component_name);

	return n;
}

#else /* CONFIG_SPARC */

static inline void of_pdt_incr_unique_id(void *p) { }
static inline void irq_trans_init(struct device_node *dp) { }

static char * __init of_pdt_build_full_name(struct device_node *dp)
{
	static int failsafe_id = 0; /* for generating unique names on failure */
	char *buf;
	int len;

	if (of_pdt_prom_ops->pkg2path(dp->phandle, NULL, 0, &len))
		goto failsafe;

	buf = prom_early_alloc(len + 1);
	if (of_pdt_prom_ops->pkg2path(dp->phandle, buf, len, &len))
		goto failsafe;
	return buf;

 failsafe:
	buf = prom_early_alloc(strlen(dp->parent->full_name) +
			       strlen(dp->name) + 16);
	sprintf(buf, "%s/%s@unknown%i",
		of_node_is_root(dp->parent) ? "" : dp->parent->full_name,
		dp->name, failsafe_id++);
	pr_err("%s: pkg2path failed; assigning %s\n", __func__, buf);
	return buf;
}

#endif /* !CONFIG_SPARC */

static struct property * __init of_pdt_build_one_prop(phandle node, char *prev,
					       char *special_name,
					       void *special_val,
					       int special_len)
{
	static struct property *tmp = NULL;
	struct property *p;
	int err;

	if (tmp) {
		p = tmp;
		memset(p, 0, sizeof(*p) + 32);
		tmp = NULL;
	} else {
		p = prom_early_alloc(sizeof(struct property) + 32);
		of_pdt_incr_unique_id(p);
	}

	p->name = (char *) (p + 1);
	if (special_name) {
		strcpy(p->name, special_name);
		p->length = special_len;
		p->value = prom_early_alloc(special_len);
		memcpy(p->value, special_val, special_len);
	} else {
		err = of_pdt_prom_ops->nextprop(node, prev, p->name);
		if (err) {
			tmp = p;
			return NULL;
		}
		p->length = of_pdt_prom_ops->getproplen(node, p->name);
		if (p->length <= 0) {
			p->length = 0;
		} else {
			int len;

			p->value = prom_early_alloc(p->length + 1);
			len = of_pdt_prom_ops->getproperty(node, p->name,
					p->value, p->length);
			if (len <= 0)
				p->length = 0;
			((unsigned char *)p->value)[p->length] = '\0';
		}
	}
	return p;
}

static struct property * __init of_pdt_build_prop_list(phandle node)
{
	struct property *head, *tail;

	head = tail = of_pdt_build_one_prop(node, NULL,
				     ".node", &node, sizeof(node));

	tail->next = of_pdt_build_one_prop(node, NULL, NULL, NULL, 0);
	tail = tail->next;
	while(tail) {
		tail->next = of_pdt_build_one_prop(node, tail->name,
					    NULL, NULL, 0);
		tail = tail->next;
	}

	return head;
}

static char * __init of_pdt_get_one_property(phandle node, const char *name)
{
	char *buf = "<NULL>";
	int len;

	len = of_pdt_prom_ops->getproplen(node, name);
	if (len > 0) {
		buf = prom_early_alloc(len);
		len = of_pdt_prom_ops->getproperty(node, name, buf, len);
	}

	return buf;
}

static struct device_node * __init of_pdt_create_node(phandle node,
						    struct device_node *parent)
{
	struct device_node *dp;

	if (!node)
		return NULL;

	dp = prom_early_alloc(sizeof(*dp));
	of_node_init(dp);
	of_pdt_incr_unique_id(dp);
	dp->parent = parent;

	dp->name = of_pdt_get_one_property(node, "name");
	dp->type = of_pdt_get_one_property(node, "device_type");
	dp->phandle = node;

	dp->properties = of_pdt_build_prop_list(node);

	irq_trans_init(dp);

	return dp;
}

static struct device_node * __init of_pdt_build_tree(struct device_node *parent,
						   phandle node,
						   struct device_node ***nextp)
{
	struct device_node *ret = NULL, *prev_sibling = NULL;
	struct device_node *dp;

	while (1) {
		dp = of_pdt_create_node(node, parent);
		if (!dp)
			break;

		if (prev_sibling)
			prev_sibling->sibling = dp;

		if (!ret)
			ret = dp;
		prev_sibling = dp;

		*(*nextp) = dp;
		*nextp = &dp->allnext;

		dp->full_name = of_pdt_build_full_name(dp);

		dp->child = of_pdt_build_tree(dp,
				of_pdt_prom_ops->getchild(node), nextp);

		if (of_pdt_build_more)
			of_pdt_build_more(dp, nextp);

		node = of_pdt_prom_ops->getsibling(node);
	}

	return ret;
}

static void * __init kernel_tree_alloc(u64 size, u64 align)
{
	return prom_early_alloc(size);
}

void __init of_pdt_build_devicetree(phandle root_node, struct of_pdt_ops *ops)
{
	struct device_node **nextp;

	BUG_ON(!ops);
	of_pdt_prom_ops = ops;

	of_allnodes = of_pdt_create_node(root_node, NULL);
#if defined(CONFIG_SPARC)
	of_allnodes->path_component_name = "";
#endif
	of_allnodes->full_name = "/";

	nextp = &of_allnodes->allnext;
	of_allnodes->child = of_pdt_build_tree(of_allnodes,
			of_pdt_prom_ops->getchild(of_allnodes->phandle), &nextp);

	/* Get pointer to "/chosen" and "/aliases" nodes for use everywhere */
	of_alias_scan(kernel_tree_alloc);
}

{'repo_name': 'OnePlusOSS/android_kernel_oneplus_msm8996', 'stars': '133', 'repo_language': 'C', 'file_name': 'mcg.c', 'mime_type': 'text/x-c', 'hash': 4883672771015560354, 'source_dataset': 'data'}


<!DOCTYPE html>

    <title>Functions  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

Collor Docs (0% documented)

View on GitHub

Install in Dash

        Collor Reference

        Functions  Reference

            Classes

                CollectionData

                CollectionDataSource

                CollectionDelegate

                CollectionUpdater

            Extensions

                NSExceptionName

                UICollectionView

            Functions

                bind(collectionView:with:and:and:)

            Protocols

                CollectionAdapter

                CollectionCellAdaptable

                CollectionCellDescribable

                CollectionDidSelectCellDelegate

                CollectionSectionDescribable

                CollectionUserEventDelegate

                Diffable

                Identifiable

            Structs

                CollorDiff

                DecorationViewsHandler

                UpdateCollectionResult

Functions

The following functions are available globally.

                    bind(collectionView:with:and:and:)

Undocumented

© 2017 Voyages-sncf.com. All rights reserved. (Last updated: 2017-11-23)

Generated by jazzy ♪♫ v0.8.3, a Realm project.

{'repo_name': 'voyages-sncf-technologies/Collor', 'stars': '177', 'repo_language': 'Swift', 'file_name': 'CollectionAdapter.swift', 'mime_type': 'text/plain', 'hash': 1708936073299302253, 'source_dataset': 'data'}


msgid ""
msgstr ""
"Project-Id-Version: outwiker\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-08-23 12:51+0300\n"
"PO-Revision-Date: 2018-08-23 13:01+0300\n"
"Last-Translator: Jenyay <jenyay.ilin@gmail.com>\n"
"Language-Team: Swedish\n"
"Language: sv_SE\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: Poedit 2.0.6\n"
"X-Crowdin-Project: outwiker\n"
"X-Crowdin-Language: sv-SE\n"
"X-Crowdin-File: diagrammer.pot\n"

#: controller.py:103 controller.py:104
msgid "Diagrammer"
msgstr "Diagrammer"

#: commanddiagram.py:55
msgid "Diagram parsing error"
msgstr "Diagramtolkningsfel"

#: actions/help.py:23
msgid "Online Help"
msgstr "Online-hjälp"

#: actions/help.py:27
msgid "Diagrammer. Go to blockdiag webpage"
msgstr "Diagrammer. Gå till blockdiagramsida"

#: actions/insertgroup.py:25
msgid "Insert group"
msgstr "Infoga grupp"

#: actions/insertgroup.py:29
msgid "Diagrammer. Insert new group"
msgstr "Diagrammer. Infoga grupp"

#: actions/insertnode.py:25
msgid "Insert node"
msgstr "Infoga nod"

#: actions/insertnode.py:29
msgid "Diagrammer. Insert new node"
msgstr "Diagrammer. Infoga ny nod"

#: actions/insertdiagram.py:26
msgid "Insert diagram"
msgstr "Infoga diagram"

#: actions/insertdiagram.py:30
msgid "Diagrammer. Insert diagram"
msgstr "Diagrammer. Infoga diagram"

#: actions/insertedge.py:55
msgid "Insert edge without any arrow"
msgstr "Infoga kant utan pil"

#: actions/insertedge.py:59
msgid "Diagrammer. Insert edge without any arrow"
msgstr "Diagrammer. Infoga kant utan pil"

#: actions/insertedge.py:79
msgid "Insert edge with the right arrow"
msgstr "Infoga kant med höger pil"

#: actions/insertedge.py:83
msgid "Diagrammer. Insert edge with the right arrow"
msgstr "Diagrammer. Infoga kant med höger pil"

#: actions/insertedge.py:103
msgid "Insert edge with the left arrow"
msgstr "Infoga kant med vänster pil"

#: actions/insertedge.py:107
msgid "Diagrammer. Insert edge with the left arrow"
msgstr "Diagrammer. Infoga kant med vänster pil"

#: actions/insertedge.py:127
msgid "Insert edge with the both arrows"
msgstr "Infoga kant med bägge pilarna"

#: actions/insertedge.py:131
msgid "Diagrammer. Insert edge with the both arrows"
msgstr "Diagrammer. Infoga kant med bägge pilarna"

#: plugin.py:34
msgid "Plugin for the construction of diagrams"
msgstr "Instick för konstruktion av diagram"

#: plugin.py:38
msgid "https://jenyay.net/Outwiker/DiagrammerEn"
msgstr "https://jenyay.net/Outwiker/DiagrammerEn"

#: gui/insertedgedialog.py:23
msgid "Insert edge"
msgstr "Infoga kant"

#: gui/insertedgedialog.py:34 gui/insertnodedialog.py:48
msgid "Options"
msgstr "Alternativ"

#: gui/insertedgedialog.py:50
msgid "First node name"
msgstr "Första nodnamn"

#: gui/insertedgedialog.py:55
msgid "Second node name"
msgstr "Andra nodnamn"

#: gui/insertedgedialog.py:67
msgid "Line style"
msgstr "Linjestil"

#: gui/insertedgedialog.py:71
msgid "Thick line"
msgstr "Tjock linje"

#: gui/insertedgedialog.py:76
msgid "Arrow style"
msgstr "Pilstil"

#: gui/insertedgedialog.py:80
msgid "Set line color"
msgstr "Ange linjefärg"

#: gui/insertedgedialog.py:87 gui/insertgroupdialog.py:44
#: gui/insertnodedialog.py:76
msgid "Label"
msgstr "Etikett"

#: gui/insertedgedialog.py:92 gui/insertnodedialog.py:108
msgid "Set font size"
msgstr "Ange teckenstorlek"

#: gui/insertedgedialog.py:101 gui/insertgroupdialog.py:60
#: gui/insertnodedialog.py:101
msgid "Set text color"
msgstr "Ange teckenfärg"

#: gui/insertedgedialog.py:108
msgid "Folded"
msgstr "Vikt"

#: gui/insertedgedialog.py:114 gui/insertdiagramdialog.py:116
#: gui/insertgroupdialog.py:80 gui/insertnodedialog.py:135
msgid "Open the documentation page"
msgstr "Öppna dokumentationssidan"

#: gui/insertedgedialog.py:159
msgid "Node1"
msgstr "Nod1"

#: gui/insertedgedialog.py:163
msgid "Node2"
msgstr "Nod2"

#: gui/insertdiagramdialog.py:21
msgid "Insert Diagram"
msgstr "Infoga diagram"

#: gui/insertdiagramdialog.py:49 gui/insertgroupdialog.py:49
msgid "Orientation"
msgstr "Orientering"

#: gui/insertdiagramdialog.py:53
msgid "Default nodes shape"
msgstr "Standard nodform"

#: gui/insertdiagramdialog.py:57
msgid "Set default nodes background color"
msgstr "Ange bakgrundsfärg för standardnoder"

#: gui/insertdiagramdialog.py:64
msgid "Set default text color"
msgstr "Ange standardfärg för text"

#: gui/insertdiagramdialog.py:71
msgid "Set default font size"
msgstr "Ange standardstorlek för tecken"

#: gui/insertdiagramdialog.py:80
msgid "Set default nodes width"
msgstr "Ange standardbredd för noder"

#: gui/insertdiagramdialog.py:89
msgid "Set default nodes height"
msgstr "Ange standardhöjd för noder"

#: gui/insertdiagramdialog.py:98
msgid "Set default horizontal span between nodes"
msgstr "Ange horisontellt standardavstånd mellan noder"

#: gui/insertdiagramdialog.py:107
msgid "Set default vertical span between nodes"
msgstr "Ange vertikalt standardavstånd mellan noder"

#: gui/insertgroupdialog.py:18
msgid "Insert Group"
msgstr "Infoga grupp"

#: gui/insertgroupdialog.py:21
msgid "Box"
msgstr "Rektangel"

#: gui/insertgroupdialog.py:22
msgid "Line"
msgstr "Linje"

#: gui/insertgroupdialog.py:39 gui/insertnodedialog.py:67
msgid "Node name"
msgstr "Nodnamn"

#: gui/insertgroupdialog.py:53 gui/insertnodedialog.py:94
msgid "Set background color"
msgstr "Ange bakgrundsfärg"

#: gui/insertgroupdialog.py:67
msgid "Border shape"
msgstr "Kantform"

#: gui/insertgroupdialog.py:76 gui/insertnodedialog.py:90
msgid "Border style"
msgstr "Kantstil"

#: gui/propertyfactory.py:22
msgid "Landscape"
msgstr "Liggande"

#: gui/propertyfactory.py:23
msgid "Portrait"
msgstr "Stående"

#: gui/propertyfactory.py:349 gui/propertyfactory.py:406
#: gui/insertnodedialog.py:35
msgid "Default"
msgstr "Standard"

#: gui/propertyfactory.py:350
msgid "Solid"
msgstr "Solid"

#: gui/propertyfactory.py:351
msgid "Dotted"
msgstr "Prickad"

#: gui/propertyfactory.py:352
msgid "Dashed"
msgstr "Streckad"

#: gui/propertyfactory.py:407
msgid "Generalization"
msgstr "Generalisering"

#: gui/propertyfactory.py:408
msgid "Composition"
msgstr "Komposition"

#: gui/propertyfactory.py:409
msgid "Aggregation"
msgstr "Sammanslagning"

#: gui/insertnodedialog.py:21
msgid "Insert Node"
msgstr "Infoga nod"

#: gui/insertnodedialog.py:81
msgid "Shape"
msgstr "Form"

#: gui/insertnodedialog.py:85
msgid "Stacked"
msgstr "Staplad"

#: gui/insertnodedialog.py:117
msgid "Set width"
msgstr "Ange bredd"

#: gui/insertnodedialog.py:126
msgid "Set height"
msgstr "Ange höjd"

#: gui/insertnodedialog.py:174
msgid "Name of a node can't be empty"
msgstr "Nodnamnet kan inte lämnas tomt"

#~ msgid "http://jenyay.net/Outwiker/DiagrammerEn"
#~ msgstr "http://jenyay.net/Outwiker/DiagrammerEn"

{'repo_name': 'Jenyay/outwiker', 'stars': '184', 'repo_language': 'Python', 'file_name': 'autorenamer.po', 'mime_type': 'text/x-po', 'hash': 8874756266742391911, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: 387ea64048d8f4163b4f7f54e4cd5b3e
timeCreated: 1548702109
licenseType: Pro
TextureImporter:
  fileIDToRecycleName: {}
  externalObjects: {}
  serializedVersion: 4
  mipmaps:
    mipMapMode: 0
    enableMipMap: 1
    sRGBTexture: 1
    linearTexture: 0
    fadeOut: 0
    borderMipMap: 0
    mipMapsPreserveCoverage: 0
    alphaTestReferenceValue: 0.5
    mipMapFadeDistanceStart: 1
    mipMapFadeDistanceEnd: 3
  bumpmap:
    convertToNormalMap: 0
    externalNormalMap: 0
    heightScale: 0.25
    normalMapFilter: 0
  isReadable: 0
  grayScaleToAlpha: 0
  generateCubemap: 6
  cubemapConvolution: 0
  seamlessCubemap: 0
  textureFormat: 1
  maxTextureSize: 2048
  textureSettings:
    serializedVersion: 2
    filterMode: -1
    aniso: -1
    mipBias: -1
    wrapU: -1
    wrapV: -1
    wrapW: -1
  nPOTScale: 1
  lightmap: 0
  compressionQuality: 50
  spriteMode: 0
  spriteExtrude: 1
  spriteMeshType: 1
  alignment: 0
  spritePivot: {x: 0.5, y: 0.5}
  spritePixelsToUnits: 100
  spriteBorder: {x: 0, y: 0, z: 0, w: 0}
  spriteGenerateFallbackPhysicsShape: 1
  alphaUsage: 1
  alphaIsTransparency: 0
  spriteTessellationDetail: -1
  textureType: 0
  textureShape: 1
  maxTextureSizeSet: 0
  compressionQualitySet: 0
  textureFormatSet: 0
  platformSettings:
  - buildTarget: DefaultTexturePlatform
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: -1
    textureCompression: 1
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
  spriteSheet:
    serializedVersion: 2
    sprites: []
    outline: []
    physicsShape: []
  spritePackingTag:
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'mapbox/mapbox-unity-sdk', 'stars': '497', 'repo_language': 'C#', 'file_name': 'toc.yml', 'mime_type': 'text/plain', 'hash': -2682905330266411103, 'source_dataset': 'data'}


angular.module('techNodeApp').directive('autoScrollToBottom', function() {
  return {
    link: function(scope, element, attrs) {
      scope.$watch(
        function() {
          return element.children().length;
        },
        function() {
          element.animate({
            scrollTop: element.prop('scrollHeight')
          }, 1000);
        }
      );
    }
  };
});

{'repo_name': 'island205/technode-tutorial', 'stars': '313', 'repo_language': 'JavaScript', 'file_name': 'technode.bmml', 'mime_type': 'text/plain', 'hash': -8595032984700453366, 'source_dataset': 'data'}


{'repo_name': 'glin/reactable', 'stars': '239', 'repo_language': 'JavaScript', 'file_name': 'reactableLang.Rd', 'mime_type': 'text/plain', 'hash': 5660144879334022686, 'source_dataset': 'data'}