text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/dev/isci/scil/sati_write.c 231689 2012-02-14 15:58:49Z jimharris $");

/**
 * @file
 * @brief This file contains the method implementations required to
 *        translate the SCSI write (6, 10, 12, or 16-byte) commands.
 */

#include <dev/isci/scil/sati_move.h>
#include <dev/isci/scil/sati_write.h>
#include <dev/isci/scil/sati_callbacks.h>
#include <dev/isci/scil/sati_util.h>

#include <dev/isci/scil/intel_ata.h>
#include <dev/isci/scil/intel_scsi.h>

//******************************************************************************
//* P R I V A T E   M E T H O D S
//******************************************************************************

/**
 * @brief This method performs the common translation functionality for
 *        all SCSI write operations that are 10 bytes in size or larger.
 *        Translated/Written items include:
 *        - Force Unit Access (FUA)
 *        - Sector Count/Transfer Length
 *        - Command register
 *
 * @param[in] sector_count This parameter specifies the number of sectors
 *            to be transferred by this request.
 * @param[in] device_head This parameter points to device head register
 *            that is to be written into the ATA task file (register FIS).
 *
 * @return Indicate if the command translation succeeded.
 * @see sati_move_set_sector_count() for additional return values.
 */
static
SATI_STATUS sati_write_large_translate_command(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io,
   U32                          sector_count,
   U8                         * device_head
)
{
   sequence->data_direction = SATI_DATA_DIRECTION_OUT;

   return sati_move_large_translate_command(
             sequence,
             scsi_io,
             ata_io,
             sector_count,
             device_head
          );
}

/**
 * @brief This method performs the common translation functionality for
 *        all SCSI write operations containing a 32-bit logical block
 *        address.
 *        Translated/Written items include:
 *        - Logical Block Address (LBA)
 *        - Force Unit Access (FUA)
 *        - Sector Count/Transfer Length
 *        - Command register
 *        For more information on the parameters passed to this method,
 *        please reference sati_translate_command().
 *
 * @param[in] sector_count This parameter specifies the number of sectors
 *            to be transferred by this request.
 * @param[in] control_byte_offset This parameter specifies the byte offset
 *            into the command descriptor block at which the control byte
 *            is located.
 *
 * @return Indicate if the command translation succeeded.
 * @see sati_move_32_bit_lba_translate_command(), sati_move_set_sector_count()
 *      for additional return values.
 */
static
SATI_STATUS sati_write_32_bit_lba_translate_command(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io,
   U32                          sector_count,
   U8                           control_byte_offset
)
{
   U8           device_head = 0;
   SATI_STATUS  status;

   status = sati_write_large_translate_command(
               sequence, scsi_io, ata_io, sector_count, &device_head
            );

   if (status == SATI_SUCCESS)
   {
      status = sati_move_32_bit_lba_translate_command(
                  sequence, scsi_io, ata_io, device_head
               );
   }

   return status;
}

//******************************************************************************
//* P U B L I C   M E T H O D S
//******************************************************************************

/**
 * @brief This method will translate the SCSI write command into a
 *        corresponding ATA write 6 command.  Depending upon the capabilities
 *        supported by the target different ATA commands can be selected.
 *        For more information on the parameters passed to this method,
 *        please reference sati_translate_command().
 *
 * @return Indicate if the command translation succeeded.
 * @retval SCI_SUCCESS This is returned if the command translation was
 *         successful.
 * @retval SATI_FAILURE_CHECK_RESPONSE_DATA This value is returned if
 *         sense data has been created as a result of something specified
 *         in the CDB.
 */
SATI_STATUS sati_write_6_translate_command(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io
)
{
   if(sati_device_state_stopped(sequence, scsi_io))
   {
      return SATI_FAILURE_CHECK_RESPONSE_DATA;
   }
   else
   {
      sequence->data_direction = SATI_DATA_DIRECTION_OUT;
      sequence->type           = SATI_SEQUENCE_WRITE_6;

      return sati_move_small_translate_command(sequence, scsi_io, ata_io);
   }
}

/**
 * @brief This method will translate the SCSI write 10 command into a
 *        corresponding ATA write command.  Depending upon the capabilities
 *        supported by the target different ATA commands can be selected.
 *        It ensures that all translation required for this command is
 *        performed successfully.
 *        For more information on the parameters passed to this method,
 *        please reference sati_translate_command().
 *
 * @return Indicate if the command translation succeeded.
 * @see sati_write_32_bit_lba_translate_command() for return values.
 */
SATI_STATUS sati_write_10_translate_command(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io
)
{
   U8  * cdb          = sati_cb_get_cdb_address(scsi_io);
   U32   sector_count = (sati_get_cdb_byte(cdb, 7) << 8) |
                        (sati_get_cdb_byte(cdb, 8));

   if(sati_device_state_stopped(sequence, scsi_io))
   {
      return SATI_FAILURE_CHECK_RESPONSE_DATA;
   }
   else
   {
      sequence->type     = SATI_SEQUENCE_WRITE_10;

      return sati_write_32_bit_lba_translate_command(
                sequence, scsi_io, ata_io, sector_count, 9
             );
   }
}

/**
 * @brief This method will translate the SCSI write 12 command into a
 *        corresponding ATA write command.  Depending upon the capabilities
 *        supported by the target different ATA commands can be selected.
 *        It ensures that all translation required for this command is
 *        performed successfully.
 *        For more information on the parameters passed to this method,
 *        please reference sati_translate_command().
 *
 * @return Indicate if the command translation succeeded.
 * @see sati_write_32_bit_lba_translate_command() for return values.
 */
SATI_STATUS sati_write_12_translate_command(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io
)
{
   U8  * cdb          = sati_cb_get_cdb_address(scsi_io);
   U32   sector_count = (sati_get_cdb_byte(cdb, 6) << 24) |
                        (sati_get_cdb_byte(cdb, 7) << 16) |
                        (sati_get_cdb_byte(cdb, 8) << 8)  |
                        (sati_get_cdb_byte(cdb, 9));

   if(sati_device_state_stopped(sequence, scsi_io))
   {
      return SATI_FAILURE_CHECK_RESPONSE_DATA;
   }
   else
   {
      sequence->type = SATI_SEQUENCE_WRITE_12;

      return sati_write_32_bit_lba_translate_command(
                sequence, scsi_io, ata_io, sector_count, 11
             );
   }
}

/**
 * @brief This method will translate the SCSI write 16 command into a
 *        corresponding ATA write command.  Depending upon the capabilities
 *        supported by the target different ATA commands can be selected.
 *        It ensures that all translation required for this command is
 *        performed successfully.
 *        For more information on the parameters passed to this method,
 *        please reference sati_translate_command().
 *
 * @return Indicate if the command translation succeeded.
 * @see sati_write_large_translate_command(), sati_move_translate_64_bit_lba()
 *      for additional return values.
 */
