text:
package uk.ac.ebi.embl.api.validation.helper;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import uk.ac.ebi.embl.api.entry.feature.FeatureFactory;
import uk.ac.ebi.embl.api.entry.feature.SourceFeature;
import uk.ac.ebi.embl.api.entry.qualifier.Qualifier;
import uk.ac.ebi.embl.api.entry.qualifier.QualifierFactory;
import uk.ac.ebi.embl.api.validation.SampleInfo;
import uk.ac.ebi.embl.api.validation.check.feature.MasterSourceQualifierValidator;
import uk.ac.ebi.embl.api.validation.dao.EraproDAOUtilsImpl.MASTERSOURCEQUALIFIERS;
import uk.ac.ebi.embl.api.validation.dao.model.SampleEntity;
import uk.ac.ebi.embl.api.validation.helper.taxon.TaxonHelper;
import uk.ac.ebi.ena.taxonomy.taxon.Taxon;

public class SourceFeatureUtils {

	private Qualifier isolationSourceQualifier=null;
	private final  String isolation_source_regex = "^\\s*environment\\s*\\(material\\)\\s*$";
	private final  Pattern isolation_sourcePattern = Pattern.compile(isolation_source_regex);
	private boolean addUniqueName=true;
	private final Map<String,String> qualifierSynonyms = new HashMap<>();
	private final Set<String> covid19RequiredQuals = new HashSet<>();
	private final MasterSourceQualifierValidator masterSourceQualifierValidator;

	public SourceFeatureUtils() {
		qualifierSynonyms.put("metagenomic source",Qualifier.METAGENOME_SOURCE_QUALIFIER_NAME);
		qualifierSynonyms.put("host scientific name",Qualifier.HOST_QUALIFIER_NAME);
		qualifierSynonyms.put("collection date",Qualifier.COLLECTION_DATE_QUALIFIER_NAME);
		qualifierSynonyms.put("gisaid accession id",Qualifier.NOTE_QUALIFIER_NAME);
		covid19RequiredQuals.add(Qualifier.COLLECTION_DATE_QUALIFIER_NAME);
		covid19RequiredQuals.add(Qualifier.COUNTRY_QUALIFIER_NAME);
		covid19RequiredQuals.add(Qualifier.LAT_LON_QUALIFIER_NAME);
		covid19RequiredQuals.add(Qualifier.HOST_QUALIFIER_NAME);
		covid19RequiredQuals.add(Qualifier.NOTE_QUALIFIER_NAME);

		isolationSourceQualifier=null;
		masterSourceQualifierValidator = new MasterSourceQualifierValidator();
	}

	public boolean isCovidTaxId(Long taxID) {
		return taxID != null  && taxID == 2697049L;
	}
	public void addSourceQualifier(String tag, String value,SourceFeature source)
	{

		if(tag==null)
			return;
		tag = tag.toLowerCase();

		if(qualifierSynonyms.containsKey(tag)) {
			tag = qualifierSynonyms.get(tag);
		}

		if(tag.equals(Qualifier.COLLECTION_DATE_QUALIFIER_NAME) && !masterSourceQualifierValidator.isValid(Qualifier.COLLECTION_DATE_QUALIFIER_NAME, value)) {
			//we have to do similar check for other qualifier as well.
			return;
		}

		if(isolation_sourcePattern.matcher(tag).matches())
		{
			tag=Qualifier.ISOLATION_SOURCE_QUALIFIER_NAME;
			if(value!=null&&!value.isEmpty())
			isolationSourceQualifier= (new QualifierFactory()).createQualifier(tag,value);
		}
		else
		{
		if (MASTERSOURCEQUALIFIERS.isValid(tag))
		{

			if(!MASTERSOURCEQUALIFIERS.isNoValue(tag) && MASTERSOURCEQUALIFIERS.isNullValue(value))
				return;

			if(Qualifier.ENVIRONMENTAL_SAMPLE_QUALIFIER_NAME.equals(tag)||Qualifier.STRAIN_QUALIFIER_NAME.equals(tag)||Qualifier.ISOLATE_QUALIFIER_NAME.equals(tag))
			{
				addUniqueName=false;
			}

			if(MASTERSOURCEQUALIFIERS.isNoValue(tag))
			{
				if(!"NO".equalsIgnoreCase(value))
					source.addQualifier(new QualifierFactory().createQualifier(tag));
			}
			else
				source.addQualifier(new QualifierFactory().createQualifier(tag, value));
		} else if(isCovidTaxId(source.getTaxId()) && covid19RequiredQuals.contains(tag)) {
			source.addQualifier(new QualifierFactory().createQualifier(tag, value));
		}
	}

	}

	public void addExtraSourceQualifiers(SourceFeature source,TaxonHelper taxonHelper,String uniqueName)
	{
		if(addUniqueName && taxonHelper.isProkaryotic(source.getScientificName()) && source.getQualifiers(Qualifier.ISOLATE_QUALIFIER_NAME).size()==0)
		{
			source.addQualifier( new QualifierFactory().createQualifier(Qualifier.ISOLATE_QUALIFIER_NAME,uniqueName));
		}

		if(source.getQualifiers(Qualifier.ISOLATION_SOURCE_QUALIFIER_NAME).size()==0 && isolationSourceQualifier!=null)
			source.addQualifier(isolationSourceQualifier);
	}

	public SourceFeature constructSourceFeature(SampleEntity sample, TaxonHelper taxonHelper, SampleInfo sampleInfo) {
		FeatureFactory featureFactory = new FeatureFactory();
		SourceFeature sourceFeature = featureFactory.createSourceFeature();
		sourceFeature.setTaxId(sampleInfo.getTaxId());
		sourceFeature.setScientificName(sampleInfo.getScientificName());
		sourceFeature.setMasterLocation();
		addQualifiers(sourceFeature,sample,taxonHelper,sampleInfo);
		return sourceFeature;
	}

	public SourceFeature updateSourceFeature(SourceFeature sourceFeature, SampleEntity sample, TaxonHelper taxonHelper, SampleInfo sampleInfo) {
		sourceFeature.setTaxId(sampleInfo.getTaxId());
		sourceFeature.setScientificName(sampleInfo.getScientificName());
		addQualifiers(sourceFeature,sample,taxonHelper,sampleInfo);
		return sourceFeature;
	}

	public void addQualifiers(SourceFeature sourceFeature,SampleEntity sample,TaxonHelper taxonHelper, SampleInfo sampleInfo){
		String latitude = null;
		String longitude = null;
		String country = null;
		String region = null;
		for (Map.Entry<String, String> entry : sample.getAttributes().entrySet()) {
			String tag = entry.getKey();
			String value = entry.getValue();
			if (isCovidTaxId(sourceFeature.getTaxId()) && tag != null) {
				// Master source qualifiers values created from multiple sample fields are constructed here.
				if (tag.toLowerCase().contains("latitude")) {
					latitude = value;
				} else if (tag.toLowerCase().contains("longitude")) {
					longitude = value;
				} else if (tag.trim().equalsIgnoreCase("geographic location (country and/or sea)")) {
					country = value;
				} else if (tag.trim().equalsIgnoreCase("geographic location (region and locality)")) {
					region = value;
				} else {
					addSourceQualifier(tag, value, sourceFeature);
				}
			} else {
				addSourceQualifier(tag, value, sourceFeature);
			}
		}

		if (latitude != null && longitude != null) {
			String latValue = latitude;
			String lonValue = longitude;
			try {
				double lat = Double.parseDouble(latitude);
				latValue += " " + (lat < 0 ? "S" : "N");
			} catch (NumberFormatException ex) {
				//ignore
			}
			try {
				double lon = Double.parseDouble(longitude);
				lonValue += " " + (lon < 0 ? "W" : "E");
			} catch (NumberFormatException ex) {
				//ignore
			}
			String latLonValue = latValue + " " + lonValue;
			addSourceQualifier(Qualifier.LAT_LON_QUALIFIER_NAME, latLonValue, sourceFeature);
		}
		if (country != null || region != null) {
			addSourceQualifier(Qualifier.COUNTRY_QUALIFIER_NAME, country == null ? region : region == null ? country : country + ":" + region, sourceFeature);
		}

		Taxon taxon = taxonHelper.getTaxonById(sampleInfo.getTaxId());
		if (taxon != null) {
			sourceFeature.setTaxon(taxon);
		}
		addExtraSourceQualifiers(sourceFeature, taxonHelper, sampleInfo.getUniqueName());
	}

}


text:
周报第四十二期

- 催稿人:
  [@swaylq][swaylq]
- 交稿人:
  [@at15][at15]
  [@arrowrowe][mie]
  [@ComMouse][dou]
  [@gaocegege][gaocegege]

[at15]: https://github.com/at15
[mie]: https://github.com/arrowrowe
[dou]: https://github.com/ComMouse
[gaocegege]: https://github.com/gaocegege
[swaylq]: https://github.com/swaylq

## 一些库