SATI_STATUS sati_write_16_translate_command(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io
)
{
   SATI_STATUS   status;
   U8            device_head  = 0;
   U8          * cdb          = sati_cb_get_cdb_address(scsi_io);
   U32           sector_count = (sati_get_cdb_byte(cdb, 10) << 24) |
                                (sati_get_cdb_byte(cdb, 11) << 16) |
                                (sati_get_cdb_byte(cdb, 12) << 8)  |
                                (sati_get_cdb_byte(cdb, 13));

   if(sati_device_state_stopped(sequence, scsi_io))
   {
      return SATI_FAILURE_CHECK_RESPONSE_DATA;
   }
   else
   {
      sequence->type   = SATI_SEQUENCE_WRITE_16;

      // Translate the sector count, write command register, and check various
      // other parts of the CDB.
      status = sati_write_large_translate_command(
                  sequence, scsi_io, ata_io, sector_count, &device_head
               );

      // Attempt to translate the 64-bit LBA field from the SCSI request
      // into the 48-bits of LBA in the ATA register FIS.
      if (status == SATI_SUCCESS)
      {
         sati_move_translate_command(sequence, scsi_io, ata_io, device_head);
         status = sati_move_translate_64_bit_lba(sequence, scsi_io, ata_io);
      }

      return status;
   }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe "ExtendedDocument attachments" do

  describe "#has_attachment?" do
    before(:each) do
      reset_test_db!
      @obj = Basic.new
      @obj.save.should == true
      @file = File.open(FIXTURE_PATH + '/attachments/test.html')
      @attachment_name = 'my_attachment'
      @obj.create_attachment(:file => @file, :name => @attachment_name)
    end

    it 'should return false if there is no attachment' do
      @obj.has_attachment?('bogus').should be_false
    end

    it 'should return true if there is an attachment' do
      @obj.has_attachment?(@attachment_name).should be_true
    end

    it 'should return true if an object with an attachment is reloaded' do
      @obj.save.should be_true
      reloaded_obj = Basic.get(@obj.id)
      reloaded_obj.has_attachment?(@attachment_name).should be_true
    end

    it 'should return false if an attachment has been removed' do
      @obj.delete_attachment(@attachment_name)
      @obj.has_attachment?(@attachment_name).should be_false
    end
  end

  describe "creating an attachment" do
    before(:each) do
      @obj = Basic.new
      @obj.save.should == true
      @file_ext = File.open(FIXTURE_PATH + '/attachments/test.html')
      @file_no_ext = File.open(FIXTURE_PATH + '/attachments/README')
      @attachment_name = 'my_attachment'
      @content_type = 'media/mp3'
    end

    it "should create an attachment from file with an extension" do
      @obj.create_attachment(:file => @file_ext, :name => @attachment_name)
      @obj.save.should == true
      reloaded_obj = Basic.get(@obj.id)
      reloaded_obj['_attachments'][@attachment_name].should_not be_nil
    end

    it "should create an attachment from file without an extension" do
      @obj.create_attachment(:file => @file_no_ext, :name => @attachment_name)
      @obj.save.should == true
      reloaded_obj = Basic.get(@obj.id)
      reloaded_obj['_attachments'][@attachment_name].should_not be_nil
    end

    it 'should raise ArgumentError if :file is missing' do
      lambda{ @obj.create_attachment(:name => @attachment_name) }.should raise_error
    end

    it 'should raise ArgumentError if :name is missing' do
      lambda{ @obj.create_attachment(:file => @file_ext) }.should raise_error
    end

    it 'should set the content-type if passed' do
      @obj.create_attachment(:file => @file_ext, :name => @attachment_name, :content_type => @content_type)
      @obj['_attachments'][@attachment_name]['content_type'].should == @content_type
    end
  end

  describe 'reading, updating, and deleting an attachment' do
    before(:each) do
      @obj = Basic.new
      @file = File.open(FIXTURE_PATH + '/attachments/test.html')
      @attachment_name = 'my_attachment'
      @obj.create_attachment(:file => @file, :name => @attachment_name)
      @obj.save.should == true
      @file.rewind
      @content_type = 'media/mp3'
    end

    it 'should read an attachment that exists' do
      @obj.read_attachment(@attachment_name).should == @file.read
    end

    it 'should update an attachment that exists' do
      file = File.open(FIXTURE_PATH + '/attachments/README')
      @file.should_not == file
      @obj.update_attachment(:file => file, :name => @attachment_name)
      @obj.save
      reloaded_obj = Basic.get(@obj.id)
      file.rewind
      reloaded_obj.read_attachment(@attachment_name).should_not == @file.read
      reloaded_obj.read_attachment(@attachment_name).should == file.read
    end

    it 'should se the content-type if passed' do
      file = File.open(FIXTURE_PATH + '/attachments/README')
      @file.should_not == file
      @obj.update_attachment(:file => file, :name => @attachment_name, :content_type => @content_type)
      @obj['_attachments'][@attachment_name]['content_type'].should == @content_type
    end

    it 'should delete an attachment that exists' do
      @obj.delete_attachment(@attachment_name)
      @obj.save
      lambda{Basic.get(@obj.id).read_attachment(@attachment_name)}.should raise_error
    end
  end

  describe "#attachment_url" do
    before(:each) do
      @obj = Basic.new
      @file = File.open(FIXTURE_PATH + '/attachments/test.html')
      @attachment_name = 'my_attachment'
      @obj.create_attachment(:file => @file, :name => @attachment_name)
      @obj.save.should == true
    end

    it 'should return nil if attachment does not exist' do
      @obj.attachment_url('bogus').should be_nil
    end

    it 'should return the attachment URL as specified by CouchDB HttpDocumentApi' do
      @obj.attachment_url(@attachment_name).should == "#{Basic.database}/#{@obj.id}/#{@attachment_name}"
    end

    it 'should return the attachment URI' do
      @obj.attachment_uri(@attachment_name).should == "#{Basic.database.uri}/#{@obj.id}/#{@attachment_name}"
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="SettingsTileLabel">
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:gravity">start|center_vertical</item>
        <item name="android:layout_gravity">center_vertical</item>
        <item name="android:layout_margin">4dp</item>
    </style>

    <style name="ProgressDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:background">@android:color/transparent</item>
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowTitleStyle">@null</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
        <item name="android:windowSoftInputMode">stateAlwaysHidden</item>
        <item name="android:backgroundDimEnabled">true</item>
    </style>

    <declare-styleable name="SlidePreferenceAttributes">
        <attr name="android:title" />
        <attr name="android:defaultValue" />
        <attr name="valueStringTemplate" format="reference" />
        <attr name="slideMinimum" format="integer|reference" />
        <attr name="slideMaximum" format="integer|reference" />
    </declare-styleable>

</resources>


text:
package com.zavtech.morpheus.stats;

/**
 * A bi-variate Statistic implementation that supports incremental calculation of a sample covariance.
 *
 *
This is open source software released under the Apache 2.0 License

 *
 * @author  Xavier Witdouck
 */
public class Covariance implements Statistic2 {

    private long n;
    private double sxy;
    private double sumX;
    private double sumY;

    /**
     * Constructor
     */
    public Covariance() {
        super();
    }

    @Override
    public long getN() {
        return n;
    }

    @Override
    public double getValue() {
        return sxy / (n-1d);
    }

    @Override
    public StatType getType() {
        return StatType.COVARIANCE;
    }

    @Override
    public long add(double value1, double value2) {
        if (n == 0) {
            this.sumX = value1;
            this.sumY = value2;
            this.n++;
        } else {
            this.sumX += value1;
            this.sxy += (value1 - sumX/(n+1d))*(value2 - sumY/n);
            this.sumY += value2;
            this.n++;
        }
        return n;
    }

    @Override
    public Statistic2 copy() {
        try {
            return (Statistic2)super.clone();
        } catch (CloneNotSupportedException ex) {
            throw new RuntimeException("Failed to clone statistic", ex);
        }
    }

    @Override
    public Statistic2 reset() {
        this.n = 0L;
        this.sxy = 0d;
        this.sumX = 0d;
        this.sumY = 0d;
        return this;
    }
}


text:
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Hosting;

namespace Frapid.Messaging
{
    public static class DisposableEmailValidator
    {
        /// <summary>
        ///     Checks if an email address belongs to a disposable email domain
        /// </summary>
        public static bool IsDisposableEmail(string tenant, string email)
        {
            string configPath;

            //The file should be a plain text file which contains the list of dispoable email domains separated by new line.
            //The file is expected to be present on either of these two paths:
            string tenantConfigFile = HostingEnvironment.MapPath($"/Tenants/{tenant}/Configs/DisposableEmailDomains.config");
            string rootConfigFile = HostingEnvironment.MapPath("/Resources/Configs/DisposableEmailDomains.config");

            if (File.Exists(tenantConfigFile))
            {
                configPath = tenantConfigFile;
            }
            else
            {
                configPath = File.Exists(rootConfigFile) ? rootConfigFile : string.Empty;
            }

            if (string.IsNullOrWhiteSpace(configPath))
            {
                //Cannot determine if the email address is disposable because no configuration file was found.
                return false;
            }

            string contents = File.ReadAllText(configPath, Encoding.UTF8);
            var domains = contents.Split
                (
                    new[]
                    {
                        "\r\n",
                        "\n"
                    },
                    StringSplitOptions.None).Select(x => x.ToUpperInvariant().Trim());
            return domains.Any(domain => email.Trim().ToUpperInvariant().EndsWith(domain.ToUpperInvariant()));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Mef;

namespace OmniSharp.Models
{
    [OmniSharpEndpoint(OmnisharpEndpoints.Close, typeof(FileCloseRequest), typeof(FileCloseResponse))]
    public class FileCloseRequest : Request { }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2022 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<resources>
  <string name="character_counter_content_description">Унети знакови: %1$d од %2$d</string>
  <string name="character_counter_overflowed_content_description">Прекорачено је ограничење броја знакова: %1$d од %2$d</string>
  <string name="password_toggle_content_description">Прикажи лозинку</string>
  <string name="clear_text_end_icon_content_description">Обриши текст</string>
  <string name="exposed_dropdown_menu_content_description">Прикажи падајући мени</string>
  <string name="error_icon_content_description">Грешка</string>
</resources>


text:
define('mousetrap', 'lib/mousetrap.js');

define('mod/chat', [
    'jquery',
    'jquery-atwho',
    'jquery-forms',
    'mod/connect',
    'mod/user_avatar',
    'mod/input-ext',
    'mousetrap',
    'bootbox'
], function ($, _, _, connectNode, loadAvatar, inputExt) {
    $(function () {
        var ajaxGet = function (url, nowMessageId) {
            $.ajax({type: "GET",
                    url: url,
                    dataType: "json",
                    success: function (data) {
                        if (data.r === 0) {
                             $(".alert-error").show();
                             location.hash = '#lobby';
                             return;
                        }

                        var messages = data.msg;
                        for (var i = 0; i < messages.length; i++) {
                            nowMessageId.append(messages[i]);
                        }
                        loadAvatar();
                        var $d = nowMessageId;
                        $d[0].scrollTop = $d[0].scrollHeight;
                        $('#message_input').focus();
                    }
            });
        };

        var roomName = "lobby";
        if (location.hash.slice(1)) {
            roomName = location.hash.slice(1);
        }
        var channelPrefix = "chat:room:";
        var roomChannel = channelPrefix + roomName;
        var io = connectNode(roomChannel);
        io.on('announce', function(data) {
            var channel = data.channel;
            var room = channel.split(':')[2];
            $('#'+room).append(data.send_message);
            loadAvatar();
            var $d= $('#'+room);
            $d[0].scrollTop = $d[0].scrollHeight;
        });
        var sliceUrl = '#' + roomName;
        var lastActive = $('[href=' + sliceUrl + ']').parents('li');
        lastActive.attr("class", "active");
        var lastMessageId = $("#"+roomName);
        var nowMessageId = $("#"+roomName);
        lastMessageId.hide();
        nowMessageId.show();
        nowMessageId.html('');

        var urlPrefix = "/j/chat/";
        var url = urlPrefix + roomName;
        $('#message-form').attr('action', url);
        ajaxGet(url, nowMessageId);

        $(window).on('hashchange',function(){
            roomName = location.hash.slice(1);
            sliceUrl = '#' + roomName;
            var needActive = $('[href='+sliceUrl+']').parents('li');
            lastActive.attr("class", "");
            needActive.attr("class", "active");
            lastActive = needActive;

            url = urlPrefix + roomName;
            $('#message-form').attr('action', url);
            lastMessageId.hide();
            nowMessageId = $('#'+roomName);
            nowMessageId.show();
            nowMessageId.html('');
            lastMessageId = nowMessageId;

            ajaxGet(url, nowMessageId);

            roomChannel = channelPrefix + roomName;
            io.emit('ready', {channel:roomChannel});
        });

        $('#message_input').focus();
        var messageInput = $('textarea#message_input');
        inputExt.shortcut2submit(messageInput);
        inputExt.enableEmojiInput(messageInput);
        $('#message-form').ajaxForm({
            dataType: 'json',
            success: function(r) {
                if (r.r === 1) {
                    $('#message_input').val('');
                    $('#message_input').focus();
                    $('#message_input').closest('form').removeClass('submitting');
                }
            }
        });

        $('.del-room').on('click', function () {
            var roomName = $(this).attr("data-name"),
                roomItem = $(this),
                msg = '你确定要删除room: ' + roomName + '?';

            if (roomName) {
                bootbox.confirm(msg, function(confirmed) {
                    if (confirmed) {
                        $.post(urlPrefix + 'delete_room', {'room_name': roomName},
                               function (ret) {
                                   if (ret.r === 1) {
                                        var li = roomItem.parents('li');
                                        li.remove();
                                   }
                               },
                               'json'
                               );
                    }
                });
            }
        });
    });
});


text:
package com.intellij.codeInspection.javaDoc;

import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.daemon.impl.quickfix.ImportClassFix;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.FQNameCellRenderer;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.psi.util.proximity.PsiProximityComparator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.*;

public class JavaDocReferenceInspection extends LocalInspectionTool {
  private static final String SHORT_NAME = "JavadocReference";

  @SuppressWarnings("WeakerAccess")
  public boolean REPORT_INACCESSIBLE = true;

  @Nullable
  @Override
  public JComponent createOptionsPanel() {
    return new SingleCheckboxOptionsPanel(
      InspectionsBundle.message("html.report.inaccessible.symbols"), this, "REPORT_INACCESSIBLE");
  }

  private static LocalQuickFix createAddQualifierFix(PsiJavaCodeReferenceElement reference) {
    List<PsiClass> classesToImport = new ImportClassFix(reference).getClassesToImport();
    return classesToImport.isEmpty() ? null : new AddQualifierFix(classesToImport);
  }

  private static RenameReferenceQuickFix createRenameReferenceQuickFix(Set<String> unboundParams) {
    return new RenameReferenceQuickFix(unboundParams);
  }

  private String getResolveErrorMessage(@NotNull PsiReference reference,
                                        PsiElement resolved,
                                        @NotNull PsiElement context,
                                        CharSequence referenceText) {
    if (resolved == null && reference instanceof PsiPolyVariantReference) {
      return getResolveErrorMessage(((PsiPolyVariantReference)reference).multiResolve(false), context, referenceText);
    }

    return getResolveErrorMessage(resolved, context, referenceText);
  }

  private String getResolveErrorMessage(ResolveResult @NotNull [] resolveResults, @NotNull PsiElement context, CharSequence referenceText) {
    if (resolveResults.length == 0) {
      return InspectionsBundle.message("inspection.javadoc.problem.cannot.resolve", "" + referenceText + "");
    }

    boolean allAccessible = !REPORT_INACCESSIBLE ||
                            Arrays.stream(resolveResults).map(ResolveResult::getElement)
                              .filter(Objects::nonNull)
                              .allMatch(element -> isAccessible(element, context));

    return allAccessible ? null :
           InspectionsBundle.message("inspection.javadoc.problem.inaccessible", "" + referenceText + "");
  }

  private String getResolveErrorMessage(PsiElement resolved, @NotNull PsiElement context, CharSequence referenceText) {
    if (resolved == null) {
      return InspectionsBundle.message("inspection.javadoc.problem.cannot.resolve", "" + referenceText + "");
    }

    if (REPORT_INACCESSIBLE && !isAccessible(resolved, context)) {
      return InspectionsBundle.message("inspection.javadoc.problem.inaccessible", "" + referenceText + "");
    }

    return null;
  }

  private static boolean isAccessible(@NotNull PsiElement resolved, @NotNull PsiElement context) {
    if (!(resolved instanceof PsiMember)) {
      return true;
    }
    if (!PsiResolveHelper.SERVICE.getInstance(resolved.getProject()).isAccessible((PsiMember)resolved, context, null)) {
      return false;
    }
    VirtualFile file = PsiUtilCore.getVirtualFile(resolved);
    return file == null || context.getResolveScope().contains(file);
  }

  private void visitRefInDocTag(PsiDocTag tag, JavadocManager manager, PsiElement context, ProblemsHolder holder, boolean isOnTheFly) {
    PsiDocTagValue value = tag.getValueElement();
    if (value == null) return;

    String tagName = tag.getName();
    JavadocTagInfo info = manager.getTagInfo(tagName);
    if (info != null && !info.isValidInContext(context)) return;

    if (info != null && info.isInline()) {
      String message = info.checkTagValue(value);
      if (message != null) {
        holder.registerProblem(holder.getManager().createProblemDescriptor(value, message, isOnTheFly, null,
                                                                           ProblemHighlightType.LIKE_UNKNOWN_SYMBOL));
      }
    }

    PsiReference reference = value.getReference();
    if (reference == null) return;
    PsiElement element = reference.resolve();

    int textOffset = value.getTextOffset();
    if (textOffset == value.getTextRange().getEndOffset()) return;
    PsiDocTagValue valueElement = tag.getValueElement();
    if (valueElement == null) return;
    CharSequence paramName = value.getContainingFile().getViewProvider().getContents().subSequence(textOffset, value.getTextRange().getEndOffset());

    String message = getResolveErrorMessage(reference, element, context, paramName);
    if (message == null) {
      return;
    }

    List<LocalQuickFix> fixes = new ArrayList<>();
    if (isOnTheFly && "param".equals(tagName)) {
      PsiDocCommentOwner commentOwner = PsiTreeUtil.getParentOfType(tag, PsiDocCommentOwner.class);
      if (commentOwner instanceof PsiMethod) {
        PsiMethod method = (PsiMethod)commentOwner;
        PsiParameter[] parameters = method.getParameterList().getParameters();
        PsiDocTag[] tags = tag.getContainingComment().getTags();
        Set<String> unboundParams = new HashSet<>();
        for (PsiParameter parameter : parameters) {
          if (!JavadocHighlightUtil.hasTagForParameter(tags, parameter)) {
            unboundParams.add(parameter.getName());
          }
        }
        if (!unboundParams.isEmpty()) {
          fixes.add(createRenameReferenceQuickFix(unboundParams));
        }
      }
    }
    fixes.add(new RemoveTagFix(tagName, paramName));

    holder.registerProblem(holder.getManager().createProblemDescriptor(valueElement, reference.getRangeInElement(), message,
                                                                       ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, isOnTheFly, fixes.toArray(LocalQuickFix.EMPTY_ARRAY)));
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @NotNull
  @Override
  public String getGroupDisplayName() {
    return InspectionsBundle.message("group.names.javadoc.issues");
  }

  @NotNull
  @Override
  public String getShortName() {
    return SHORT_NAME;
  }

  @NotNull
  @Override
  public HighlightDisplayLevel getDefaultLevel() {
    return HighlightDisplayLevel.ERROR;
  }

  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
    return new JavaElementVisitor() {
      @Override
      public void visitJavaFile(PsiJavaFile file) {
        if (PsiPackage.PACKAGE_INFO_FILE.equals(file.getName())) {
          checkComment(PsiTreeUtil.getChildOfType(file, PsiDocComment.class), file, holder, isOnTheFly);
        }
      }

      @Override
      public void visitModule(PsiJavaModule module) {
        checkComment(module.getDocComment(), module, holder, isOnTheFly);
      }

      @Override
      public void visitClass(PsiClass aClass) {
        checkComment(aClass.getDocComment(), aClass, holder, isOnTheFly);
      }

      @Override
      public void visitField(PsiField field) {
        checkComment(field.getDocComment(), field, holder, isOnTheFly);
      }

      @Override
      public void visitMethod(PsiMethod method) {
        checkComment(method.getDocComment(), method, holder, isOnTheFly);
      }
    };
  }

  private void checkComment(PsiDocComment comment, @NotNull PsiElement context, ProblemsHolder holder, boolean isOnTheFly) {
    if (comment == null) return;

    JavadocManager javadocManager = JavadocManager.SERVICE.getInstance(holder.getProject());
    comment.accept(new JavaElementVisitor() {
      @Override
      public void visitReferenceExpression(PsiReferenceExpression expression) {
        visitElement(expression);
      }

      @Override
      public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
        super.visitReferenceElement(reference);
        JavaResolveResult result = reference.advancedResolve(false);
        PsiElement resolved = result.getElement();
        String message = getResolveErrorMessage(resolved, context, reference.getText());
        if (message != null && !result.isPackagePrefixPackageReference()) {
          PsiElement referenceNameElement = reference.getReferenceNameElement();
          PsiElement element = referenceNameElement != null ? referenceNameElement : reference;

          LocalQuickFix fix = isOnTheFly ? createAddQualifierFix(reference) : null;
          holder.registerProblem(holder.getManager().createProblemDescriptor(element, message, fix,
                                                                             ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, isOnTheFly));
        }
      }

      @Override
      public void visitDocTag(PsiDocTag tag) {
        super.visitDocTag(tag);
        JavadocTagInfo info = javadocManager.getTagInfo(tag.getName());
        if (info == null || !info.isInline()) {
          visitRefInDocTag(tag, javadocManager, context, holder, isOnTheFly);
        }
      }

      @Override
      public void visitInlineDocTag(PsiInlineDocTag tag) {
        super.visitInlineDocTag(tag);
        visitRefInDocTag(tag, javadocManager, context, holder, isOnTheFly);
      }

      @Override
      public void visitElement(@NotNull PsiElement element) {
        for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
          child.accept(this);
        }
      }
    });
  }

  private static class RenameReferenceQuickFix implements LocalQuickFix {
    private final Set<String> myUnboundParams;

    RenameReferenceQuickFix(Set<String> unboundParams) {
      myUnboundParams = unboundParams;
    }

    @Override
    @NotNull
    public String getFamilyName() {
      return InspectionsBundle.message("change.to");
    }

    @Override
    public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
      DataManager.getInstance().getDataContextFromFocusAsync()
                 .onSuccess(dataContext -> {
                   final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
                   assert editor != null;
                   final TextRange textRange = ((ProblemDescriptorBase)descriptor).getTextRange();
                   editor.getSelectionModel().setSelection(textRange.getStartOffset(), textRange.getEndOffset());

                   final String word = editor.getSelectionModel().getSelectedText();

                   if (word == null || StringUtil.isEmptyOrSpaces(word)) {
                     return;
                   }
                   final List<LookupElement> items = new ArrayList<>();
                   for (String variant : myUnboundParams) {
                     items.add(LookupElementBuilder.create(variant));
                   }
                   LookupManager.getInstance(project).showLookup(editor, items.toArray(LookupElement.EMPTY_ARRAY));
                 });
    }
  }

  private static class AddQualifierFix implements LocalQuickFix {
    private final List<? extends PsiClass> originalClasses;

    AddQualifierFix(final List<? extends PsiClass> originalClasses) {
      this.originalClasses = originalClasses;
    }

    @Override
    @NotNull
    public String getFamilyName() {
      return QuickFixBundle.message("add.qualifier");
    }

    @Override
    public boolean startInWriteAction() {
      return false;
    }

    @Override
    public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
      PsiJavaCodeReferenceElement element = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiJavaCodeReferenceElement.class);
      if (element != null) {
        Collections.sort(originalClasses, new PsiProximityComparator(element.getElement()));
        DataManager.getInstance()
                   .getDataContextFromFocusAsync()
                   .onSuccess(dataContext ->
          JBPopupFactory.getInstance()
            .createPopupChooserBuilder(originalClasses)
            .setTitle(QuickFixBundle.message("add.qualifier.original.class.chooser.title"))
            .setItemChosenCallback(psiClass -> {
              if (!element.isValid()) return;
              WriteCommandAction.writeCommandAction(project, element.getContainingFile()).run(() -> {
                if (psiClass.isValid()) {
                  PsiDocumentManager.getInstance(project).commitAllDocuments();
                  element.bindToElement(psiClass);
                }
              });
            })
            .setRenderer(new FQNameCellRenderer())
            .createPopup()
            .showInBestPositionFor(dataContext));
      }
    }
  }

  private static class RemoveTagFix implements LocalQuickFix {
    private final String myTagName;
    private final CharSequence myParamName;

    RemoveTagFix(String tagName, CharSequence paramName) {
      myTagName = tagName;
      myParamName = paramName;
    }

    @NotNull
    @Override
    public String getName() {
      return InspectionsBundle.message("remove.0.1", myTagName, myParamName);
    }

    @NotNull
    @Override
    public String getFamilyName() {
      return InspectionsBundle.message("remove.tag");
    }

    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      PsiDocTag myTag = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiDocTag.class);
      if (myTag != null) {
        myTag.delete();
      }
    }
  }
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.compositor.bottombar.contextualsearch;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.view.ViewGroup;

import org.chromium.base.MathUtils;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.compositor.animation.CompositorAnimator;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelAnimation;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelInflater;
import org.chromium.ui.resources.dynamics.DynamicResourceLoader;

/**
 * Controls the Search Bar Banner.
 */
public class ContextualSearchBarBannerControl extends OverlayPanelInflater {
    /**
     * The initial width of the ripple for the appearance animation, in dps.
     */
    private static final float RIPPLE_MINIMUM_WIDTH_DP = 56.f;

    /**
     * Whether the Bar Banner is visible.
     */
    private boolean mIsVisible;

    /**
     * Whether the Bar Banner is in the process of hiding.
     */
    private boolean mIsHiding;

    /**
     * The height of the Bar Banner, in pixels.
     */
    private float mHeightPx;

    /**
     * The width of the Ripple resource in pixels.
     */
    private float mRippleWidthPx;

    /**
     * The opacity of the Ripple resource.
     */
    private float mRippleOpacity;

    /**
     * The opacity of the Text View dynamic resource.
     */
    private float mTextOpacity;

    /**
     * The precomputed padding of the Bar Banner, in pixels.
     */
    private final float mPaddingPx;

    /**
     * The padded height of the Bar Banner in pixels. Set to zero initially, calculated on the first
     * call.
     */
    private float mPaddedHeightPx;