- [slate](https://github.com/ianstormtaylor/slate), A completely customizable framework for building rich text editors in the browser.
- [Faker](https://github.com/fzaninotto/Faker), Faker is a PHP library that generates fake data for you.

  > 很管用啊感觉, by [@gaocegege][gaocegege].
- [gomail](https://github.com/go-gomail/gomail), 用golang连接smtp服务器发邮件的lib.

## 一些工具

- [marp](https://github.com/yhatt/marp), Electron based markdown editor (pre maker?)

- [unsplash](https://unsplash.com/), Free (do whatever you want) high-resolution photos. For 10 new photos every 10 days.

  > it has API: https://unsplash.com/developers
- [Gitamin](http://gitamin.com/), An open-source, self-hosted git repository management software based on the Laravel PHP Framework.

  ![Screenshot](http://www.gitamin.com/screenshot1.png)
- [wercker](http://wercker.com/), Automate your development. Move faster with pipelines and steps. cc [@gaocegege][gaocegege].

  > re @at15 http://wercker.com/ 不好用, by [@gaocegege][gaocegege].

## 奇怪的东西

- [PLY (Python Lex-Yacc)](http://www.dabeaz.com/ply/), PLY is an implementation of lex and yacc parsing tools for Python.

## 关于搜索

All about search

- [sack](https://github.com/sampson-chen/sack), s(hortcut)-ack: a faster way to use ag, ack (or grep)!
- [the_silver_searcher](https://github.com/ggreer/the_silver_searcher), A code-searching tool similar to ack, but faster.
- [the_platinum_searcher](https://github.com/monochromegane/the_platinum_searcher), A code search tool similar to ack and the_silver_searcher(ag).
- [more-tools](http://beyondgrep.com/more-tools/)

## P2P 文件分享

- [Hyperdrive](https://github.com/mafintosh/hyperdrive)
- [Hypercore](https://github.com/mafintosh/hypercore)
- [Hyperdrive + Hypercore Specification](https://github.com/datproject/docs/blob/master/hyperdrive.md)

## Pokemon-Go专题

- [PokemonGoMove](https://github.com/huacnlee/PokemonGoMove), Pokemon GO iOS GPS Emulator - NO Jailbreak needed, lets you play the game on your Mac :)
- [PokemonGo-Finder](https://github.com/jxmorris12/PokemonGo-Finder), 发现周围的Pokemon并通知.
- [PokemonGo-DesktopMap](https://github.com/mchristopher/PokemonGo-DesktopMap), Electron App around PokemonGo-Map.
- [pokemongo-webspoof](https://github.com/iam4x/pokemongo-webspoof), 亲测可用,功能同第一个.
- [PokemonHook](https://github.com/rpplusplus/PokemonHook), 在Github上发现的第一个Pokemon相关的项目,是Fake Location的,就是把基准位置定为其他地方,来解决国内地图没有Pokemon的问题.

> All by [@gaocegege][gaocegege].

redpajama_set_name: RedPajamaGithub


text:
package input

import (
	"strconv"

	"engo.io/engo"
)

var (
	sceneRegistry *[]Key
)

// Key contains the information needed for key events. It also contains three
// functions that can be set on each type of key event.
type Key struct {
	Name string
	Keys []engo.Key

	OnPress   func(engo.Key, *Modifiers)
	OnRelease func(engo.Key, *Modifiers)
}

// RegisterKeys registers keys with functions for the scene. It also handles
// registering modifiers to the global key management system so that we can
// tell if the key was used at the same time that a modifier key was used.
func RegisterKeys(keys []Key) {
	// Store the button registry globally
	sceneRegistry = &keys

	// Register all of the buttons
	for _, key := range keys {
		for index, k := range key.Keys {
			engo.Input.RegisterButton(
				key.Name+strconv.Itoa(index),
				k,
			)
		}
	}

	registerModifiers()
}


text:
 Improve this Doc

Error: $injector:modulerr

Module Error

Failed to instantiate module {0} due to:
{1}

Description

This error occurs when a module fails to load due to some exception. The error
message above should provide additional context.

Using ngRoute

In AngularJS 1.2.0 and later, ngRoute has been moved to its own module.
If you are getting this error after upgrading to 1.2.x or later, be sure that you've
installed ngRoute.

Monkey-patching Angular's ng module

This error can also occur if you have tried to add your own components to the ng module.
This has never been supported and from 1.3.0 it will actually trigger this error.
For instance the following code could trigger this error.

angular.module('ng').filter('tel', function (){});

Instead create your own module and add it as a dependency to your application's top-level module.
See #9692 and
#7709 for more information


text:
package consulo.logging.internal;

import consulo.annotation.ReviewAfterMigrationToJRE;
import consulo.logging.attachment.AttachmentFactory;

import javax.annotation.Nonnull;
import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @author VISTALL
 * @since 2019-08-10
 */
public class AttachmentFactoryInternal {
  private static final AttachmentFactory ourInstance = loadSingleOrError(AttachmentFactory.class);

  @Nonnull
  @ReviewAfterMigrationToJRE(9)
  private static <T> T loadSingleOrError(@Nonnull Class<T> clazz) {
    ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz, clazz.getClassLoader());
    Iterator<T> iterator = serviceLoader.iterator();
    if (iterator.hasNext()) {
      return iterator.next();
    }
    throw new Error("Unable to find '" + clazz.getName() + "' implementation");
  }

  public static AttachmentFactory get() {
    return ourInstance;
  }
}


text:
package com.sgu.infowksporga.jfx.views.common.action;

import java.awt.event.ActionEvent;

import com.sgu.apt.annotation.AnnotationConfig;
import com.sgu.apt.annotation.i18n.I18n;
import com.sgu.apt.annotation.i18n.I18nProperty;
import com.sgu.infowksporga.jfx.menu.action.AbstractInfoWrkspOrgaAction;
import com.sgu.infowksporga.jfx.views.AbstractView;
import com.sgu.infowksporga.jfx.views.common.dialog.AbstractViewPropertiesDlg;

/**
 * Description : Display View Properties Dlg Action class

 *
 * @author SGU
 */
public abstract class AbstractShowViewPropertiesDlgAction extends AbstractInfoWrkspOrgaAction {

  /**
   * The attribute serialVersionUID
   */
  private static final long serialVersionUID = -6124596911162025134L;

  /**
   * The reference to get the view
   */
  protected final AbstractView view;

  /**
   * Constructor

   */
  @I18n(baseProject = AnnotationConfig.I18N_TARGET_APPLICATION_PROPERTIES_FOLDER, filePackage = "i18n", fileName = "application-prez",
  properties = { // Force \n
                @I18nProperty(key = "common.view.action.properties.text", value = "Propriétés de la vue"), // Force \n
                @I18nProperty(key = "common.view.action.properties.tooltip", value = "Configure la vue sélectionnée"), // Force \n
                @I18nProperty(key = "common.view.action.properties.icon", value = "/icons/configuration.gif"), // Force \n
  })
  public AbstractShowViewPropertiesDlgAction(final AbstractView view) {
    super("common.view.action.properties");
    this.view = view;
  }

  /** {@inheritDoc} */
  @Override
  public void actionPerformed(final ActionEvent evt) {
    final AbstractViewPropertiesDlg dlg = builViewPropertiesDlg(view);
    dlg.pack();
    dlg.centerDialogVsScreen();
    dlg.setVisible(true);
  }

  /**
   * Buil view properties dlg.
   *
   * @param view the view
   * @return the abstract view properties dlg
   */
  protected abstract AbstractViewPropertiesDlg builViewPropertiesDlg(AbstractView view);
}


text:
import re
import tokenize

from sahara.utils.hacking import commit_message
from sahara.utils.hacking import import_checks

def _starts_with_any(line, *prefixes):
    for prefix in prefixes:
        if line.startswith(prefix):
            return True
    return False

def _any_in(line, *sublines):
    for subline in sublines:
        if subline in line:
            return True
    return False

def import_db_only_in_conductor(logical_line, filename):
    """Check that db calls are only in conductor module and in tests.

    S361
    """
    if _any_in(filename,
               "sahara/conductor",
               "sahara/tests",
               "sahara/db"):
        return

    if _starts_with_any(logical_line,
                        "from sahara import db",
                        "from sahara.db",
                        "import sahara.db"):
        yield (0, "S361: sahara.db import only allowed in "
                  "sahara/conductor/*")

def hacking_no_author_attr(logical_line, tokens):
    """__author__ should not be used.

    S362: __author__ = slukjanov
    """
    for token_type, text, start_index, _, _ in tokens:
        if token_type == tokenize.NAME and text == "__author__":
            yield (start_index[1],
                   "S362: __author__ should not be used")

def check_oslo_namespace_imports(logical_line):
    """Check to prevent old oslo namespace usage.

    S363
    """
    oslo_imports = (re.compile(r"(((from)|(import))\s+oslo\.)"),
                    re.compile(r"(from\s+oslo\s+import)"))

    if re.match(oslo_imports[0], logical_line):
        yield(0, "S363: '%s' must be used instead of '%s'." % (
            logical_line.replace('oslo.', 'oslo_'),
            logical_line))

    if re.match(oslo_imports[1], logical_line):
        yield(0, "S363: '%s' must be used instead of '%s'" % (
              'import oslo_%s' % logical_line.split()[-1],
              logical_line))

def dict_constructor_with_list_copy(logical_line):
    """Check to prevent dict constructor with a sequence of key-value pairs.

    S368
    """
    dict_constructor_with_list_copy_re = re.compile(r".*\bdict\((\[)?(\(|\[)")

    if dict_constructor_with_list_copy_re.match(logical_line):
        yield (0, 'S368: Must use a dict comprehension instead of a dict '
               'constructor with a sequence of key-value pairs.')

def factory(register):
    register(import_db_only_in_conductor)
    register(hacking_no_author_attr)
    register(check_oslo_namespace_imports)
    register(commit_message.OnceGitCheckCommitTitleBug)
    register(commit_message.OnceGitCheckCommitTitleLength)
    register(import_checks.hacking_import_groups)
    register(import_checks.hacking_import_groups_together)
    register(dict_constructor_with_list_copy)


text:
.class final Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService$SettingsObserver;
.super Landroid/database/ContentObserver;
.source "SemDisplaySolutionManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x12
    name = "SettingsObserver"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService;

# direct methods
.method public constructor <init>(Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService;Landroid/os/Handler;)V
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService$SettingsObserver;->this$0:Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService;

    invoke-direct {p0, p2}, Landroid/database/ContentObserver;-><init>(Landroid/os/Handler;)V

    return-void
.end method

# virtual methods
.method public onChange(ZLandroid/net/Uri;)V
    .locals 1

    iget-object v0, p0, Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService$SettingsObserver;->this$0:Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService;

    invoke-static {v0}, Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService;->-wrap0(Lcom/samsung/android/displaysolution/SemDisplaySolutionManagerService;)V

    return-void
.end method


text:
                    Postavljeno na dan

                    od

                    Kreiraj novi odgovor?

                <button class="btn btn-primary" data-ng-click="showResponses()">Prikaži odgovore</button>

Odgovor {{requestresponse.created | date:'mediumDate'}}

{{requestresponse.text}}


text:
require 'spec_helper'

describe OfficeAutopilotApi::Client::Contacts do

  before do
    @contact_endpoint = "#{api_endpoint}/cdata.php"
    @client = OfficeAutopilotApi::Client.new(:api_id => 'xxx', :api_key => 'xxx')
    @auth_str = "Appid=#{@client.api_id}&Key=#{@client.api_key}"
  end

  def request_body(req_type, options = {})
    options = { 'reqType' => req_type }.merge(options)

    query = ''
    options.each do |key, value|
      if key == "data"
        value = escape_xml(value)
      end
      query << "#{key}=#{value}&"
    end
    query << @auth_str
  end

  describe "#xml_for_search" do
    # <search>
    #   <equation>
    #     <field>E-Mail</field>
    #     <op>e</op>
    #     <value>john@example.com</value>
    #   </equation>
    # </search>

    context "searching with one field" do
      it "returns a valid simple search data xml" do
        field = "E-Mail"
        op = "e"
        value = "john@example.com"

        xml = Nokogiri::XML(@client.send(:xml_for_search, { :field => field, :op => op, :value => value }) )
        xml.at_css('field').content.should == field
        xml.at_css('op').content.should == op
        xml.at_css('value').content.should == value
      end
    end

    context "searching with more than one field" do
      it "returns a valid multi search data xml" do
        search_options = [
          {:field => 'E-Mail', :op => 'e', :value => 'foo@example.com'},
          {:field => 'Contact Tags', :op => 'n', :value => 'bar'},
        ]

        xml = @client.send(:xml_for_search, search_options)
        xml = Nokogiri::XML(xml)
        xml.css('field')[0].content.should == 'E-Mail'
        xml.css('op')[0].content.should == 'e'
        xml.css('value')[0].content.should == 'foo@example.com'

        xml.css('field')[1].content.should == 'Contact Tags'
        xml.css('op')[1].content.should == 'n'
        xml.css('value')[1].content.should == 'bar'
      end
    end
  end

  describe "#contacts_search" do
    it "returns the matched contacts" do
      search_options = {:field => 'E-Mail', :op => 'e', :value => 'prashant@example.com'}
      search_xml = @client.send(:xml_for_search, search_options)
      contacts_xml = test_data('contacts_search_single_response.xml')

      request_body = request_body('search', 'data' => search_xml)
      stub_request(:post, @contact_endpoint).with(:body => request_body).to_return(:body => contacts_xml)

      contacts = @client.contacts_search(search_options)
      WebMock.should have_requested(:post, @contact_endpoint).with(:body => request_body)
      contacts.should == @client.send(:parse_contacts_xml, contacts_xml)
    end
  end

  describe "#xml_for_contact" do
    before do
      @contact_options = {
        'Contact Information' => {'First Name' => 'Bob', 'Last Name' => 'Foo', 'E-Mail' => 'b@example.com'},
        'Lead Information' => {'Contact Owner' => 'Mr Bar'}
      }
    end

    it "returns a valid contacts xml" do
      xml = @client.send(:xml_for_contact, @contact_options)
      xml = Nokogiri::XML(xml)

      xml.at_css('contact')['id'].should be_nil

      contact_info = xml.css("contact Group_Tag[name='Contact Information']")
      contact_info.at_css("field[name='First Name']").content.should == 'Bob'
      contact_info.at_css("field[name='Last Name']").content.should == 'Foo'

      lead_info = xml.css("contact Group_Tag[name='Lead Information']")
      lead_info.at_css("field[name='Contact Owner']").content.should == 'Mr Bar'
    end

    context "when 'id' is specified" do
      it "returns a valid contact xml containing the contact id" do
        @contact_options.merge!('id' => '1234')
        xml = Nokogiri::XML( @client.send(:xml_for_contact, @contact_options) )

        xml.at_css('contact')['id'].should == '1234'
        contact_info = xml.css("contact Group_Tag[name='Contact Information']")
        contact_info.at_css("field[name='First Name']").content.should == 'Bob'
        contact_info.at_css("field[name='Last Name']").content.should == 'Foo'

        lead_info = xml.css("contact Group_Tag[name='Lead Information']")
        lead_info.at_css("field[name='Contact Owner']").content.should == 'Mr Bar'
      end
    end
  end

  describe "#parse_contacts_xml" do
    context "when the results contain one contact" do
      it "returns an array containing the contact" do
        contacts = @client.send(:parse_contacts_xml, test_data('contacts_search_single_response.xml'))

        contacts.size.should == 1

        contacts.each do |contact|
          contact['id'].should == '7'
          contact['Contact Information']['First Name'].should == 'prashant'
          contact['Contact Information']['Last Name'].should == 'nadarajan'
          contact['Contact Information']['E-Mail'].should == 'prashant@example.com'
          contact['Lead Information']['Contact Owner'].should == 'Don Corleone'
        end
      end
    end

    context "when the results contain more than one contact" do
      it "returns an array containing the contacts" do
        contacts = @client.send(:parse_contacts_xml, test_data('contacts_search_multiple_response.xml'))

        contacts.size.should == 3

        contacts[0]['id'].should == '8'
        contacts[0]['Contact Information']['E-Mail'].should == 'bobby@example.com'
        contacts[0]['Lead Information']['Contact Owner'].should == 'Jimbo Watunusi'

        contacts[1]['id'].should == '5'
        contacts[1]['Contact Information']['E-Mail'].should == 'ali@example.com'
        contacts[1]['Lead Information']['Contact Owner'].should == 'Jimbo Watunusi'
      end
    end
  end

  describe "#contacts_add" do
    it "returns the newly created contact" do
      contact_options = {
        'Contact Information' => {'First Name' => 'prashant', 'Last Name' => 'nadarajan', 'E-Mail' => 'prashant@example.com'},
        'Lead Information' => {'Contact Owner' => 'Don Corleone'}
      }

      request_contact_xml = @client.send(:xml_for_contact, contact_options)
      response_contact_xml = test_data('contacts_add_response.xml')

      request_body = request_body('add', 'return_id' => '1', 'data' => request_contact_xml)
      stub_request(:post, @contact_endpoint).with(:body => request_body).to_return(:body => response_contact_xml)

      contact = @client.contacts_add(contact_options)
      WebMock.should have_requested(:post, @contact_endpoint).with(:body => request_body)

      contact['id'].should == '7'
      contact['Contact Information']['First Name'].should == 'prashant'
      contact['Contact Information']['Last Name'].should == 'nadarajan'
      contact['Contact Information']['E-Mail'].should == 'prashant@example.com'
      contact['Lead Information']['Contact Owner'].should == 'Don Corleone'
    end
  end

  describe "#contacts_pull_tag" do
    it "returns all the contact tag names and ids" do
      pull_tags_xml = test_data('contacts_pull_tags.xml')
      stub_request(:post, @contact_endpoint).with(:body => request_body('pull_tag')).to_return(:body => pull_tags_xml)

      tags = @client.contacts_pull_tag
      tags['3'].should == 'newleads'
      tags['4'].should == 'old_leads'
      tags['5'].should == 'legacy Leads'
    end
  end

  describe "#contacts_fetch_sequences" do
    it "returns all the available contact sequences" do
      xml = test_data('contacts_fetch_sequences.xml')
      stub_request(:post, @contact_endpoint).with(:body => request_body('fetch_sequences')).to_return(:body => xml)
      sequences = @client.contacts_fetch_sequences
      sequences['3'].should == 'APPOINTMENT REMINDER'
      sequences['4'].should == 'foo sequence'
    end
  end

  describe "#contacts_key" do
    it "returns information on the contact data structure" do
      xml = test_data('contacts_key_type.xml')
      stub_request(:post, @contact_endpoint).with(:body => request_body('key')).to_return(:body => xml)

      result = @client.contacts_key
      result["Contact Information"]["editable"].should be_false
      result["Contact Information"]["fields"]["Cell Phone"]["editable"].should be_false
      result["Contact Information"]["fields"]["Cell Phone"]["type"].should == "phone"
      result["Contact Information"]["fields"]["Birthday"]["type"].should == "fulldate"

      result["Lead Information"]["fields"]["Lead Source"]["type"].should == "tdrop"
      result["Lead Information"]["fields"]["Lead Source"]["options"][0].should == "Adwords"
      result["Lead Information"]["fields"]["Lead Source"]["options"][4].should == "Newspaper Ad"

      result["Sequences and Tags"]["fields"]["Contact Tags"]["type"].should == "list"
      result["Sequences and Tags"]["fields"]["Contact Tags"]["list"]["5"].should == "legacy Leads"

      result["PrecisoPro"]["editable"].should be_true
      result["PrecisoPro"]["fields"]["Lead Status"]["editable"].should be_true
    end
  end

  describe "#contacts_fetch" do
    context "when all the ids exists" do
      it "returns the contacts" do
        xml_response = test_data('contacts_search_multiple_response.xml')
        xml_request = "<contact_id>8</contact_id><contact_id>5</contact_id><contact_id>7</contact_id>"
        stub_request(:post, @contact_endpoint).with(:body => request_body('fetch', 'data' => xml_request )).to_return(:body => xml_response)

        results = @client.contacts_fetch([8, 5, 7])
        results.size.should == 3
        results[0]["Contact Information"].should_not be_nil
      end
    end

    context "when some of the ids don't exist" do
      pending
    end

    context "when all the ids don't exist" do
      pending
    end
  end
end


text:
# PlaneTrainPlace
通过FMDB读取数据库文件中火车飞机地点的name和code,选择地点通过Block会调。

/**
飞机票(回调地点和编码)
*/

PlaneAndTrainPlaceController *vc = [[PlaneAndTrainPlaceController alloc]init];

[vc setPlaceType:0];

vc.planeBlock = ^(NSString *name,NSString *code){

};

[self presentViewController:vc animated:YES completion:nil];

/**
火车票(只回调地点)
*/

PlaneAndTrainPlaceController *vc = [[PlaneAndTrainPlaceController alloc]init];

[vc setPlaceType:1];

vc.trainBlock = ^(NSString *name){

};

[self presentViewController:vc animated:YES completion:nil];


text:
ARCH=$(shell uname -m | sed -e 's/i.86/i386/;s/arm.*/arm/')
TARGET=$(ARCH)

CODEGEN=old
COMPILEOPTS=-s

MACH_SOURCES=compiler/mach.pco
CODEGEN_SOURCES=

# Code generation stratey selection
ifeq ($(CODEGEN),old)
CODEGEN_SOURCES+=compiler/codegen-old.pco
else ifeq ($(CODEGEN),simple)
CODEGEN_SOURCES+=compiler/codegen-simple.pco
else ifeq ($(CODEGEN),context)
CODEGEN_SOURCES+=compiler/codegen-context.pco
else
$(error unknown codegen strategy $(CODEGEN))
endif

ifeq ($(TARGET),arm)
# ARM
MACH_SOURCES+=compiler/mach-32bit.pco compiler/mach-arm.pco
CODEGEN_SOURCES+=compiler/codegen-risc.pco compiler/codegen-arm.pco

else ifeq ($(TARGET),mips)
MACH_SOURCES+=compiler/mach-32bit.pco compiler/mach-mips32.pco
CODEGEN_SOURCES+=compiler/codegen-risc.pco compiler/codegen-mips32.pco

else
# x86
STACK_REGIME=no-fp

ifeq ($(STACK_REGIME),no-fp)
CODEGEN_SOURCES+=compiler/stack-traditional.pco compiler/stack-no-fp.pco
else ifeq ($(STACK_REGIME),fp)
CODEGEN_SOURCES+=compiler/stack-traditional.pco compiler/stack-fp.pco
else
$(error unknown stack regime $(STACK_REGIME))
endif

CODEGEN_SOURCES+=compiler/codegen-x86.pco
ifeq ($(TARGET),i386)
MACH_SOURCES+=compiler/mach-32bit.pco compiler/mach-i386.pco
CODEGEN_SOURCES+=compiler/codegen-i386.pco
else ifeq ($(TARGET),x86_64)
MACH_SOURCES+=compiler/mach-64bit.pco compiler/mach-x86_64.pco
CODEGEN_SOURCES+=compiler/codegen-x86_64.pco
else
$(error unknown target $(TARGET))
endif
MACH_SOURCES+=compiler/mach-x86.pco

endif

COMPILER_SOURCES= \
    language/util.pco language/expander.pco language/interpreter.pco \
    compiler/walker.pco $(MACH_SOURCES) compiler/front-end.pco \
    $(CODEGEN_SOURCES) compiler/codegen-generic.pco compiler/driver.pco

CL_COMPILER_SOURCES= \
    bootstrap/cl-dialect.lisp runtime/runtime-common.pco runtime/io-common.pco \
    $(COMPILER_SOURCES)
export CL_COMPILER_SOURCES

RUNTIME=runtime/runtime.pco runtime/cl-compat.pco runtime/runtime-common.pco \
    runtime/io.pco runtime/io-common.pco no-interp!runtime/sysconstants.pco \
    no-interp!runtime/compiled-builtins.pco no-interp!runtime/gc.pco
RUNTIME_SOURCES=$(patsubst no-interp!%,%,$(RUNTIME))
SL_COMPILER_SOURCES=$(COMPILER_SOURCES) compiler/drivermain.pco

# The initial compiler used.  Default to bootstrapping from SBCL
BOOTSTRAP_COMPILER=scripts/sbcl-wrapper

# The phase to stop at when dumping the intermediate program
DUMP_PHASE=fill-closures

.PHONY: all clean print-compiler-sources compare-stage3 mk-build-dir

all: stage0-test-run stage0-gc-test-run stage0-arity-mismatch-test-run compare-stage3 stage2-static-arity-mismatch-test-run

build/sysconstants: runtime/sysconstants.c | mk-build-dir
	$(CC) -Wall -Werror -o $@ $<

runtime/sysconstants.pco: build/sysconstants
	$< >$@

clean::
	rm -f runtime/sysconstants.pco

print-compiler-sources:
	@echo $(SL_COMPILER_SOURCES)

mk-build-dir:
	@mkdir -p build

# compile,compiler,dest,sources
define compile
$(2) $(2).s: $(1) $(RUNTIME_SOURCES) $(3) | mk-build-dir
	scripts/compile -C $(1) $(COMPILEOPTS) -o $(2) $(3)
endef

define stage_template
.PHONY: $(2)-interp-test $(2)-compile $(2)-test-run $(2)-time

$(2)-interp-test: $(1) $(RUNTIME_SOURCES) test/test.pco
	$(1) interpret $(RUNTIME) test/test.pco

$(2)-compile: $(1) $(RUNTIME_SOURCES) test/test.pco
	$(1) compile $(RUNTIME) test/test.pco

$(eval $(call compile,$(1),build/$(2)-test,test/test.pco))
$(eval $(call compile,$(1),build/$(2)-gc-test,test/gc-test.pco))
$(eval $(call compile,$(1),build/$(2)-arity-mismatch-test,test/arity-mismatch-test.pco))

$(2)-test-run: build/$(2)-test
	$$<

$(2)-gc-test-run: build/$(2)-gc-test
	$$<

$(2)-arity-mismatch-test-run: build/$(2)-arity-mismatch-test
	[ "$$$$( ( $$< 2>&1 ; [ $$$$? -ge 128 ] || echo 'wrong exit code' ) | sed '/^Aborted/d' )" = "expected 2 arguments, got 1" ]

$(2)-static-arity-mismatch-test-run: $(1) $(RUNTIME_SOURCES) test/static-arity-mismatch-test.pco
	@mkdir -p build
	[ "$$$$( ( scripts/compile -C $(1) $(COMPILEOPTS) -o build/static-arity-mismatch-test test/static-arity-mismatch-test.pco 2>&1 && echo 'should have failed' ) | sed '/Aborted/d' )" = "wrong number of arguments in call to func (expected 1, got 2)" ]

$(2)-expand: $(1) $(RUNTIME_SOURCES) $(SL_COMPILER_SOURCES)
	$(1) expand $(RUNTIME) $(SL_COMPILER_SOURCES)

$(2)-dump: $(1) $(RUNTIME_SOURCES) $(SL_COMPILER_SOURCES)
	$(1) dump $(DUMP_PHASE) $(RUNTIME) $(SL_COMPILER_SOURCES)

$(2)-expand-test: $(1) $(RUNTIME_SOURCES) test/test.pco
	$(1) expand $(RUNTIME) test/test.pco

$(2)-dump-test: $(1) $(RUNTIME_SOURCES) test/test.pco
	$(1) dump $(DUMP_PHASE) $(RUNTIME) test/test.pco

$(eval $(call compile,$(1),build/$(3),$(SL_COMPILER_SOURCES)))

$(2)-time: $(1) $(RUNTIME_SOURCES) $(SL_COMPILER_SOURCES)
	scripts/compile -C $(1) $(COMPILEOPTS) -T $(SL_COMPILER_SOURCES)
endef

clean::
	rm -rf build

scripts/sbcl-wrapper: $(CL_COMPILER_SOURCES)

$(eval $(call stage_template,$(BOOTSTRAP_COMPILER),stage0,stage1))
$(eval $(call stage_template,build/stage1,stage1,stage2))
$(eval $(call stage_template,build/stage2,stage2,stage3))

compare-stage3: build/stage2.s build/stage3.s
	cmp -s build/stage2.s build/stage3.s

build/repl build/repl.s: language/repl.pco language/util.pco language/interpreter.pco language/expander.pco | build/stage2
	scripts/compile $^ $(COMPILEOPTS) -o $@

.PHONY: repl
repl: build/repl
	build/repl $(patsubst no-interp!%,,$(RUNTIME))


text:
local_path=$(cd $(dirname $0);pwd)
source $local_path/Common
xpk_path=$local_path/../testapp
originalOneApp="update_original_versionOne_tests"
originalLowerApp="update_original_LowerMulti_tests"

#func_check_xwalkservice

getPkgid $originalOneApp
get_uninstall=`pkgcmd -u -n  $pkg_id -q`
getPkgid $originalLowerApp
get_uninstall=`pkgcmd -u -n  $pkg_id -q`

install_origin_xpk  $xpk_path/$originalOneApp.xpk $originalOneApp

#update valid xpk and check DB
update_negative_xpk $xpk_path/$originalLowerApp.xpk 2 $originalLowerApp

# because of the pass condition is fail to install the update_original_LowerMulti_tests xpk, so we must uninstall the update_original_versionOne_tests here
getPkgid $originalOneApp
get_uninstall=`pkgcmd -u -n  $pkg_id -q`

exit 0


text:
<?php
/**
 * The Events Calendar Advanced Functions for the Organizer Post Type
 *
 * These functions can be used to manipulate Organizer data. These functions may be useful for integration with other WordPress plugins and extended functionality.
 */

// Don't load directly
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

if ( class_exists( 'TribeEvents' ) ) {

	/**
	 * Create an Organizer
	 *
	 * $args accepts all the args that can be passed to wp_insert_post().
	 * In addition to that, the following args can be passed specifically
	 * for the process of creating an Organizer:
	 *
	 * - Organizer string - Title of the Organizer. (required)
	 * - Email string - Email address of the Organizer.
	 * - Website string - URL of the Organizer.
	 * - Phone string - Phone number for the Organizer.
	 *
	 * @param array $args Elements that make up post to insert.
	 *
	 * @return int ID of the Organizer that was created. False if insert failed.
	 * @link     http://codex.wordpress.org/Function_Reference/wp_insert_post
	 * @see      wp_insert_post()
	 * @category Organizer Functions
	 */
	function tribe_create_organizer( $args ) {
		$postId = TribeEventsAPI::createOrganizer( $args );

		return $postId;
	}

	/**
	 * Update an Organizer
	 *
	 * @param int   $postId ID of the Organizer to be modified.
	 * @param array $args   Args for updating the post. See {@link tribe_create_organizer()} for more info.
	 *
	 * @return int ID of the Organizer that was created. False if update failed.
	 * @link     http://codex.wordpress.org/Function_Reference/wp_update_post
	 * @see      wp_update_post()
	 * @see      tribe_create_organizer()
	 * @category Organizer Functions
	 */
	function tribe_update_organizer( $postId, $args ) {
		$postId = TribeEventsAPI::updateOrganizer( $postId, $args );

		return $postId;
	}

	/**
	 * Delete an Organizer
	 *
	 * @param int  $postId       ID of the Organizer to be deleted.
	 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
	 *
	 * @return bool false if delete failed.
	 * @link     http://codex.wordpress.org/Function_Reference/wp_delete_post
	 * @see      wp_delete_post()
	 * @category Organizer Functions
	 */
	function tribe_delete_organizer( $postId, $force_delete = false ) {
		$success = TribeEventsAPI::deleteOrganizer( $postId, $args );

		return $success;
	}

}
?>


text:
package ch.raffael.sangria.modules.shutdown;

import java.util.EventListener;

/**
 * @author Raffael Herzog
 */
public interface ShutdownListener extends EventListener {

    void prepareShutdown();

    void performShutdown();

    void postShutdown();

}


text:
/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#ifndef __MYGUI_SKIN_ITEM_H__
#define __MYGUI_SKIN_ITEM_H__

#include "MyGUI_Prerequest.h"
#include "MyGUI_LayerItem.h"
#include "MyGUI_ISubWidgetRect.h"
#include "MyGUI_ISubWidgetText.h"
#include "MyGUI_ResourceSkin.h"

namespace MyGUI
{

	class MYGUI_EXPORT SkinItem :
		public LayerItem
	{
	public:
		SkinItem();

		/** Get text sub widget or nullptr if no text sub widget */
		ISubWidgetText* getSubWidgetText();
		/** Get sub widget of first texture or nullptr if no sub widget with texture */
		ISubWidgetRect* getSubWidgetMain();

		void _setTextureName(const std::string& _texture);
		const std::string& _getTextureName() const;

	protected:
		void _createSkinItem(ResourceSkin* _info);
		void _deleteSkinItem();

		void _setSkinItemAlign(const IntSize& _size);
		void _setSkinItemVisible(bool _value);
		void _setSkinItemColour(const Colour& _value);
		void _setSkinItemAlpha(float _value);
		void _correctSkinItemView();
		void _updateSkinItemView();

		bool _setSkinItemState(const std::string& _state);
		void _setSubSkinVisible(bool _visible);

	private:
		// вектор всех детей сабскинов
		VectorSubWidget mSubSkinChild;
		// указатель на окно текста
		ISubWidgetText* mText;
		// указатель на первый не текстовой сабскин
		ISubWidgetRect* mMainSkin;
		// список всех стейтов
		MapWidgetStateInfo mStateInfo;

		std::string mTextureName;
		ITexture* mTexture;

		bool mSubSkinsVisible;
	};

} // namespace MyGUI

#endif // __MYGUI_SKIN_ITEM_H__


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Josh Yu | Start Here</title>

Josh Yu

I am glad our paths have crossed! I am a software developer interested in embedded systems, consumer products and computer security. I received both my M.S. and B.S. degrees in Electrical and Computer Engineering from Carnegie Mellon University.

I'm on Twitter @justjoshyu. You can also leave me a message down below.

LinkedIn

Travel + Photos

Bit and Pieces

Send me a note

			Website template provided by Doug Neiner / Chris Coyer. Blog built with Jekyll with the Galileo Theme by Rowan Oulton.


text:
var webdriverio = require('../../build/index');

var options = {
    desiredCapabilities: {
        browserName: 'chrome'
    }
};

var client = webdriverio.remote(options);

client
    .init()
    .url('https://news.ycombinator.com/')
    .selectorExecute('//div', function(inputs, message){
        return inputs.length + ' ' + message;
    }, 'divs on the page')
    .then(function(res){
        console.log(res);
    })
    .end();


text:
<?php

require('secure.inc.php');
if(!is_object($thisclient) || !$thisclient->isValid()) die('Access denied'); //Double check again.

if ($thisclient->isGuest())
    $_REQUEST['id'] = $thisclient->getTicketId();

require_once(INCLUDE_DIR.'class.ticket.php');
require_once(INCLUDE_DIR.'class.json.php');
$ticket=null;
if($_REQUEST['id']) {
    if (!($ticket = Ticket::lookup($_REQUEST['id']))) {
        $errors['err']=__('Unknown or invalid ticket ID.');
    } elseif(!$ticket->checkUserAccess($thisclient)) {
        $errors['err']=__('Unknown or invalid ticket ID.'); //Using generic message on purpose!
        $ticket=null;
    }
}

if (!$ticket && $thisclient->isGuest())
    Http::redirect('view.php');

$tform = TicketForm::objects()->one()->getForm();
$messageField = $tform->getField('message');
$attachments = $messageField->getWidget()->getAttachments();

//Process post...depends on $ticket object above.
if ($_POST && is_object($ticket) && $ticket->getId()) {
    $errors=array();
    switch(strtolower($_POST['a'])){
    case 'edit':
        if(!$ticket->checkUserAccess($thisclient) //double check perm again!
                || $thisclient->getId() != $ticket->getUserId())
            $errors['err']=__('Access Denied. Possibly invalid ticket ID');
        else {
            $forms=DynamicFormEntry::forTicket($ticket->getId());
            $changes = array();
            foreach ($forms as $form) {
                $form->filterFields(function($f) { return !$f->isStorable(); });
                $form->setSource($_POST);
                if (!$form->isValid())
                    $errors = array_merge($errors, $form->errors());
            }
        }
        if (!$errors) {
            foreach ($forms as $f) {
                $changes += $f->getChanges();
                $f->save();
            }
            if ($changes)
                $ticket->logEvent('edited', array('fields' => $changes));
            $_REQUEST['a'] = null; //Clear edit action - going back to view.
        }
        break;
    case 'reply':
        if(!$ticket->checkUserAccess($thisclient)) //double check perm again!
            $errors['err']=__('Access Denied. Possibly invalid ticket ID');

        $_POST['message'] = ThreadEntryBody::clean($_POST['message']);
        if (!$_POST['message'])
            $errors['message'] = __('Message required');

        if(!$errors) {
            //Everything checked out...do the magic.
            $vars = array(
                    'userId' => $thisclient->getId(),
                    'poster' => (string) $thisclient->getName(),
                    'message' => $_POST['message']
                    );
            $vars['cannedattachments'] = $attachments->getClean();
            if (isset($_POST['draft_id']))
                $vars['draft_id'] = $_POST['draft_id'];

            if(($msgid=$ticket->postMessage($vars, 'Web'))) {
                $msg=__('Message Posted Successfully');
                // Cleanup drafts for the ticket. If not closed, only clean
                // for this staff. Else clean all drafts for the ticket.
                Draft::deleteForNamespace('ticket.client.' . $ticket->getId());
                // Drop attachments
                $attachments->reset();
                $attachments->getForm()->setSource(array());
            } else {
                $errors['err'] = sprintf('%s %s',
                    __('Unable to post the message.'),
                    __('Correct any errors below and try again.'));
            }

        } elseif(!$errors['err']) {
            $errors['err'] = __('Correct any errors below and try again.');
        }
        break;
    default:
        $errors['err']=__('Unknown action');
    }
}
elseif (is_object($ticket) && $ticket->getId()) {
    switch(strtolower($_REQUEST['a'])) {
    case 'print':
        if (!$ticket || !$ticket->pdfExport($_REQUEST['psize']))
            $errors['err'] = __('Internal error: Unable to print to PDF');
        break;
    }
}

$nav->setActiveNav('tickets');
if($ticket && $ticket->checkUserAccess($thisclient)) {
    if (isset($_REQUEST['a']) && $_REQUEST['a'] == 'edit'
            && $ticket->hasClientEditableFields()) {
        $inc = 'edit.inc.php';
        if (!$forms) $forms=DynamicFormEntry::forTicket($ticket->getId());
        // Auto add new fields to the entries
        foreach ($forms as $f) {
            $f->filterFields(function($f) { return !$f->isStorable(); });
            $f->addMissingFields();
        }
    }
    else
        $inc='view.inc.php';
} elseif($thisclient->getNumTickets($thisclient->canSeeOrgTickets())) {
    $inc='tickets.inc.php';
} else {
    $nav->setActiveNav('new');
    $inc='open.inc.php';
}
include(CLIENTINC_DIR.'header.inc.php');
include(CLIENTINC_DIR.$inc);
print $tform->getMedia();
include(CLIENTINC_DIR.'footer.inc.php');
?>


text:
package com.intellij.refactoring.typeCook.deductive.resolver;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.typeCook.Settings;
import com.intellij.refactoring.typeCook.Util;
import com.intellij.refactoring.typeCook.deductive.PsiExtendedTypeVisitor;
import com.intellij.refactoring.typeCook.deductive.builder.Constraint;
import com.intellij.refactoring.typeCook.deductive.builder.ReductionSystem;
import com.intellij.refactoring.typeCook.deductive.builder.Subtype;
import com.intellij.util.graph.DFSTBuilder;
import com.intellij.util.graph.Graph;
import consulo.logging.Logger;
import consulo.util.collection.primitive.ints.IntList;
import consulo.util.collection.primitive.objects.ObjectIntMap;
import consulo.util.collection.primitive.objects.ObjectMaps;

import java.util.*;
import java.util.function.IntConsumer;

/**
 * @author db
 */
public class ResolverTree
{
	private static final Logger LOG = Logger.getInstance(ResolverTree.class);

	private ResolverTree[] mySons = new ResolverTree[0];
	private final BindingFactory myBindingFactory;
	private Binding myCurrentBinding;
	private final SolutionHolder mySolutions;
	private final Project myProject;
	private final ObjectIntMap<PsiTypeVariable> myBindingDegree; //How many times this type variable is bound in the system
	private final Settings mySettings;
	private boolean mySolutionFound = false;

	private HashSet<Constraint> myConstraints;

	public ResolverTree(final ReductionSystem system)
	{
		myBindingFactory = new BindingFactory(system);
		mySolutions = new SolutionHolder();
		myCurrentBinding = myBindingFactory.create();
		myConstraints = system.getConstraints();
		myProject = system.getProject();
		myBindingDegree = calculateDegree();
		mySettings = system.getSettings();

		reduceCyclicVariables();
	}

	private ResolverTree(final ResolverTree parent, final HashSet<Constraint> constraints, final Binding binding)
	{
		myBindingFactory = parent.myBindingFactory;
		myCurrentBinding = binding;
		mySolutions = parent.mySolutions;
		myConstraints = constraints;
		myProject = parent.myProject;
		myBindingDegree = calculateDegree();
		mySettings = parent.mySettings;
	}

	private static class PsiTypeVarCollector extends PsiExtendedTypeVisitor
	{
		final HashSet<PsiTypeVariable> mySet = new HashSet<PsiTypeVariable>();

		public Object visitTypeVariable(final PsiTypeVariable var)
		{
			mySet.add(var);

			return null;
		}

		public HashSet<PsiTypeVariable> getSet(final PsiType type)
		{
			type.accept(this);
			return mySet;
		}
	}

	private boolean isBoundElseWhere(final PsiTypeVariable var)
	{
		return myBindingDegree.getInt(var) != 1;
	}

	private boolean canBePruned(final Binding b)
	{
		if(mySettings.exhaustive())
		{
			return false;
		}
		for(final PsiTypeVariable var : b.getBoundVariables())
		{
			final PsiType type = b.apply(var);

			if(!(type instanceof PsiTypeVariable) && isBoundElseWhere(var))
			{
				return false;
			}
		}

		return true;
	}

	private ObjectIntMap<PsiTypeVariable> calculateDegree()
	{
		final ObjectIntMap<PsiTypeVariable> result = ObjectMaps.newObjectIntHashMap();

		for(final Constraint constr : myConstraints)
		{
			final PsiTypeVarCollector collector = new PsiTypeVarCollector();

			setDegree(collector.getSet(constr.getRight()), result);
		}

		return result;
	}

	private void setDegree(final HashSet<PsiTypeVariable> set, ObjectIntMap<PsiTypeVariable> result)
	{
		for(final PsiTypeVariable var : set)
		{
			if(result.containsKey(var))
			{
				int value = result.getInt(var);
				result.putInt(var, value + 1);
			}
		}
	}

	private HashSet<Constraint> apply(final Binding b)
	{
		final HashSet<Constraint> result = new HashSet<Constraint>();

		for(final Constraint constr : myConstraints)
		{
			result.add(constr.apply(b));
		}

		return result;
	}

	private HashSet<Constraint> apply(final Binding b, final HashSet<Constraint> additional)
	{
		final HashSet<Constraint> result = new HashSet<Constraint>();

		for(final Constraint constr : myConstraints)
		{
			result.add(constr.apply(b));
		}

		for(final Constraint constr : additional)
		{
			result.add(constr.apply(b));
		}

		return result;
	}

	private ResolverTree applyRule(final Binding b)
	{
		final Binding newBinding = b != null ? myCurrentBinding.compose(b) : null;

		return newBinding == null ? null : new ResolverTree(this, apply(b), newBinding);
	}

	private ResolverTree applyRule(final Binding b, final HashSet<Constraint> additional)
	{
		final Binding newBinding = b != null ? myCurrentBinding.compose(b) : null;

		return newBinding == null ? null : new ResolverTree(this, apply(b, additional), newBinding);
	}

	private void reduceCyclicVariables()
	{
		final HashSet<PsiTypeVariable> nodes = new HashSet<PsiTypeVariable>();
		final HashSet<Constraint> candidates = new HashSet<Constraint>();

		final HashMap<PsiTypeVariable, HashSet<PsiTypeVariable>> ins = new HashMap<PsiTypeVariable, HashSet<PsiTypeVariable>>();
		final HashMap<PsiTypeVariable, HashSet<PsiTypeVariable>> outs = new HashMap<PsiTypeVariable, HashSet<PsiTypeVariable>>();

		for(final Constraint constraint : myConstraints)
		{
			final PsiType left = constraint.getLeft();
			final PsiType right = constraint.getRight();

			if(left instanceof PsiTypeVariable && right instanceof PsiTypeVariable)
			{
				final PsiTypeVariable leftVar = (PsiTypeVariable) left;
				final PsiTypeVariable rightVar = (PsiTypeVariable) right;

				candidates.add(constraint);

				nodes.add(leftVar);
				nodes.add(rightVar);

				final HashSet<PsiTypeVariable> in = ins.get(leftVar);
				final HashSet<PsiTypeVariable> out = outs.get(rightVar);

				if(in == null)
				{
					final HashSet<PsiTypeVariable> newIn = new HashSet<PsiTypeVariable>();

					newIn.add(rightVar);

					ins.put(leftVar, newIn);
				}
				else
				{
					in.add(rightVar);
				}

				if(out == null)
				{
					final HashSet<PsiTypeVariable> newOut = new HashSet<PsiTypeVariable>();

					newOut.add(leftVar);

					outs.put(rightVar, newOut);
				}
				else
				{
					out.add(leftVar);
				}
			}
		}

		final DFSTBuilder<PsiTypeVariable> dfstBuilder = new DFSTBuilder<PsiTypeVariable>(new Graph<PsiTypeVariable>()
		{
			public Collection<PsiTypeVariable> getNodes()
			{
				return nodes;
			}

			public Iterator<PsiTypeVariable> getIn(final PsiTypeVariable n)
			{
				final HashSet<PsiTypeVariable> in = ins.get(n);

				if(in == null)
				{
					return new HashSet<PsiTypeVariable>().iterator();
				}

				return in.iterator();
			}

			public Iterator<PsiTypeVariable> getOut(final PsiTypeVariable n)
			{
				final HashSet<PsiTypeVariable> out = outs.get(n);

				if(out == null)
				{
					return new HashSet<PsiTypeVariable>().iterator();
				}

				return out.iterator();
			}

		});

		final IntList sccs = dfstBuilder.getSCCs();
		final HashMap<PsiTypeVariable, Integer> index = new HashMap<PsiTypeVariable, Integer>();

		sccs.forEach(new IntConsumer()
		{
			int myTNumber = 0;

			public void accept(int size)
			{
				for(int j = 0; j < size; j++)
				{
					index.put(dfstBuilder.getNodeByTNumber(myTNumber + j), myTNumber);
				}
				myTNumber += size;
			}
		});

		for(final Constraint constraint : candidates)
		{
			if(index.get(constraint.getLeft()).equals(index.get(constraint.getRight())))
			{
				myConstraints.remove(constraint);
			}
		}

		Binding binding = myBindingFactory.create();

		for(final PsiTypeVariable fromVar : index.keySet())
		{
			final PsiTypeVariable toVar = dfstBuilder.getNodeByNNumber(index.get(fromVar).intValue());

			if(!fromVar.equals(toVar))
			{
				binding = binding.compose(myBindingFactory.create(fromVar, toVar));

				if(binding == null)
				{
					break;
				}
			}
		}

		if(binding != null && binding.nonEmpty())
		{
			myCurrentBinding = myCurrentBinding.compose(binding);
			myConstraints = apply(binding);
		}
	}

	private void reduceTypeType(final Constraint constr)
	{
		final PsiType left = constr.getLeft();
		final PsiType right = constr.getRight();
		final HashSet<Constraint> addendumRise = new HashSet<Constraint>();
		final HashSet<Constraint> addendumSink = new HashSet<Constraint>();
		final HashSet<Constraint> addendumWcrd = new HashSet<Constraint>();

		int numSons = 0;
		Binding riseBinding = myBindingFactory.rise(left, right, addendumRise);
		if(riseBinding != null)
		{
			numSons++;
		}
		Binding sinkBinding = myBindingFactory.sink(left, right, addendumSink);
		if(sinkBinding != null)
		{
			numSons++;
		}
		Binding wcrdBinding = mySettings.cookToWildcards() ? myBindingFactory.riseWithWildcard(left, right, addendumWcrd) : null;
		if(wcrdBinding != null)
		{
			numSons++;
		}
		Binding omitBinding = null;

		if(mySettings.exhaustive())
		{
			final PsiClassType.ClassResolveResult rightResult = Util.resolveType(right);
			final PsiClassType.ClassResolveResult leftResult = Util.resolveType(left);

			final PsiClass rightClass = rightResult.getElement();
			final PsiClass leftClass = leftResult.getElement();

			if(rightClass != null && leftClass != null && rightClass.getManager().areElementsEquivalent(rightClass, leftClass))
			{
				if(PsiUtil.typeParametersIterator(rightClass).hasNext())
				{
					omitBinding = myBindingFactory.create();
					numSons++;
					for(PsiType type : rightResult.getSubstitutor().getSubstitutionMap().values())
					{
						if(!(type instanceof Bottom))
						{
							numSons--;
							omitBinding = null;
							break;
						}
					}
				}
			}
		}

		if(numSons == 0)
		{
			return;
		}

		if((riseBinding != null && sinkBinding != null && riseBinding.equals(sinkBinding)) || canBePruned(riseBinding))
		{
			numSons--;
			sinkBinding = null;
		}

		if(riseBinding != null && wcrdBinding != null && riseBinding.equals(wcrdBinding))
		{
			numSons--;
			wcrdBinding = null;
		}

		myConstraints.remove(constr);

		mySons = new ResolverTree[numSons];

		int n = 0;

		if(riseBinding != null)
		{
			mySons[n++] = applyRule(riseBinding, addendumRise);
		}

		if(wcrdBinding != null)
		{
			mySons[n++] = applyRule(wcrdBinding, addendumWcrd);
		}

		if(omitBinding != null)
		{
			mySons[n++] = applyRule(omitBinding, addendumWcrd);
		}

		if(sinkBinding != null)
		{
			mySons[n++] = applyRule(sinkBinding, addendumSink);
		}
	}

	private void fillTypeRange(final PsiType lowerBound,
							   final PsiType upperBound,
							   final HashSet<PsiType> holder)
	{
		if(lowerBound instanceof PsiClassType && upperBound instanceof PsiClassType)
		{
			final PsiClassType.ClassResolveResult resultLower = ((PsiClassType) lowerBound).resolveGenerics();
			final PsiClassType.ClassResolveResult resultUpper = ((PsiClassType) upperBound).resolveGenerics();

			final PsiClass lowerClass = resultLower.getElement();
			final PsiClass upperClass = resultUpper.getElement();

			if(lowerClass != null && upperClass != null && !lowerClass.equals(upperClass))
			{
				final PsiSubstitutor upperSubst = resultUpper.getSubstitutor();
				final PsiClass[] parents = upperClass.getSupers();
				final PsiElementFactory factory = JavaPsiFacade.getInstance(myProject).getElementFactory();

				for(final PsiClass parent : parents)
				{
					final PsiSubstitutor superSubstitutor = TypeConversionUtil.getClassSubstitutor(parent, upperClass, upperSubst);
					if(superSubstitutor != null)
					{
						final PsiClassType type = factory.createType(parent, superSubstitutor);
						holder.add(type);
						fillTypeRange(lowerBound, type, holder);
					}
				}
			}
		}
		else if(lowerBound instanceof PsiArrayType && upperBound instanceof PsiArrayType)
		{
			fillTypeRange(((PsiArrayType) lowerBound).getComponentType(), ((PsiArrayType) upperBound).getComponentType(), holder);
		}
	}

	private PsiType[] getTypeRange(final PsiType lowerBound, final PsiType upperBound)
	{
		final HashSet<PsiType> range = new HashSet<PsiType>();

		range.add(lowerBound);
		range.add(upperBound);

		fillTypeRange(lowerBound, upperBound, range);

		return range.toArray(new PsiType[]{});
	}

	private void reduceInterval(final Constraint left, final Constraint right)
	{
		final PsiType leftType = left.getLeft();
		final PsiType rightType = right.getRight();
		final PsiTypeVariable var = (PsiTypeVariable) left.getRight();

		if(leftType.equals(rightType))
		{
			final Binding binding = myBindingFactory.create(var, leftType);

			myConstraints.remove(left);
			myConstraints.remove(right);

			mySons = new ResolverTree[]{applyRule(binding)};

			return;
		}

		Binding riseBinding = myBindingFactory.rise(leftType, rightType, null);
		Binding sinkBinding = myBindingFactory.sink(leftType, rightType, null);

		int indicator = (riseBinding == null ? 0 : 1) + (sinkBinding == null ? 0 : 1);

		if(indicator == 0)
		{
			return;
		}
		else if((indicator == 2 && riseBinding.equals(sinkBinding)) || canBePruned(riseBinding))
		{
			indicator = 1;
			sinkBinding = null;
		}

		PsiType[] riseRange = PsiType.EMPTY_ARRAY;
		PsiType[] sinkRange = PsiType.EMPTY_ARRAY;

		if(riseBinding != null)
		{
			riseRange = getTypeRange(riseBinding.apply(rightType), riseBinding.apply(leftType));
		}

		if(sinkBinding != null)
		{
			sinkRange = getTypeRange(sinkBinding.apply(rightType), sinkBinding.apply(leftType));
		}

		if(riseRange.length + sinkRange.length > 0)
		{
			myConstraints.remove(left);
			myConstraints.remove(right);
		}

		mySons = new ResolverTree[riseRange.length + sinkRange.length];

		for(int i = 0; i < riseRange.length; i++)
		{
			final PsiType type = riseRange[i];

			mySons[i] = applyRule(riseBinding.compose(myBindingFactory.create(var, type)));
		}

		for(int i = 0; i < sinkRange.length; i++)
		{
			final PsiType type = sinkRange[i];

			mySons[i + riseRange.length] = applyRule(sinkBinding.compose(myBindingFactory.create(var, type)));
		}
	}

	private void reduce()
	{
		if(myConstraints.size() == 0)
		{
			return;
		}

		if(myCurrentBinding.isCyclic())
		{
			reduceCyclicVariables();
		}

		final HashMap<PsiTypeVariable, Constraint> myTypeVarConstraints = new HashMap<PsiTypeVariable, Constraint>();
		final HashMap<PsiTypeVariable, Constraint> myVarTypeConstraints = new HashMap<PsiTypeVariable, Constraint>();

		for(final Constraint constr : myConstraints)
		{
			final PsiType left = constr.getLeft();
			final PsiType right = constr.getRight();

			switch((left instanceof PsiTypeVariable ? 0 : 1) + (right instanceof PsiTypeVariable ? 0 : 2))
			{
				case 0:
					continue;

				case 1:
				{
					final Constraint c = myTypeVarConstraints.get(right);

					if(c == null)
					{
						final Constraint d = myVarTypeConstraints.get(right);

						if(d != null)
						{
							reduceInterval(constr, d);
							return;
						}

						myTypeVarConstraints.put((PsiTypeVariable) right, constr);
					}
					else
					{
						reduceTypeVar(constr, c);
						return;
					}
				}
				break;

				case 2:
				{
					final Constraint c = myVarTypeConstraints.get(left);

					if(c == null)
					{
						final Constraint d = myTypeVarConstraints.get(left);

						if(d != null)
						{
							reduceInterval(d, constr);
							return;
						}

						myVarTypeConstraints.put((PsiTypeVariable) left, constr);
					}
					else
					{
						reduceVarType(constr, c);
						return;
					}
					break;
				}

				case 3:
					reduceTypeType(constr);
					return;
			}
		}

		//T1 < a < b ... < T2
		{
			for(final Constraint constr : myConstraints)
			{
				final PsiType left = constr.getLeft();
				final PsiType right = constr.getRight();

				if(!(left instanceof PsiTypeVariable) && right instanceof PsiTypeVariable)
				{
					final HashSet<PsiTypeVariable> bound = new PsiTypeVarCollector().getSet(left);

					if(bound.contains(right))
					{
						myConstraints.remove(constr);
						mySons = new ResolverTree[]{applyRule(myBindingFactory.create(((PsiTypeVariable) right), Bottom.BOTTOM))};

						return;
					}

					final PsiManager manager = PsiManager.getInstance(myProject);
					final PsiType leftType = left instanceof PsiWildcardType ? ((PsiWildcardType) left).getBound() : left;
					final PsiType[] types = getTypeRange(PsiType.getJavaLangObject(manager, GlobalSearchScope.allScope(myProject)), leftType);

					mySons = new ResolverTree[types.length];

					if(types.length > 0)
					{
						myConstraints.remove(constr);
					}

					for(int i = 0; i < types.length; i++)
					{
						final PsiType type = types[i];
						mySons[i] = applyRule(myBindingFactory.create(((PsiTypeVariable) right), type));
					}

					return;
				}
			}
		}

		//T1 < a < b < ...
		{
			final HashSet<PsiTypeVariable> haveLeftBound = new HashSet<PsiTypeVariable>();

			Constraint target = null;
			final HashSet<PsiTypeVariable> boundVariables = new HashSet<PsiTypeVariable>();

			for(final Constraint constr : myConstraints)
			{
				final PsiType leftType = constr.getLeft();
				final PsiType rightType = constr.getRight();

				if(leftType instanceof PsiTypeVariable)
				{
					boundVariables.add((PsiTypeVariable) leftType);

					if(rightType instanceof PsiTypeVariable)
					{
						boundVariables.add((PsiTypeVariable) rightType);
						haveLeftBound.add(((PsiTypeVariable) rightType));
					}
					else if(!Util.bindsTypeVariables(rightType))
					{
						target = constr;
					}
				}
			}

			if(target == null)
			{
				if(mySettings.exhaustive())
				{
					for(final Constraint constr : myConstraints)
					{
						final PsiType left = constr.getLeft();
						final PsiType right = constr.getRight();

						PsiType[] range = null;
						PsiTypeVariable var = null;

						if(left instanceof PsiTypeVariable && !(right instanceof PsiTypeVariable))
						{
							range = getTypeRange(PsiType.getJavaLangObject(PsiManager.getInstance(myProject), GlobalSearchScope.allScope(myProject)),
									right);
							var = (PsiTypeVariable) left;
						}

						if(range == null && right instanceof PsiTypeVariable && !(left instanceof PsiTypeVariable))
						{
							range = new PsiType[]{right};
							var = (PsiTypeVariable) right;
						}

						if(range != null)
						{
							mySons = new ResolverTree[range.length];

							for(int i = 0; i < range.length; i++)
							{
								mySons[i] = applyRule(myBindingFactory.create(var, range[i]));
							}

							return;
						}
					}
				}

				Binding binding = myBindingFactory.create();

				for(final PsiTypeVariable var : myBindingFactory.getBoundVariables())
				{
					if(!myCurrentBinding.binds(var) && !boundVariables.contains(var))
					{
						binding = binding.compose(myBindingFactory.create(var, Bottom.BOTTOM));
					}
				}

				if(!binding.nonEmpty())
				{
					myConstraints.clear();
				}

				mySons = new ResolverTree[]{applyRule(binding)};
			}
			else
			{
				final PsiType type = target.getRight();
				final PsiTypeVariable var = (PsiTypeVariable) target.getLeft();

				final Binding binding =
						(haveLeftBound.contains(var) || type instanceof PsiWildcardType) || !mySettings.cookToWildcards()
								? myBindingFactory.create(var, type)
								: myBindingFactory.create(var, PsiWildcardType.createExtends(PsiManager.getInstance(myProject), type));

				myConstraints.remove(target);

				mySons = new ResolverTree[]{applyRule(binding)};
			}
		}
	}

	private void logSolution()
	{
		LOG.debug("Reduced system:");

		for(final Constraint constr : myConstraints)
		{
			LOG.debug(constr.toString());
		}

		LOG.debug("End of Reduced system.");
		LOG.debug("Reduced binding:");
		LOG.debug(myCurrentBinding.toString());
		LOG.debug("End of Reduced binding.");
	}

	private interface Reducer
	{
		LinkedList<Pair<PsiType, Binding>> unify(PsiType x, PsiType y);

		Constraint create(PsiTypeVariable var, PsiType type);

		PsiType getType(Constraint c);

		PsiTypeVariable getVar(Constraint c);
	}

	private void reduceTypeVar(final Constraint x, final Constraint y)
	{
		reduceSideVar(x, y, new Reducer()
		{
			public LinkedList<Pair<PsiType, Binding>> unify(final PsiType x, final PsiType y)
			{
				return myBindingFactory.intersect(x, y);
			}

			public Constraint create(final PsiTypeVariable var, final PsiType type)
			{
				return new Subtype(type, var);
			}

			public PsiType getType(final Constraint c)
			{
				return c.getLeft();
			}

			public PsiTypeVariable getVar(final Constraint c)
			{
				return (PsiTypeVariable) c.getRight();
			}
		});
	}

	private void reduceVarType(final Constraint x, final Constraint y)
	{
		reduceSideVar(x, y, new Reducer()
		{
			public LinkedList<Pair<PsiType, Binding>> unify(final PsiType x, final PsiType y)
			{
				return myBindingFactory.union(x, y);
			}

			public Constraint create(final PsiTypeVariable var, final PsiType type)
			{
				return new Subtype(var, type);
			}

			public PsiType getType(final Constraint c)
			{
				return c.getRight();
			}

			public PsiTypeVariable getVar(final Constraint c)
			{
				return (PsiTypeVariable) c.getLeft();
			}
		});
	}

	private void reduceSideVar(final Constraint x, final Constraint y, final Reducer reducer)
	{
		final PsiTypeVariable var = reducer.getVar(x);

		final PsiType xType = reducer.getType(x);
		final PsiType yType = reducer.getType(y);

		final LinkedList<Pair<PsiType, Binding>> union = reducer.unify(xType, yType);

		if(union.size() == 0)
		{
			return;
		}

		myConstraints.remove(x);
		myConstraints.remove(y);

		mySons = new ResolverTree[union.size()];
		int i = 0;

		Constraint prev = null;

		for(final Pair<PsiType, Binding> pair : union)
		{
			if(prev != null)
			{
				myConstraints.remove(prev);
			}

			prev = reducer.create(var, pair.getFirst());
			myConstraints.add(prev);

			mySons[i++] = applyRule(pair.getSecond());
		}
	}

	public void resolve()
	{
		reduce();

		if(mySons.length > 0)
		{
			for(int i = 0; i < mySons.length; i++)
			{

				if(mySons[i] != null)
				{
					mySons[i].resolve();
					if(!mySettings.exhaustive() && mySettings.cookToWildcards() && mySons[i].mySolutionFound)
					{
						break;
					}
					mySons[i] = null;
				}
			}
		}
		else
		{
			if(myConstraints.size() == 0)
			{
				logSolution();

				mySolutions.putSolution(myCurrentBinding);
				mySolutionFound = true;
			}
		}
	}

	public Binding getBestSolution()
	{
		return mySolutions.getBestSolution();
	}
}


text:
#define __FIL_BUILDING_CORE__
#include "core/filament.h"

typedef struct _pyfil_message {
    PyObject_HEAD

    FilWaiterList waiters;

    PyObject *result_or_exc_type;
    int is_exc;
    PyObject *exc_value; /* non NULL indicates exception */
    PyObject *exc_tb;
} PyFilMessage;

static PyFilMessage *_message_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
    PyFilMessage *self = (PyFilMessage *)type->tp_alloc(type, 0);

    if (self != NULL) {
        fil_waiterlist_init(self->waiters);
    }

    return self;
}

static int _message_init(PyFilMessage *self, PyObject *args, PyObject *kargs)
{
    /* Returns -1 on error */
    return 0;
}

static void _message_dealloc(PyFilMessage *self)
{
    Py_CLEAR(self->result_or_exc_type);
    Py_CLEAR(self->exc_value);
    Py_CLEAR(self->exc_tb);
    assert(fil_waiterlist_empty(self->waiters));

    PyObject_Del(self);
}

static PyObject *_message_result(PyFilMessage *self)
{
    Py_INCREF(self->result_or_exc_type);

    if (self->is_exc)
    {
        Py_XINCREF(self->exc_value);
        Py_XINCREF(self->exc_tb);
        PyErr_Restore(self->result_or_exc_type, self->exc_value,
                      self->exc_tb);
        return NULL;
    }

    return self->result_or_exc_type;
}

static PyObject *__message_wait(PyFilMessage *self, struct timespec *ts)
{
    int err;

    if (self->result_or_exc_type != NULL)
    {
        return _message_result(self);
    }

    err = fil_waiterlist_wait(self->waiters, ts, NULL);
    if (err)
    {
        return NULL;
    }

    return _message_result(self);
}

static int __message_send(PyFilMessage *self, PyObject *message)
{
    if (self->result_or_exc_type != NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Can only send once");
        return -1;
    }

    Py_INCREF(message);
    self->result_or_exc_type = message;

    fil_waiterlist_signal_all(self->waiters);

    return 0;
}

static int __message_send_exception(PyFilMessage *self, PyObject *exc_type,
                                    PyObject *exc_value, PyObject *exc_tb)
{
    if (self->result_or_exc_type != NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Can only send once");
        return -1;
    }

    self->is_exc = 1;
    Py_INCREF(exc_type);
    Py_XINCREF(exc_value);
    Py_XINCREF(exc_tb);

    self->result_or_exc_type = exc_type;
    self->exc_value = exc_value;
    self->exc_tb = exc_tb;

    fil_waiterlist_signal_all(self->waiters);

    return 0;
}

PyDoc_STRVAR(_message_wait_doc, "Wait!");
static PyObject *_message_wait(PyFilMessage *self, PyObject *args, PyObject *kwargs)
{
    /*
    struct timespec tsbuf;
    */
    struct timespec tsbuf;
    struct timespec *ts;
    PyObject *timeout = NULL;
    static char *keywords[] = {"timeout", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O:wait", keywords, &timeout))
    {
        return NULL;
    }

    if (fil_timespec_from_pyobj_interval(timeout, &tsbuf, &ts) < 0)
    {
        return NULL;
    }

    return __message_wait(self, ts);
}

PyDoc_STRVAR(_message_send_doc, "Send an object.");
static PyObject *_message_send(PyFilMessage *self, PyObject *message)
{
    if (__message_send(self, message) < 0)
    {
        return NULL;
    }
    Py_RETURN_NONE;
}

PyDoc_STRVAR(_message_send_exc_doc, "Tell a message to raise an exception.");
static PyObject *_message_send_exception(PyFilMessage *self, PyObject *args)
{
    PyObject *exc_type;
    PyObject *exc_value;
    PyObject *exc_tb;

    if (!PyArg_ParseTuple(args, "OOO:send_exception", &exc_type, &exc_value, &exc_tb))
        return NULL;

    if (__message_send_exception(self, exc_type, exc_value, exc_tb) < 0)
        return NULL;

    Py_RETURN_NONE;
}

static PyMethodDef _message_methods[] = {
    {"wait", (PyCFunction)_message_wait, METH_VARARGS|METH_KEYWORDS, _message_wait_doc},
    {"send", (PyCFunction)_message_send, METH_O, _message_send_doc},
    {"send_exception", (PyCFunction)_message_send_exception, METH_VARARGS, _message_send_exc_doc},
    { NULL, NULL }
};

static PyTypeObject _message_type = {
    PyVarObject_HEAD_INIT(0, 0)
    "_filament.Message",                        /* tp_name */
    sizeof(PyFilMessage),                       /* tp_basicsize */
    0,                                          /* tp_itemsize */
    (destructor)_message_dealloc,               /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_compare */
    0,                                          /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    PyObject_GenericGetAttr,                    /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    FIL_DEFAULT_TPFLAGS,                        /* tp_flags */
    0,                                          /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    _message_methods,                           /* tp_methods */
    0,                                          /* tp_members */
    0,                                          /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    (initproc)_message_init,                    /* tp_init */
    PyType_GenericAlloc,                        /* tp_alloc */
    (newfunc)_message_new,                      /* tp_new */
    PyObject_Del,                               /* tp_free */
    0,                                          /* tp_is_gc */
    0,                                          /* tp_bases */
    0,                                          /* tp_mro */
    0,                                          /* tp_cache */
    0,                                          /* tp_subclasses */
    0,                                          /* tp_weaklist */
    0,                                          /* tp_del */
    0,                                          /* tp_version_tag */
};

/****************/

PyFilMessage *fil_message_alloc(void)
{
    PyFilMessage *self;

    self = (PyFilMessage *)_message_new(&_message_type, NULL, NULL);
    if (self == NULL)
        return NULL;

    if (_message_init(self, NULL, NULL) < 0)
    {
        Py_DECREF(self);
        return NULL;
    }
    return self;
}

int fil_message_send(PyFilMessage *message, PyObject *result)
{
    return __message_send(message, result);
}

int fil_message_send_exception(PyFilMessage *message, PyObject *exc_type,
                               PyObject *exc_value, PyObject *exc_tb)
{
    return __message_send_exception(message, exc_type, exc_value, exc_tb);
}

PyObject *fil_message_wait(PyFilMessage *message, struct timespec *ts)
{
    return __message_wait(message, ts);
}

int fil_message_init(PyObject *module, PyFilCore_CAPIObject *capi)
{
    PyGreenlet_Import();
    if (PyType_Ready(&_message_type) < 0)
    {
        return -1;
    }

    Py_INCREF((PyObject *)&_message_type);
    if (PyModule_AddObject(module, "Message", (PyObject *)&_message_type) != 0)
    {
        Py_DECREF((PyObject *)&_message_type);
        return -1;
    }

    return 0;
}


text:
@echo off
set CL=/MP
premake5 --file=release.lua prepare --toolset=vs2015
pause
goto:eof


text:
layout: post
cover: 'assets/images/mountainous_lake.jpg'
title: Dynamic methods in Ruby
date:   2016-03-10 10:18:00
tags: ruby coding
subclass: 'post tag-test tag-content'
categories: 'casper'
navigation: True
logo: 'assets/images/logo.png'
---
There are three main ways to get Ruby to dynamically generate code for us. These are ways that Ruby will generate code for a method when it simply does not exist yet.

In our examples, we will be defining code in a Library class, which could have an ivar called `@books` as an array of Book objects.

###Send

The `#send` method is pretty much at the center of all our dynamic methods. It takes a symbol, and passes it to the calling class where it searches that class and all ancestors for that method to execute. For our example, lets say our Book objects have `attr_reader :title` enabled.

```
def sort_books_by(attr)
  @books.sort_by {|p| p.send(attr)}
end
```

And our `library` object would reference this method as:

`library.sort_books_by('title')`

###Define method

`#define_method` works by taking a block and defining that instance method on the receiver. So you are are creating as many methods are there are in the `books` array.

```
@books.first.instance_variables.each do |ivar|
  type = ivar[1..-1]
  define_method("sort_books_by_" + type) do
    @books.sort_by {|b| b.send(type)}
  end
end
```

If the above code was in a Libray class, you could call one of the defined methods as:

`library.sort_books_by_author`

###Method missing

Probably the most dangerous of way to dynamically create methods, Ruby looks for a method in the current class, then checks all of that classe's ancestors for the called method. If it does not find it, it calls `#method_missing` on the BasicObject class. We are redefining that method to allow our `sort_books_by_index` to be caught, and have the `index` attribute to be passed using `#send`.

```
def method_missing(method, *args)
  attr = method.split('_').last
  super unless self.books.first.respond_to?(attr)
  self.books.sort_by{ |b| b.send(attr) }
end
```

And the below code will run without any problems:

`library.sort_books_by_index`


text:
package com.yourblogz.busstop.example;

import org.junit.Test;

import junit.framework.TestCase;

public class DongGuanFileBuslineGeneratorTest extends TestCase {

    @Test
    public void testGenerator() {
//        DongGuanFileBuslineGenerator generator = new DongGuanFileBuslineGenerator("classpath:dongguan.bl");
//        generator.setConnectTimeout(10000).start();
    }
}


text:
import logging
import pprint
import json

import click

from kilda.probe.entity.message import create_list
from kilda.probe.messaging import send_with_context, \
    receive_with_context_async
from prettytable import PrettyTable

LOG = logging.getLogger(__name__)

def print_table(records):
    table = PrettyTable(['Topology', 'Component', 'Task ID'])
    for record in records:
        data = json.loads(record.value)
        payload = data['payload']
        LOG.debug(pprint.pformat(data))
        table.add_row(
            [payload['topology'], payload['component'], payload['task_id']])
    print(table)

@click.command(name='list')
@click.pass_obj
def list_command(ctx):
    message = create_list(ctx.correlation_id)
    LOG.debug('command = {}'.format(message.serialize()))

    with receive_with_context_async(ctx) as records:
        send_with_context(ctx, message.serialize())

    print_table(records)


text:
package es.tid.cosmos.common

import com.typesafe.config.{ConfigFactory, Config}

/**
 * Component that pulls configuration application.conf.
 */
trait ApplicationConfigComponent extends ConfigComponent {

  def config: Config = ConfigFactory.load()
}


text:
import { Component, OnInit, Input } from '@angular/core';
// #enddocregion import-input
// #docregion import-hero
import { Hero } from '../hero';
// #enddocregion import-hero

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
  // #docregion input-hero
  @Input() hero?: Hero;
  // #enddocregion input-hero

  constructor() { }

  ngOnInit() {
  }

}


text:
CREATE TABLE `b2c_account` (
  `account_id` varchar(31) NOT NULL COMMENT '用户id',
  `username` varchar(127) NOT NULL COMMENT '用户账户',
  `password` varchar(127) NOT NULL COMMENT '用户密码',
  `account_level` tinyint(11) NOT NULL COMMENT '用户昵称',
  `create_time` bigint(30) NOT NULL COMMENT '创建时间',
  `account_type` varchar(255) NOT NULL COMMENT '用户账户类型',
  `disabled` enum('false','true') NOT NULL DEFAULT 'false' COMMENT '是否失效',
  PRIMARY KEY (`account_id`),
  KEY `b2c_account_type` (`account_type`) USING BTREE COMMENT '账户类型'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--账户登录记录
CREATE TABLE `b2c_login_record` (
  `id` varchar(31) NOT NULL COMMENT '记录id',
  `account_id` varchar(31) NOT NULL COMMENT '登陆账户id',
  `account_type` tinyint(11) NOT NULL COMMENT '账户类型',
  `username` varchar(127) NOT NULL COMMENT '用户账户',
  `login_time` bigint(30) NOT NULL COMMENT '登录时间',
  PRIMARY KEY (`id`),
  KEY `b2c_login_record_account_id` (`account_id`) USING BTREE COMMENT '账户id',
  KEY `b2c_login_record_account_type` (`account_type`) USING BTREE COMMENT '账户类型'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--用户信息
CREATE TABLE `b2c_member` (
  `member_id` varchar(31) NOT NULL COMMENT '用户id',
  `nick_name` varchar(127) NOT NULL COMMENT '昵称',
  `mobile` varchar(127) NOT NULL COMMENT '电话',
  `real_name` varchar(127) NOT NULL COMMENT '真实姓名',
  `email` varchar(255) DEFAULT NULL COMMENT '邮件地址',
  `id_card` varchar(127) DEFAULT NULL COMMENT '身份证',
  `gender` enum('male','female') DEFAULT NULL COMMENT '性别',
  PRIMARY KEY (`member_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
What it does
------------

This plugin highlights all copies of a word that's currently selected, or,
optionally, highlights all copies of a word which currently has the insertion cursor upon it.

Additionally you may select all these words highlighted with `ALT+ENTER`, or also may append to the selection these words one by one similar to CTRL+D.

Install
-------

The easiest method to install would be using [Package Control](https://sublime.wbond.net/installation).
Ensure you have the latest by visiting that link, then open the command palette, type in
"Install Package", and search for "WordHighLight".

Alternatively, to manually install go to your Packages subdirectory under ST's data directory, where `X` is the ST version:

* Windows: %APPDATA%\Sublime Text X
* OS X: ~/Library/Application Support/Sublime Text X
* Linux: ~/.config/sublime-text-X
* Portable Installation: Sublime Text X/Data

Then clone this repository:

    git clone git://github.com/SublimeText/WordHighlight.git

That's it!

Options
-------

Under the Packages/WordHighlight sub-directory, edit the `Word Highlight.sublime-settings` file:

*	`"draw_outlined" : true`

	This makes the highlights be drawn as outlines instead of as filled
	highlights.
*	`"mark_occurrences_on_gutter" : true`

	If this comes true, icons will be used to mark all occurrences of selected words on the gutter bar.
	To customize the icons, the property "icon_type_on_gutter" is helpful.

*	`"icon_type_on_gutter" : dot`

	Normally, there are 4 valid types: dot, circle, bookmark and cross. If you want more, please
	have a look at folder "Theme - Default" under the "Packages" of Sublime Text (this can be done
    via menu "Preferences > Browse Packages").

*	`"highlight_when_selection_is_empty" : true`

	This makes words highlight when the insertion point is inside of them but when
	they're not actually selected.

*	`"highlight_word_under_cursor_when_selection_is_empty" : true`

	When the previous option is enabled, this makes the word under the cursor to gain highlighting

*	`"highlight_delay" : 0`

	This delays highlighting all occurrences using given time (in milliseconds) to let users move cursor
	around without being distracted with immediate highlights. Default value 0 means almost no delay.

*	`"show_word_highlight_status_bar_message" : true`

	This lets you toggle if you want a status bar message to show how many occurrences of the highlighted word there are.
	If you mix this with `"highlight_word_under_cursor_when_selection_is_empty": false` the occurrence number will not count word your cursor is on.

*	`"color_scope_name" : "wordhighlight"`

	Normally the color of the highlights is the same as the color of comments in
	your code. If you'd like to customize the color, add the below to your color
	scheme file and change EDF2E9 to whatever color you want, then change
	color_scope_name to the scope name in the block you added. If you'd like to
	specify a background color, uncomment the background part in the example below
	and set "draw_outlined" to "false").

			<dict>
				<key>name</key>
				<string>WordHighlight</string>
				<key>scope</key>
				<string>wordhighlight</string>
				<key>settings</key>
				<dict>
					<key>foreground</key>
					<string>#EDF2E9</string>

					<!--
					<key>background</key>
					<string>#16DD00</string>
					-->
				</dict>
			</dict>

* `"file_size_limit" : 4194304`

	Files bigger than this number will put WordHighlight on mode "highlight around view port" (a portion of the document)

* `"when_file_size_limit_search_this_num_of_characters" : 20000`

	When a file is bigger than the previous setting. This controls how many characters below and above the  view port you want to search for words to highlight

Selections
-------

By default it provides the key `ALT+ENTER` to select all the words highlighted by this package (you may highlight multiple words and then select all the instances)

It also has two functions with no keymap defined, to mimic `CTRL+D` and `CTRL+K, CTRL+D`. You may decided to use the alternatives by adding (upon customization) the following to the keymap file (`Packages/User/Default (Windows).sublime-keymap`):

```
	{ "keys": ["ctrl+enter"], "command": "select_highlighted_next_word", "context":
		[	{ "key": "selection_empty", "operator": "equal", "operand": false },
			{ "key": "setting.is_widget", "operator": "equal", "operand": false }
		]
	},
	{ "keys": ["ctrl+backspace"], "command": "select_highlighted_skip_last_word", "context":
		[	{ "key": "selection_empty", "operator": "equal", "operand": false },
			{ "key": "setting.is_widget", "operator": "equal", "operand": false }
		]
	},
```


text:
<root>
  <styles>
    <include src="s2r://panorama/styles/dotastyles.vcss_c" />
    <include src="file://{resources}/styles/containers/container.css" />
  </styles>
  <scripts>
    <include src="file://{resources}/scripts/containers/dota_inventory.js" />
  </scripts>
  <Panel class="InventoryOverlayRoot" hittest="false">
    <Panel id="stash_row" />
    <Panel id="inventory_items">
      <Panel id="inventory_row_1" />
      <Panel id="inventory_row_2" />
    </Panel>
  </Panel>
</root>


text:
module Guards where
import Data.Monoid
import Numeric

-- output
echo :: String -> String -> IO ()
echo msg_one msg_two = putStrLn $ msg_one `Data.Monoid.mappend` msg_two

-- see: http://www.whathealth.com/bmi/formula.html
calcBmi :: (RealFloat a) => a -> a -> a
calcBmi weight height = weight / (height/100)^2

-- see: http://stackoverflow.com/questions/1559590/haskell-force-floats-to-have-two-decimals
formatFloatN floatNum numOfDecimals = showFFloat (Just numOfDecimals) floatNum ""

-- based on your bmi, the function tells you off (omg!)
bmiTell :: (RealFloat a) => a -> String
bmiTell bmi
    | bmi <= 18.5 = "You're underweight, you emo you!"
    | bmi <= 25.0 = "You're supposedly normal. Pfft, I bet you're ugly!"
    | bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
    | otherwise   = "You're a whale, congratulations!"

max' :: (Ord a) => a -> a -> a
max' a b
    | a > b     = a
    | otherwise = b

main :: IO ()
main = do
       echo "calcBmi 72 182: " $ formatFloatN (calcBmi 72 182) 2
       echo "bmiTell calcBmi 72 182: " $ bmiTell $ calcBmi 72 182
       echo "max' 1 2: " $ show $ max' 1 2
       echo "max' 4 3: " $ show $ max' 4 3


text:
package com.fillumina.performance.producer;

import com.fillumina.performance.consumer.PerformanceConsumer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Encapsulates the consumers management (add, remove and call).
 *
 * @author Francesco Illuminati
 */
public class AbstractPerformanceProducer<T extends AbstractPerformanceProducer<T>>
        implements Serializable, PerformanceProducer, PerformanceConsumer {
    private static final long serialVersionUID = 1L;

    private final List<PerformanceConsumer> consumers;

    public AbstractPerformanceProducer() {
        this.consumers = new ArrayList<>();
    }

    public AbstractPerformanceProducer(final PerformanceConsumer... consumers) {
        this.consumers = new ArrayList<>();
        addPerformanceConsumer(consumers);
    }

    /**
     * A {@code null} argument and {@code null} array elements are ignored.
     */
    @SuppressWarnings("unchecked")
    @Override
    public T addPerformanceConsumer(
            final PerformanceConsumer... consumersArray) {
        if (consumersArray != null) {
            for (final PerformanceConsumer consumer: consumersArray) {
                if (consumer != null) {
                    consumers.add(consumer);
                }
            }
        }
        return (T) this;
    }

    /**
     * A {@code null} argument and {@code null} array's elements are ignored.
     */
    @SuppressWarnings("unchecked")
    @Override
    public T removePerformanceConsumer(
            final PerformanceConsumer... consumersArray) {
        if (consumersArray != null) {
            for (final PerformanceConsumer consumer: consumersArray) {
                if (consumer != null) {
                    consumers.remove(consumer);
                }
            }
        }
        return (T) this;
    }

    /**
     * Passes the {@link LoopPerformances} to all {@link PerformanceConsumer}s
     * in the same order they were added.
     */
    @Override
    public void consume(final String message,
            final LoopPerformances loopPerformances) {
        for (final PerformanceConsumer consumer: consumers) {
            consumer.consume(message, loopPerformances);
        }
    }
}


text:
package host

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestIsPhysicalInterface(t *testing.T) {
	assert.True(t, IsPhysicalInterface("i-am-not-a-network-interface"))
}


text:
package org.knowm.xchange.exceptions;

/** An exception indicating there the rate limit for making requests has been exceeded */
public class RateLimitExceededException extends ExchangeException {

  public RateLimitExceededException(String message) {
    super(message);
  }

  public RateLimitExceededException(Throwable e) {
    super(e);
  }

  public RateLimitExceededException(String message, Throwable cause) {
    super(message, cause);
  }

  public RateLimitExceededException() {
    super("Rate limit for making requests exceeded!");
  }
}


text:
- Fix text selection on sidebar (see #31)

## v0.1.7 (2015-09-09)

- Catch context menu events on sidebar (#23)
- Fix jQuery event handlers/Bootstrap controls on sidebar (#31)

## v0.1.6 (2014-08-23)

- Added support for [bower.io](http://bower.io/search/) (#21)

## v0.1.5 (2014-04-15)

- Added support for [component.io](http://component.io/) (#17, thanks @zedd45)
- Added `shown` and `hidden` events (#18)

## v0.1.4 (2014-02-16)

- Adjusted CSS for touch devices (#12)
- Converted build system to [gulp.js](http://gulpjs.com/)
- Added [TravisCI](http://travis-ci.org/) support for CI linting

## v0.1.3 (2014-02-06)

- Added `autoPan` option

## v0.1.2 (2013-12-28)

- Fixed broken `stopPropagation()` call (#2)
- Fire `show` and `hide` events on sidebar instances
- Added `getCloseButton()` method
- Several memory leaks related to event handlers fixed (#7)
  Thanks to Jerroyd Moore!

## v0.1.1 (2013-11-03)

- Fixed close button event handler (#1)

## v0.1.0 (2013-10-30)

- First official release
- `position` option
- `closeButton` option
- `getContainer()` and `setContent()` methods
- two more examples

## v0.0.0 (2013-10-29)

- Preview release


text:
package org.jboss.pnc.bpm.task;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.jboss.pnc.bpm.model.RepositoryCreationProcess;
import org.jboss.pnc.common.json.GlobalModuleGroup;
import org.jboss.pnc.enums.JobNotificationType;
import org.jboss.pnc.spi.exception.CoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.HashMap;

/**
 * @author Matej Lazar
 */
@ToString(callSuper = true)
public class RepositoryCreationTask {

    private static final Logger logger = LoggerFactory.getLogger(RepositoryCreationTask.class);

    @Getter
    @Setter
    @Deprecated
    private Integer taskId;

    /**
     * The RepositoryCreationRest.BuildConfigurationRest
     */
    private final RepositoryCreationProcess repositoryCreationProcess;
    private JobNotificationType jobType;
    private GlobalModuleGroup globalConfig;

    public RepositoryCreationTask(RepositoryCreationProcess repositoryCreationProcess) {
        this.repositoryCreationProcess = repositoryCreationProcess;
    }

    public Serializable getProcessParameters() throws CoreException {
        HashMap<String, Object> params = new HashMap<>();
        params.put("pncBaseUrl", globalConfig.getPncUrl());
        params.put("repourBaseUrl", globalConfig.getExternalRepourUrl());
        params.put("jobType", jobType.toString());
        params.put("taskData", repositoryCreationProcess);
        return params;
    }

    public void setJobType(JobNotificationType jobType) {
        this.jobType = jobType;
    }

    public void setGlobalConfig(GlobalModuleGroup globalConfig) {
        this.globalConfig = globalConfig;
    }

    public GlobalModuleGroup getGlobalConfig() {
        return globalConfig;
    }
}


text:
package org.apache.dubbo.rpc.filter;

import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.TimeoutCountDown;
import org.apache.dubbo.rpc.support.RpcUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.rpc.Constants.ASYNC_KEY;
import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;

/**
 * ContextFilter set the provider RpcContext with invoker, invocation, local port it is using and host for
 * current execution thread.
 *
 * @see RpcContext
 */
@Activate(group = PROVIDER, order = -10000)
public class ContextFilter implements Filter, Filter.Listener {

    private static final String TAG_KEY = "dubbo.tag";

    private static final Set<String> UNLOADING_KEYS;

    static {
        UNLOADING_KEYS = new HashSet<>(128);
        UNLOADING_KEYS.add(PATH_KEY);
        UNLOADING_KEYS.add(INTERFACE_KEY);
        UNLOADING_KEYS.add(GROUP_KEY);
        UNLOADING_KEYS.add(VERSION_KEY);
        UNLOADING_KEYS.add(DUBBO_VERSION_KEY);
        UNLOADING_KEYS.add(TOKEN_KEY);
        UNLOADING_KEYS.add(TIMEOUT_KEY);
        UNLOADING_KEYS.add(TIMEOUT_ATTACHMENT_KEY);

        // Remove async property to avoid being passed to the following invoke chain.
        UNLOADING_KEYS.add(ASYNC_KEY);
        UNLOADING_KEYS.add(TAG_KEY);
        UNLOADING_KEYS.add(FORCE_USE_TAG);
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Map<String, Object> attachments = invocation.getObjectAttachments();
        if (attachments != null) {
            Map<String, Object> newAttach = new HashMap<>(attachments.size());
            for (Map.Entry<String, Object> entry : attachments.entrySet()) {
                String key = entry.getKey();
                if (!UNLOADING_KEYS.contains(key)) {
                    newAttach.put(key, entry.getValue());
                }
            }
            attachments = newAttach;
        }

        RpcContext context = RpcContext.getContext();
        context.setInvoker(invoker)
                .setInvocation(invocation)
//                .setAttachments(attachments)  // merged from dubbox
                .setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort());
        String remoteApplication = (String) invocation.getAttachment(REMOTE_APPLICATION_KEY);
        if (StringUtils.isNotEmpty(remoteApplication)) {
            context.setRemoteApplicationName(remoteApplication);
        } else {
            context.setRemoteApplicationName((String) context.getAttachment(REMOTE_APPLICATION_KEY));
        }

        long timeout = RpcUtils.getTimeout(invocation, -1);
        if (timeout != -1) {
            context.set(TIME_COUNTDOWN_KEY, TimeoutCountDown.newCountDown(timeout, TimeUnit.MILLISECONDS));
        }

        // merged from dubbox
        // we may already added some attachments into RpcContext before this filter (e.g. in rest protocol)
        if (attachments != null) {
            if (context.getObjectAttachments() != null) {
                context.getObjectAttachments().putAll(attachments);
            } else {
                context.setObjectAttachments(attachments);
            }
        }

        if (invocation instanceof RpcInvocation) {
            ((RpcInvocation) invocation).setInvoker(invoker);
        }

        try {
            context.clearAfterEachInvoke(false);
            return invoker.invoke(invocation);
        } finally {
            context.clearAfterEachInvoke(true);
            // IMPORTANT! For async scenario, we must remove context from current thread, so we always create a new RpcContext for the next invoke for the same thread.
            RpcContext.removeContext(true);
            RpcContext.removeServerContext();
        }
    }

    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
        // pass attachments to result
        appResponse.addObjectAttachments(RpcContext.getServerContext().getObjectAttachments());
    }

    @Override
    public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {

    }
}