    /**
     * The precomputed minimum width of the Ripple resource in pixels.
     */
    private final float mRippleMinimumWidthPx;

    /**
     * The precomputed maximum width of the Ripple resource in pixels.
     */
    private float mRippleMaximumWidthPx;

    /**
     * @param panel             The panel.
     * @param context           The Android Context used to inflate the View.
     * @param container         The container View used to inflate the View.
     * @param resourceLoader    The resource loader that will handle the snapshot capturing.
     */
    public ContextualSearchBarBannerControl(OverlayPanel panel, Context context,
            ViewGroup container, DynamicResourceLoader resourceLoader) {
        super(panel, R.layout.contextual_search_bar_banner_text_view,
                R.id.contextual_search_bar_banner_text_view, context, container, resourceLoader);

        final float dpToPx = context.getResources().getDisplayMetrics().density;

        mPaddingPx = context.getResources().getDimensionPixelOffset(
                R.dimen.contextual_search_bar_banner_padding);

        mRippleMinimumWidthPx = RIPPLE_MINIMUM_WIDTH_DP * dpToPx;
        mRippleMaximumWidthPx = panel.getMaximumWidthPx();
    }

    /**
     * Shows the Bar Banner. This includes inflating the View and setting it to its initial state.
     * This also means a new cc::Layer will be created and added to the tree.
     */
    void show() {
        if (mIsVisible) return;

        mIsVisible = true;
        mHeightPx = Math.round(getPaddedHeightPx());

        invalidate();
    }

    /**
     * Hides the Bar Banner, returning the Control to its initial uninitialized state. In this
     * state, now View will be created and no Layer added to the tree (or removed if present).
     */
    void hide() {
        if (!mIsVisible) return;

        if (mHeightPx == 0.f) {
            mIsVisible = false;
        } else {
            animateDisappearance();
        }
    }

    /**
     * @return The height of the Bar Banner when the Panel is the peeked state.
     */
    float getHeightPeekingPx() {
        return (!isVisible() || mIsHiding) ? 0.f : getPaddedHeightPx();
    }

    /** Calculates the padded height of the bar banner if it has not been calculated before.
     * @return The padded height of the Bar Banner.
     */
    private float getPaddedHeightPx() {
        if (mPaddedHeightPx == 0.f) {
            // Calculate the padded height based on the measured height of the TextView.
            inflate();
            layout();
            mPaddedHeightPx = getMeasuredHeight() + (2 * mPaddingPx);
        }
        return mPaddedHeightPx;
    }

    // ============================================================================================
    // Custom Behaviors
    // ============================================================================================

    void onResized(ContextualSearchPanel panel) {
        mRippleMaximumWidthPx = panel.getMaximumWidthPx();

        // In the rare condition that size is changed mid-animation, e.g. the device orientation is
        // changed, mRippleWidthPx will be updated by the CompositorAnimator and will grow to the
        // new mRippleMaximumWidthPx by the end of animation.
        mRippleWidthPx = mRippleMaximumWidthPx;
    }

    // ============================================================================================
    // Public API
    // ============================================================================================

    /**
     * @return Whether the Bar Banner is visible.
     */
    public boolean isVisible() {
        return mIsVisible;
    }

    /**
     * @return The Bar Banner height in pixels.
     */
    public float getHeightPx() {
        return mHeightPx;
    }

    /**
     * @return The Bar Banner padding in pixels.
     */
    public float getPaddingPx() {
        return mPaddingPx;
    }

    /**
     * @return The width of the Ripple resource in pixels.
     */
    public float getRippleWidthPx() {
        return mRippleWidthPx;
    }

    /**
     * @return The opacity of the Ripple resource.
     */
    public float getRippleOpacity() {
        return mRippleOpacity;
    }

    /**
     * @return The opacity of the Text View dynamic resource.
     */
    public float getTextOpacity() {
        return mTextOpacity;
    }

    // ============================================================================================
    // Panel Animation
    // ============================================================================================

    /**
     * Interpolates the UI from states Closed to Peeked.
     *
     * @param percentage The completion percentage.
     */
    public void onUpdateFromCloseToPeek(float percentage) {
        if (!isVisible() || mIsHiding) return;

        mHeightPx = Math.round(getPaddedHeightPx());
    }

    /**
     * Interpolates the UI from states Peeked to Expanded.
     *
     * @param percentage The completion percentage.
     */
    public void onUpdateFromPeekToExpand(float percentage) {
        if (!isVisible() || mIsHiding) return;

        mHeightPx = Math.round(MathUtils.interpolate(getPaddedHeightPx(), 0.f, percentage));
        mTextOpacity = MathUtils.interpolate(1.f, 0.f, percentage);
    }

    /**
     * Interpolates the UI from states Expanded to Maximized.
     *
     * @param percentage The completion percentage.
     */
    public void onUpdateFromExpandToMaximize(float percentage) {
        if (!isVisible() || mIsHiding) return;

        mHeightPx = 0.f;
        mTextOpacity = 0.f;
    }

    // ============================================================================================
    // Bar Banner Appearance Animation
    // ============================================================================================

    /**
     * Animates the Bar Banner appearance.
     */
    public void animateAppearance() {
        CompositorAnimator rippleWidth = CompositorAnimator.ofFloat(
                mOverlayPanel.getAnimationHandler(), mRippleMinimumWidthPx, mRippleMaximumWidthPx,
                OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS,
                animator -> { mRippleWidthPx = animator.getAnimatedValue(); });
        CompositorAnimator rippleOpacity =
                CompositorAnimator.ofFloat(mOverlayPanel.getAnimationHandler(), 0.f, 1.f,
                        OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS,
                        animator -> { mRippleOpacity = animator.getAnimatedValue(); });
        CompositorAnimator textOpacity =
                CompositorAnimator.ofFloat(mOverlayPanel.getAnimationHandler(), 0.f, 1.f,
                        OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS / 2,
                        animator -> { mTextOpacity = animator.getAnimatedValue(); });
        textOpacity.setStartDelay(OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS / 2);

        rippleWidth.start();
        rippleOpacity.start();
        textOpacity.start();
    }

    /**
     * Animates the Bar Banner disappearance.
     */
    private void animateDisappearance() {
        mIsHiding = true;
        CompositorAnimator disappearance =
                CompositorAnimator.ofFloat(mOverlayPanel.getAnimationHandler(), getPaddedHeightPx(),
                        0.f, OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS, null);
        disappearance.addUpdateListener(animator -> {
            if (isVisible()) {
                mHeightPx = animator.getAnimatedValue();
            }
        });
        disappearance.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mHeightPx = 0.f;
                mIsHiding = false;
                hide();
            }
        });
        disappearance.start();
    }
}


text:
import BuiCheckboxModule from './buiCheckbox';
import BuiCheckboxController from './buiCheckbox.controller';
import BuiCheckboxComponent from './buiCheckbox.component';
import BuiCheckboxTemplate from './buiCheckbox.html';

describe('BuiCheckbox', () => {
  let $rootScope, makeController;

  beforeEach(window.module(BuiCheckboxModule));
  beforeEach(inject((_$rootScope_) => {
    $rootScope = _$rootScope_;
    makeController = () => {
      return new BuiCheckboxController();
    };
  }));

  describe('Module', () => {
    // top-level specs: i.e., routes, injection, naming
  });

  describe('Controller', () => {
    // controller specs
    it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller
      let controller = makeController();
      expect(controller).to.have.property('name');
    });
  });

  describe('Template', () => {
    // template specs
    // tip: use regex to ensure correct bindings are used e.g., {{  }}
    it('has name in template [REMOVE]', () => {
      expect(BuiCheckboxTemplate).to.match(/{{\s?\$ctrl\.name\s?}}/g);
    });
  });

  describe('Component', () => {
    // component/directive specs
    let component = BuiCheckboxComponent;

    it('includes the intended template', () => {
      expect(component.template).to.equal(BuiCheckboxTemplate);
    });

    it('invokes the right controller', () => {
      expect(component.controller).to.equal(BuiCheckboxController);
    });
  });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Botryosporium leucostachys Zopf

### Remarks
null


text:
"""Test a pre-segwit node upgrading to segwit consensus"""

from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
    softfork_active,
)

class SegwitUpgradeTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 1
        self.extra_args = [["-segwitheight=10"]]

    def run_test(self):
        """A pre-segwit node with insufficiently validated blocks needs to redownload blocks"""

        self.log.info("Testing upgrade behaviour for pre-segwit node to segwit rules")
        node = self.nodes[0]

        # Node hasn't been used or connected yet
        assert_equal(node.getblockcount(), 0)

        assert not softfork_active(node, "segwit")

        # Generate 8 blocks without witness data
        node.generate(8)
        assert_equal(node.getblockcount(), 8)

        self.stop_node(0)
        # Restarting the node (with segwit activation height set to 5) should result in a shutdown
        # because the blockchain consists of 3 insufficiently validated blocks per segwit consensus rules.
        node.assert_start_raises_init_error(
                extra_args=["-segwitheight=5"],
                expected_msg=": Witness data for blocks after height 5 requires validation. Please restart with -reindex..\nPlease restart with -reindex or -reindex-chainstate to recover.")

        # As directed, the user restarts the node with -reindex
        self.start_node(0, extra_args=["-reindex", "-segwitheight=5"])

        # With the segwit consensus rules, the node is able to validate only up to block 4
        assert_equal(node.getblockcount(), 4)

        # The upgraded node should now have segwit activated
        assert softfork_active(node, "segwit")

if __name__ == '__main__':
    SegwitUpgradeTest().main()


text:
// TypeScript Version: 2.0

/**
* Returns a list of US state capitals in alphabetical order according to state name.
*
* ## Notes
*
* -   This function synchronously reads data from disk for each invocation. Such behavior is intentional and so is the avoidance of `require`. We assume that invocations are infrequent, and we want to avoid the `require` cache. This means that we allow data to be garbage collected and a user is responsible for explicitly caching data.
*
*
* @throws unable to read data
* @returns capitals
*
* @example
* var data = capitals();
* // returns [ 'Montgomery', 'Juneau', 'Phoenix', 'Little Rock', ... ]
*/
declare function capitals(): Array<string>;

// EXPORTS //

export = capitals;


text:
+++
hook = "A simple pattern for tracing requests across a service-oriented architecture by injecting a UUID into the events that they produce."
location = "San Francisco"
published_at = 2013-06-02T17:21:43Z
title = "Tracing Request IDs"
+++

Log into Heroku's [Dashboard](https://dashboard.heroku.com) and you'll hit three different components that work together to usher you in and show you an app list, run a `git push heroku master` and that number is more like six. These kinds of service-oriented patterns produce all kinds of logistical benefits, but debugging such a system at production scale can get messy.

It's key to have powerful techniques at your disposable to gain introspection and track down bugs in your production system. A simple one that's tremendously useful even on its own, is the use of request IDs to trace requests as they thread themselves through a set of composed components.

## Request IDs (#request-ids)

A very lightweight alternative to something like [Twitter's Zipkin](http://engineering.twitter.com/2012/06/distributed-systems-tracing-with-zipkin.html), and based on the same ideas as the [troubleshooting technique that Amazon uses for route 53](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResponseHeader_RequestID.html), request IDs are a way of grouping all the information associated with a given request, even as that request makes its way across a distributed architecture. The benefits are two-fold:

* Provides a tagging mechanism for events that are produced, so that a full report of what occurred and timing in every component touched can be generated.
* Exposes an identifier to users, both internal and external, which can be used to track down specific issues that they're running into.

In practice, the request ID is a UUID that's generated at the beginning of a request and stored for its duration. Here's a simple Rack middleware that does this job:

``` ruby
class Middleware::Instruments
  def initialize(app)
    @app = app
  end

  def call(env)
    env["REQUEST_ID"] = SecureRandom.uuid
    @app.call(env)
  end
end
```

Logging events in the main app include this identifier in their associated data. A sample helper for Sinatra might look like:

``` ruby
def log(action, data={})
  data.merge!(request_id: request.env["REQUEST_ID"])
  ...
end
```

And with everything done right, a request emits a nice logging stream with each event tagged with the generated request ID:

```
app=api authenticate elapsed=0.001 request_id=9d5ccdbe-6a5c-4da7-8762-8fb627a020a4
app=api rate_limit elapsed=0.001 request_id=9d5ccdbe-6a5c-4da7-8762-8fb627a020a4
app=api provision_token elapsed=0.003 request_id=9d5ccdbe-6a5c-4da7-8762-8fb627a020a4
app=api serialize elapsed=0.000 request_id=9d5ccdbe-6a5c-4da7-8762-8fb627a020a4
app=api response status=201 elapsed=0.005 request_id=9d5ccdbe-6a5c-4da7-8762-8fb627a020a4
```

Our apps are all configured to drain their log streams to Splunk, which provides a centralized location that allows us to query for all information associated with a given request ID:

```
9d5ccdbe-6a5c-4da7-8762-8fb627a020a4
```

## Heroku's request IDs (#heroku)

Heroku's routing layer can [generate a request ID](https://devcenter.heroku.com/articles/http-request-id) automatically, which allows platform-generated logging events to be tagged in as well. Rather than generating them yourself, these IDs can be accessed through an incoming header:

``` ruby
def log(action, data={})
  data.merge!(request_id: request.env["HTTP_HEROKU_REQUEST_ID"])
  ...
end
```

## Composing request IDs (#composition)

Request IDs provide a convenient mechanism for digging into a single request for any given app, but so far they're not much help when it comes to a number of composed apps that are constantly making calls to each other.

We take the concept a step further by having apps that make calls to other apps inject their own request ID via a request header.

``` ruby
api = Excon.new("https://api.heroku.com", headers: {
  "Request-ID" => request.env["REQUEST_ID"]
})
api.post("/oauth/tokens", expects: 201)
```

The callee in turn accepts a request ID, and if it looks like a valid identifier, tags all its requests with the given request ID _as well as_ one that it generates itself. This way we can make sure that a request across many apps can be tracked as a group, but each app always has a way of tracking every one of its requests invidually.

``` ruby
def call(env)
  env["REQUEST_ID"] = SecureRandom.uuid
  if env["HTTP_REQUEST_ID"] =~ UUID_PATTERN
    env["REQUEST_ID"] += "," + env["HTTP_REQUEST_ID"]
  end
  @app.call(env)
end
```

The event stream emitted by the composed apps is now tagged based on all generated request IDs:

```
app=id session_check elapsed=0.000 request_id=4edef22b...
app=api authenticate elapsed=0.001 request_id=9d5ccdbe...,4edef22b...
app=api rate_limit elapsed=0.001 request_id=9d5ccdbe...,4edef22b...
app=api provision_token elapsed=0.003 request_id=9d5ccdbe...,4edef22b...
app=api serialize elapsed=0.000 request_id=9d5ccdbe...,4edef22b...
app=api response status=201 elapsed=0.005 request_id=9d5ccdbe...,4edef22b...
app=id response status=200 elapsed=0.010 request_id=4edef22b...
```

A Splunk query based on the top-level request ID will yield logging events from all composed apps. Note that although we use Splunk here, alternatives like Papertrail will do the same job.

{{Figure "Getting ready to search Splunk for a request ID." (ImgSrcAndAltAndClass "/assets/images/request-ids/splunk-search.png" "Getting ready to search Splunk for a request ID." "overflowing")}}

## Tweaks (#tweaks)

### Inject any number of request IDs (#multiple)

A minor modification to the middleware pattern above will allow any number of request IDs to be injected into a given app, so that a request can be traced across three or more composed services.

``` ruby
def call(env)
  env["REQUEST_ID"] = SecureRandom.uuid
  if env["HTTP_REQUEST_ID"]
    request_ids = env["HTTP_REQUEST_ID"].split(",").
      select { |id| id =~ UUID_PATTERN }
    env["REQUEST_ID"] = (env["REQUEST_ID"] + request_ids).join(",")
  end
  @app.call(env)
end
```

### Respond with request ID (#response)

The request ID can be returned as a response header to enable easier identification and subsequent debugging of any given request:

``` ruby
def call(env)
  request_id = SecureRandom.uuid
  ...
  status, headers, response = @app.call(env)
  headers["Request-ID"] = request_id
  [status, headers, response]
end
```

```
curl -i https://api.example.com/hello
...
Request-ID: 9d5ccdbe-6a5c-4da7-8762-8fb627a020a4
...
```

Heroku's new [V3 platform API](https://devcenter.heroku.com/articles/platform-api-reference#request-id) includes a request ID in the response with every request.

### Storing request ID in a request store (#storage)

In a larger application, producing logs from a context-sensitive method like a Sinatra helper may be architecturally difficult. In cases like this, a thread-safe request store pattern can be used instead.

``` ruby
# request store that keys a hash to the current thread
module RequestStore
  def self.store
    Thread.current[:request_store] ||= {}
  end
end

# middleware that initializes a request store and and adds a request ID to it
class Middleware::Instruments
  ...

  def call(env)
    RequestStore.store.clear
    RequestStore.store[:request_id] = SecureRandom.uuid
    @app.call(env)
  end
end

# class method that can extract a request ID and tag logging events with it
module Log
  def self.log(action, data={})
    data.merge!(request_id: RequestStore.store[:request_id])
    ...
  end
end
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using DebugEngine.Interfaces;

namespace DebugEngine
{
    class TempFuncEval
    {
        internal static AutoResetEvent mEvent = new AutoResetEvent(false);
        internal static ICorDebugValue value = null;
    }
}


text:
.. _pylewenstein:

pylewenstein.py
---------------

.. highlight:: python

Description
~~~~~~~~~~~

This module is not part of the Matlab/Octave framework.

It allows you to compute single atom dipole responses in Python by exposing a low-level interface to the Lewenstein model implemented in C++.

Overview
~~~~~~~~

The module provides three functions and one class, namely:

- :ref:`get_weights <pylewenstein-get-weights>` produces weights vectors used as argument to the ``lewenstein`` function.
- :ref:`sau_convert <pylewenstein-sau-convert>` converts between SI units and scaled atomic units.
- :ref:`lewenstein <pylewenstein-lewenstein>` computes dipole responses.
- :ref:`dipole_elements_H <pylewenstein-elements>` represents dipole elements derived from a hydrogen-like atomic potential.

.. _pylewenstein-lewenstein:

The ``lewenstein`` function
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``lewenstein`` function computes the time-dependent dipole vector given a time-dependent electric field vector, using the Lewenstein model. It supports 1-, 2- or 3-dimensional field vectors and accounts for ground state depletion. Its signature is

::

    def lewenstein(t,Et,ip,wavelength=None,weights=None,at=None,dipole_elements=None,epsilon_t=1e-4)

The return value ``d[C,t_i]`` is an array that contains the time-dependent dipole moment, where the first index gives the component of the dipole moment vector and the second index gives the time (corresponding to the argument t). The arguments are:

-  ``t`` is the time axis. The array must be equally spaced.

-  ``Et[C,t_i]`` is the time-dependent electric driving field. The first index gives the component of the electric
   field vector, so that you can pass elliptically polarized driving
   fields. The second index is for time (corresponding to the
   argument ``t``).

-  ``ip`` is the ionization potential :math:`I_p` of the used model atom.

-  ``wavelength`` (optional) is the wavelength of the driving field in SI units, i.e. meters. If omitted, all others arguments are assumed to be in scaled atomic units,
   and the return value is also in scaled atomic units. If provided, all other arguments and the return value are in SI units.

-  ``weights`` (optional) is a one-dimensional array specifying the
   window function :math:`w(\tau)` of the integral over :math:`\tau` in the Lewenstein formula.
   The corresponding :math:`\tau` axis is given by the ``t`` argument (shifted accordingly to start at zero). If the length of the weights
   vector is shorter than the ``t`` vector, the remaining values are assumed to be zero.
   If omitted, weights are generated that are one over one complete driving field period and then go softly to zero over half a driving field period, which includes both the short and the long trajectory.

-  ``at`` (optional) is a vector specifying the
   time-dependent ground state amplitude, which is used to account for
   ground state depletion. The vector must be of the same length as the ``t`` argument.
   If omitted, ground state depletion is neglected.

-  ``dipole_elements`` (optional) are the bound-continuum dipole matrix
   elements :math:`\vect D(\vect v)`. To get dipole matrix elements for a scaled
   hydrogen-like potential, use the ``dipole_elements_H`` class.
   If omitted, an instance of this class with appropriate value for ``ip`` is created on the fly.

-  ``epsilon_t`` (optional) is a small positive constant that
   is used to prevent the integral over :math:`\tau` in the Lewenstein formula from diverging at :math:`\tau=0`, in
   scaled atomic units (even if wavelength argument is provided). The default value is :math:`10^{-4}`.

.. _pylewenstein-get-weights:

The ``get_weights`` function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``get_weights`` function computes weight functions :math:`w(\tau)` which are :math:`1` over a certain :math:`\tau` interval and then go to zero following a :math:`\cos^2` function, for use as argument for the :ref:`lewenstein <pylewenstein-lewenstein>` function. Its signature is

::

    def get_weights(tau,T=2*np.pi,periods_one=1,periods_soft=.5)

The return value ``w[t_i]`` is an array of weights, where the index gives the time (corresponding to the argument t). Its length is in general shorter than the length of the ``tau`` argument. The arguments are:

-  ``tau`` is the :math:`\tau` axis. The array must be equally spaced, and you can use arbitrary units but must use the same unit as for the ``T`` argument.

-  ``T`` (optional) is the oscillation period of the driving field. If omitted, it is set to :math:`2\pi` (one period in scaled atomic units), so in this case the ``tau`` argument must also be in scaled atomic units.

-  ``periods_one`` is the length of the :math:`\tau` interval over which :math:`w(\tau)=1`, in driving field oscillation periods.

-  ``periods_soft`` is the length of the :math:`\tau` interval over which :math:`w(\tau)` follows a falling :math:`\cos^2` window, in driving field oscillation periods.

.. _pylewenstein-sau-convert:

The ``sau_convert`` function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``sau_convert`` function converts between SI and scaled atomic units. Its signature is::

    def sau_convert(value, quantity, target, wavelength)

The return value is the converted value. The arguments are:

-  ``value`` is the value that should be converted, in SI units if ``target=='SAU'`` or in scaled atomic units if ``target=='SI'``.

-  ``quantity`` is the physical quantity as a string. Supported values are ``'t'`` (time), ``'omega'`` (angular frequency), ``'U'`` (energy), ``'q'`` (charge), ``'s'`` (length), ``'E'`` (electric field), ``'d'`` (dipole moment), ``'m'`` (mass), and ``'p'`` (momentum).

-  ``target`` specifies the direction of the conversion. If ``target=='SAU'``, ``value`` is converted from SI units to scaled atomic units, if ``target=='SI'`` vice versa.

-  ``wavelength`` is the driving field wavelength in SI units, i.e. meters, which is needed for the conversion.

.. _pylewenstein-elements:

The ``dipole_elements_H`` class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``dipole_elements_H`` function represents dipole matrix elements derived from a hydrogen-like atomic potential. A instance of this class can be used as the ``dipole_elements`` argument of the :ref:`lewenstein <pylewenstein-lewenstein>` function. Its constructor's signature is::

    def __init__(self, dims, ip, wavelength=None)

The class does not expose any public methods or properties. The arguments of the constructor are:

-  ``dims`` is the number of dimensions of the electric field vector. Must be :math:`1`, :math:`2` or :math:`3`.

-  ``ip`` gives the ionization potential to which the atomic potential should be scaled.

-  ``wavelength`` (optional) is the wavelength of the driving field in SI units, i.e. meters. If omitted, the ``ip`` argument is assumed to be in scaled atomic units. If provided, it is assumed to be in SI units.


text:
var stack = require("../../")
  , connect = require("connect");

module.exports = function(config) {
  if (!config) config = {};

  // Create a pack
  var pack = stack();

  // Add some default middleware
  pack.use(connect.favicon());
  pack.use(connect.directory(config.static || __dirname));

  // Return the pack
  return pack;
};


text:
<?php

namespace Xtendsys;

class PrestoException extends \Exception {

}

?>


text:
package com.all.shared.model.constraints;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.ConstraintPayload;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@Documented
@Size(max = 15, min = 0)
@Pattern(regexp = "[a-zA-Z0-9-_\\.@]*")
@ReportAsSingleViolation
@Constraint(validatedBy = ZipCode.ZipCodeValidator.class)
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface ZipCode {

	String message() default "{constraint.zipcode.invalid}";

	Class<?>[] groups() default {};

	Class<? extends ConstraintPayload>[] payload() default {};

	class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {

		@Override
		public void initialize(ZipCode constraintAnnotation) {
		}

		@Override
		public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
			return true;
		}

	}

}


text:
<?php

namespace App\Modules\Partners\Http\Controllers;

use App\Modules\Partners\Partner;
use App\Modules\Partners\PartnerCat;
use View;
use Widget;

class PartnersWidget extends Widget
{

    public function render(array $parameters = []) : string
    {
        if (isset($parameters['categoryId'])) {
            $categoryId = $parameters['categoryId'];
        } else {
            $partnerCat = PartnerCat::first();
            if ($partnerCat) {
                $categoryId = $partnerCat->id;
            } else {
                $categoryId = 0;
            }
        }

        $partners = Partner::wherePartnerCatId($categoryId)->published()->orderBy('position', 'ASC')->get();

        return View::make('partners::widget', compact('partners'))->render();
    }

}


text:
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Routing;
using R4Mvc;
using AspNetSimple;

namespace AspNetSimple.Controllers
{
    public partial class HomeController
    {
        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public HomeController()
        {
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected HomeController(Dummy d)
        {
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(IActionResult result)
        {
            var callInfo = result.GetR4ActionResult();
            return RedirectToRoute(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(Task<IActionResult> taskResult)
        {
            return RedirectToAction(taskResult.Result);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(IActionResult result)
        {
            var callInfo = result.GetR4ActionResult();
            return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(Task<IActionResult> taskResult)
        {
            return RedirectToActionPermanent(taskResult.Result);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToPage(IActionResult result)
        {
            var callInfo = result.GetR4ActionResult();
            return RedirectToRoute(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToPage(Task<IActionResult> taskResult)
        {
            return RedirectToPage(taskResult.Result);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToPagePermanent(IActionResult result)
        {
            var callInfo = result.GetR4ActionResult();
            return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToPagePermanent(Task<IActionResult> taskResult)
        {
            return RedirectToPagePermanent(taskResult.Result);
        }

        [NonAction]
        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public virtual IActionResult Error()
        {
            return new R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult(Area, Name, ActionNames.Error);
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public HomeController Actions => MVC.Home;
        [GeneratedCode("R4Mvc", "1.0")]
        public readonly string Area = "";
        [GeneratedCode("R4Mvc", "1.0")]
        public readonly string Name = "Home";
        [GeneratedCode("R4Mvc", "1.0")]
        public const string NameConst = "Home";
        [GeneratedCode("R4Mvc", "1.0")]
        static readonly ActionNamesClass s_ActionNames = new ActionNamesClass();
        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public ActionNamesClass ActionNames => s_ActionNames;
        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public class ActionNamesClass
        {
            public readonly string Index = "Index";
            public readonly string About = "About";
            public readonly string Contact = "Contact";
            public readonly string Error = "Error";
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public class ActionNameConstants
        {
            public const string Index = "Index";
            public const string About = "About";
            public const string Contact = "Contact";
            public const string Error = "Error";
        }

        [GeneratedCode("R4Mvc", "1.0")]
        static readonly ActionParamsClass_Error s_ErrorParams = new ActionParamsClass_Error();
        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public ActionParamsClass_Error ErrorParams => s_ErrorParams;
        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public class ActionParamsClass_Error
        {
            public readonly string statusCode = "errorCode";
        }

        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public class ViewsClass
        {
            static readonly _ViewNamesClass s_ViewNames = new _ViewNamesClass();
            public _ViewNamesClass ViewNames => s_ViewNames;
            public class _ViewNamesClass
            {
                public readonly string About = "About";
                public readonly string Contact = "Contact";
                public readonly string Index = "Index";
            }

            public readonly string About = "~/Views/Home/About.cshtml";
            public readonly string Contact = "~/Views/Home/Contact.cshtml";
            public readonly string Index = "~/Views/Home/Index.cshtml";
        }

        [GeneratedCode("R4Mvc", "1.0")]
        static readonly ViewsClass s_Views = new ViewsClass();
        [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
        public ViewsClass Views => s_Views;
    }

    [GeneratedCode("R4Mvc", "1.0"), DebuggerNonUserCode]
    public partial class R4MVC_HomeController : AspNetSimple.Controllers.HomeController
    {
        public R4MVC_HomeController(): base(Dummy.Instance)
        {
        }

        [NonAction]
        partial void IndexOverride(R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult callInfo);
        [NonAction]
        public override Microsoft.AspNetCore.Mvc.IActionResult Index()
        {
            var callInfo = new R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult(Area, Name, ActionNames.Index);
            IndexOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void AboutOverride(R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult callInfo);
        [NonAction]
        public override Microsoft.AspNetCore.Mvc.IActionResult About()
        {
            var callInfo = new R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult(Area, Name, ActionNames.About);
            AboutOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void ContactOverride(R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult callInfo);
        [NonAction]
        public override Microsoft.AspNetCore.Mvc.IActionResult Contact()
        {
            var callInfo = new R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult(Area, Name, ActionNames.Contact);
            ContactOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void ErrorOverride(R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult callInfo, int statusCode);
        [NonAction]
        public override Microsoft.AspNetCore.Mvc.IActionResult Error(int statusCode)
        {
            var callInfo = new R4Mvc_Microsoft_AspNetCore_Mvc_ActionResult(Area, Name, ActionNames.Error);
            ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "errorCode", statusCode);
            ErrorOverride(callInfo, statusCode);
            return callInfo;
        }
    }
}
#pragma warning restore 1591, 3008, 3009, 0108


text:
<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!-- 填充的颜色 -->
    <solid android:color="@color/white"/>
    <!-- 设置按钮的四个角为弧形 -->
    <!-- android:radius 弧形的半径 -->

    <corners
        android:bottomLeftRadius="5dp"
        android:topLeftRadius="5dp"
        android:bottomRightRadius="5dp"
        android:topRightRadius="5dp"
        />
    <!-- padding: Button 里面的文字与Button边界的间隔 -->
    <stroke android:color="@color/DarkGray"
           android:width="1dp"
        />

</shape>


text:
				コンポーネント・アクション・メニュー

${title}

${loading}

			<a aria-haspopup="true" aria-label="メニューの表示" role="button" href="javascript:;" class="wpthemeIcon wpthemeActionDisabled wpthemeMenuFocus" tabindex="0"
                onclick="if (typeof wptheme != 'undefined') wptheme.contextMenu.init({ 'node': this, menuId: 'skinAction', jsonQuery: {'navID':ibmCfg.portalConfig.currentPageOID,'windowID':wptheme.getWindowIDFromSkin(this)}, params: {'alignment':'right'}});"
				onmousemove="javascript:if (typeof i$ != 'undefined' && typeof wptheme != 'undefined') { i$.removeClass(this,'wpthemeActionDisabled'); this.onmousemove = null; }"
				onkeydown="javascript:if (typeof i$ != 'undefined' && typeof wptheme != 'undefined') {if (event.keyCode ==13 || event.keyCode ==32 || event.keyCode==38 || event.keyCode ==40) {wptheme.contextMenu.init(this, 'skinAction', {'navID':ibmCfg.portalConfig.currentPageOID,'windowID':wptheme.getWindowIDFromSkin(this)}); return false;}}">

				アクション


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2014-present Open Networking Foundation
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.onosproject</groupId>
        <artifactId>onlab-utils</artifactId>
        <version>1.10.11-SNAPSHOT</version>
    </parent>

    <artifactId>onlab-junit</artifactId>
    <packaging>bundle</packaging>

    <description>ON.Lab JUnit test utilities</description>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava-testlib</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>


text:
pub struct Status {
    pcdata: String
}


text:
<?php

// autoload_namespaces.php generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
    'Guzzle\\Tests' => array($vendorDir . '/guzzle/guzzle/tests'),
    'Guzzle' => array($vendorDir . '/guzzle/guzzle/src'),
);


text:
<?php

namespace Tygh\StoreImport\Pro;
use Tygh\StoreImport\General;
use Tygh\Registry;

class F306Tult
{
    protected $store_data = array();
    protected $main_sql_filename = 'F306Tult.sql';

    public function __construct($store_data)
    {
        $store_data['product_edition'] = 'PROFESSIONAL';
        $this->store_data = $store_data;
    }

    public function import($db_already_cloned)
    {
        General::setProgressTitle(__CLASS__);
        if (!$db_already_cloned) {
            if (!General::cloneImportedDB($this->store_data)) {
                return false;
            }
        } else {
            General::setEmptyProgressBar(__('importing_data'));
            General::setEmptyProgressBar(__('importing_data'));
        }

        General::connectToOriginalDB(array('table_prefix' => General::formatPrefix()));

        $default_company = General::getDefaultCompany();

        $supplier_settings = $this->getSupplierSettings();
        General::setSupplierSettings($supplier_settings);
        $enabledSuppliers = General::supplierSettings('enabled') ? true : false;

        $main_sql = Registry::get('config.dir.addons') . 'store_import/database/' . $this->main_sql_filename;
        if (is_file($main_sql)) {
            //Process main sql
            if (!db_import_sql_file($main_sql)) {
                return false;
            }
        }

        if ($enabledSuppliers) {
            $this->_importSuppliers();
        }

        General::processAddons($this->store_data, __CLASS__);

        General::setEmptyProgressBar();
        $this->_deleteAllCompanies();
        $default_company_id = (int) General::createDefaultCompany($default_company);
        $this->_fillSharingTable($default_company_id);
        $this->_updateCompanyId($default_company_id);
        $this->_setStorefromUrl($default_company_id, $this->store_data);

        General::setEmptyProgressBar();

        return true;
    }

    protected function _importSuppliers()
    {
        $suppliers = array();
        $shippings = array();

        db_query("CREATE TABLE `?:suppliers` (
                `supplier_id` mediumint(8) UNSIGNED NOT NULL auto_increment,
                `company_id` int(11) unsigned NOT NULL,
                `name` varchar(255),
                `address` varchar(255) NOT NULL,
                `city` varchar(64) NOT NULL,
                `state` varchar(32) NOT NULL,
                `country` char(2) NOT NULL,
                `zipcode` varchar(16) NOT NULL,
                `email` varchar(128) NOT NULL,
                `phone` varchar(32) NOT NULL,
                `fax` varchar(32) NOT NULL,
                `url` varchar(128) NOT NULL,
                `timestamp` int(11) unsigned NOT NULL DEFAULT '0',
                `status` char(1) NOT NULL default 'A',
                PRIMARY KEY  (`supplier_id`),
                KEY `company` (`company_id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=UTF8");

        db_query("CREATE TABLE `?:supplier_links` (
                `supplier_id` mediumint(8) UNSIGNED NOT NULL,
                `object_id` int(11) UNSIGNED NOT NULL,
                `object_type` char(1),
                PRIMARY KEY  (`supplier_id`, `object_id`, `object_type`)
            ) ENGINE=MyISAM DEFAULT CHARSET=UTF8");

        $companies = db_get_array("SELECT * FROM ?:companies");

        if (!empty($companies)) {
            foreach ($companies as $company) {
                $suppliers[] = array(
                    'supplier_id' => $company['company_id'],
                    'company_id' => 0,
                    'name' => $company['company'],
                    'address' => $company['address'],
                    'city' => $company['city'],
                    'state' => $company['state'],
                    'country' => $company['country'],
                    'zipcode' => $company['zipcode'],
                    'email' => $company['email'],
                    'phone' => $company['phone'],
                    'fax' => $company['fax'],
                    'url' => $company['url'],
                    'timestamp' => $company['timestamp'],
                    'status' => $company['status']
                );

                $shippings[$company['company_id']] = explode(',', $company['shippings']);
            }

            db_query("INSERT INTO ?:suppliers ?m", $suppliers);

            db_query("INSERT INTO ?:supplier_links SELECT company_id as supplier_id, product_id as object_id, 'P' as object_type FROM ?:products WHERE company_id > 0");
            db_query("INSERT INTO ?:supplier_links SELECT company_id as supplier_id, shipping_id as object_id, 'S' as object_type FROM ?:shippings WHERE company_id > 0");

            foreach ($shippings as $supplier_id => $shipping_ids) {
                db_query("INSERT INTO ?:supplier_links SELECT ?i as supplier_id, shipping_id as object_id, 'S' as object_type FROM ?:shippings WHERE company_id = 0 AND shipping_id IN (?a)", $supplier_id, $shipping_ids);
            }
        }
    }

    protected function _deleteAllCompanies()
    {
        db_query("TRUNCATE TABLE ?:companies");

        return true;
    }

    protected function _updateCompanyId($default_company_id)
    {
        $prefix = General::formatPrefix();

        $tables = db_get_fields(
            "SELECT TABLE_NAME "
            . "FROM INFORMATION_SCHEMA.COLUMNS "
            . "WHERE TABLE_SCHEMA = ?s AND COLUMN_NAME = ?s AND TABLE_NAME LIKE ?s",
            Registry::get('config.db_name'), 'company_id', $prefix . '%'
        );

        foreach ($tables as $table_name) {
            if ($table_name !== $prefix . 'users') {
                db_query("UPDATE `?p` SET `company_id` = ?i", $table_name, $default_company_id);
            } else {
                db_query("UPDATE `?p` SET `company_id` = ?i WHERE `user_type` <> 'A' OR `is_root` <> 'Y'", $table_name, $default_company_id);
            }
        }

        $count_product_orders = db_get_field("SELECT COUNT(*) FROM ?:order_details");

        if ($count_product_orders > 0) {
            for ($i = 0; $i <= floor($count_product_orders/50); $i++) {
                $products = db_get_array("SELECT item_id, order_id, extra FROM ?:order_details LIMIT ?i, ?i", $i * 50, 50);

                if (is_array($products)) {
                    foreach ($products as $product) {
                        $extra = unserialize($product['extra']);
                        if (!empty($extra['company_id'])) {
                            $extra['supplier_id'] = $extra['company_id'];
                        }
                        $extra['company_id'] = $default_company_id;
                        $product['extra'] = serialize($extra);
                        db_query("UPDATE ?:order_details SET extra = ?s WHERE item_id = ?i AND order_id = ?i", $product['extra'], $product['item_id'], $product['order_id']);
                    }
                }
            }
        }

        //Hack for the root admin.
        db_query("UPDATE ?:users SET company_id = 0 WHERE user_type = 'A' AND is_root = 'Y'");

        $common_descriptions_objects = array(
            'Customer_logo',
            'Admin_logo',
            'Gift_certificate_logo',
            'Mail_logo',
            'Signin_logo'
        );

        //Suppliers create several unnesessary records during creation. We should remove them
        db_query("DELETE FROM ?:common_descriptions WHERE object_holder IN (?a) AND object_id <> 0", $common_descriptions_objects);
        db_query("UPDATE ?:common_descriptions SET object_id = ?i WHERE object_holder IN (?a)", $default_company_id,  $common_descriptions_objects);
    }

    protected function _fillSharingTable($default_company_id)
    {
        $objects = array(
            'shippings' => 'shipping_id',
            'payments' => 'payment_id',
            'languages' => 'lang_code',
            'currencies' => 'currency_code',
            'promotions' => 'promotion_id',
            'pages' => 'page_id',
            'product_features' => 'feature_id',
            'product_filters' => 'filter_id',
            'profile_fields' => 'field_id',
            'usergroups' => 'usergroup_id',
            'static_data' => 'param_id',
        );

        if (General::supplierSettings('enabled')) {
            $objects['suppliers'] = 'supplier_id';
        }

        //Process addons sharing data
        //We do not include form buider and polls because 'pages' object included in the common objects list
        $addons_objects = array(
            'banners' => array(
                'banners' => 'banner_id',
            ),
            'news_and_emails' => array(
                'mailing_lists' => 'list_id',
                'news' => 'news_id',
            ),
            'store_locator' => array(
                'store_locations' => 'store_location_id',
            ),
        );
        $addons = General::getInstalledAddons();
        foreach ($addons_objects as $addon => $data) {
            if (in_array($addon, $addons)) {
                $objects = fn_array_merge($data, $objects);
            }
        }

        foreach ($objects as $object => $field) {
            db_query("REPLACE INTO ?:ult_objects_sharing (share_company_id, share_object_id, share_object_type) SELECT '$default_company_id', $field, '$object' FROM ?:$object");
        }

        db_query("REPLACE INTO ?:ult_objects_sharing (share_company_id, share_object_id, share_object_type) SELECT '$default_company_id', option_id, 'product_options' FROM ?:product_options WHERE product_id IN (SELECT DISTINCT product_id FROM ?:ult_product_descriptions)");
        db_query("REPLACE INTO ?:ult_objects_sharing (share_company_id, share_object_id, share_object_type) SELECT '$default_company_id', option_id, 'product_options' FROM ?:product_options");

        return true;
    }

    protected function getSupplierSettings()
    {
        $supplier_settings['enabled'] = db_get_field("SELECT value FROM ?:settings_objects WHERE name = 'enable_suppliers'");
        $supplier_settings['display_supplier'] = db_get_field("SELECT value FROM ?:settings_objects WHERE name = 'display_supplier'");
        $supplier_settings['display_shipping_methods_separately'] = db_get_field("SELECT value FROM ?:settings_objects WHERE name = 'display_shipping_methods_separately'");

        return $supplier_settings;
    }

    protected function _setStorefromUrl($company_id, $store_data)
    {
        General::connectToOriginalDB(array('table_prefix' => General::formatPrefix()));
        db_query("UPDATE ?:companies SET storefront = ?s, secure_storefront = ?s WHERE company_id = ?i", $store_data['new_storefront_url'], $store_data['new_secure_storefront_url'], $company_id);

        return true;
    }
}


text:
@interface WYQMyConnectionsViewController ()
{
    int viewFlag;
}
@end

@implementation WYQMyConnectionsViewController
@synthesize headerV;
@synthesize dataDelegateCircleArray;
@synthesize dataTableView;
@synthesize dataRecommendCircleArray;
@synthesize dataServiceCircleArray;
@synthesize numberLab;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    viewFlag=100;//默认是推荐圈

    self.headerV.titleLab.text=@"我的人脉";
    [headerV.backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    self.dataRecommendCircleArray=@[[NSDictionary dictionaryWithObjects:@[@"一代",@"100"] forKeys:@[@"name",@"num"]],[NSDictionary dictionaryWithObjects:@[@"二代",@"200"] forKeys:@[@"name",@"num"]],[NSDictionary dictionaryWithObjects:@[@"三代",@"300"] forKeys:@[@"name",@"num"]]];
}
-(void)backBtnClick:(UIButton *)btn //返回按钮点击
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma UITableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(viewFlag==100)
    {
        return self.dataRecommendCircleArray.count;
    }
    return 10;//[dataArray count];//arrays是你所定义的数据存储数组
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(viewFlag==100)
    {
        return 60.0;
    }
    return 100.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(viewFlag==100)
    {
        static NSString *MyIdentifier = @"WYQRecommendCircleTableViewCell"; //相当于一个行标识
        WYQRecommendCircleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    //tableViewCell重绘
        if (cell == nil) {
            cell =[[[NSBundle mainBundle]loadNibNamed:@"WYQRecommendCircleTableViewCell" owner:self options:nil]lastObject];
        }
        NSDictionary *dic=[self.dataRecommendCircleArray objectAtIndex:indexPath.row];
        cell.gegerationLab.text=[dic objectForKey:@"name"];
        cell.gegerationNumLab.text=[dic objectForKey:@"num"];
        cell.backImageV.image=[UIImage imageNamed:@"connectsItem.png"];
        return cell;
    }
    if(viewFlag==101)
    {
        static NSString *MyIdentifier = @"WYQMyConnectionsSimpleTableViewCell"; //相当于一个行标识
        WYQMyConnectionsSimpleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        //tableViewCell重绘
        if (cell == nil) {
            cell =[[[NSBundle mainBundle]loadNibNamed:@"WYQMyConnectionsSimpleTableViewCell" owner:self options:nil]lastObject];
        }
        return cell;
    }
    if(viewFlag==102)
    {
        static NSString *MyIdentifier = @"WYQMyConnectionsDetailTableViewCell"; //相当于一个行标识
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        //tableViewCell重绘
        if (cell == nil) {
            cell =[[[NSBundle mainBundle]loadNibNamed:@"WYQMyConnectionsDetailTableViewCell" owner:self options:nil]lastObject];
        }
        if(indexPath.row%3==0)
        {
           if(![cell isKindOfClass:[WYQMyConnectionsSimpleTableViewCell class]])
           {
               cell=[[[NSBundle mainBundle]loadNibNamed:@"WYQMyConnectionsSimpleTableViewCell" owner:self options:nil]lastObject];
           }
        }
        return cell;
    }
    return nil;

}
//tabbar按钮点击
-(void)radioClick:(RadioButton *)selectedButton
{
    if(viewFlag==selectedButton.tag)
    {
        return;
    }
    viewFlag=selectedButton.tag;
    if(viewFlag==100)
    {
        self.numberLab.hidden=YES;
    }else
    {
        self.numberLab.text=[NSString stringWithFormat:@"%d",arc4random()%100+1];
        self.numberLab.hidden=NO;
    }
    [dataTableView reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end