text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Authenticate to the Azure Service Management API | TripDubRoot</title>
	<meta name="description" content="So, back in the day we used x509 Certificates to authenticate to Azure's API. A year or so ago, Azure Active Directory became the defacto method of authentic...">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta http-equiv="X-Frame-Options" content="sameorigin">

	<link rel="stylesheet" href="/css/main.css">

	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

	<link rel="canonical" href="http://tripdubroot.com/azure/development/2015/07/01/authenticate-to-the-azure-service-management-api.html">

	<link rel="alternate" type="application/atom+xml" title="TripDubRoot" href="http://tripdubroot.com/feed.xml" />

	<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">

	<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,700italic,400italic" rel="stylesheet" type="text/css">

	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.css">

			TripDubRoot

					About

Authenticate to the Azure Service Management API

    July 1, 2015
     - {"login"=>"adminian", "email"=>"ian.philpot@microsoft.com", "display_name"=>"adminian", "first_name"=>"", "last_name"=>""}

So, back in the day we used x509 Certificates to authenticate to Azure's API. A year or so ago, Azure Active Directory became the defacto method of authentication. MSDN talks about it in the article: Authenticating Azure Resource Manager requests. From the article:

"All of the tasks that you do on resources using the Azure Resource Manager must be authenticated with Azure Active Directory. The easiest way to do this is to use PowerShell or Azure CLI. If you don't have access to PowerShell or Azure CLI, use the Azure Management Portal to set up authentication."

So yea… this isn't necessarily true. I worked with a couple of folks from support engineering to use the common authentication endpoint, so that you don't have to setup an application in Azure Active Directory and provide an application id.

I posted the code up to GitHub here: devdash/EzAzureMgmtApiAuth.

*Note: I can't claim this is supported in anyway… but it works great and has since the beginning.

The App

Basically it's a console app that asks you to login using your Azure credentials, asks you which subscription you'd like to use if you have more than one, and then finally prints out the choice you made. Simple, but I think powerful.

The Code

If you're anything like me, you'll open Git Shell and run:

git clone https://github.com/devdash/EzAzureMgmtApiAuth.git

Then open the SLN:

C:srcghEzAzureMgmtApiAuth [master]> .AzureRestPlayground.sln

Now normally once I have the solution open in Visual Studio and I see that it's a console app I start looking at: Program.cs. Below is the relevant code, the code that kicks off the authentication process…

[code lang="csharp"]

static void Main(string[] args)

{

     var azSubs = new AzureSubscriptions();

     var subList = azSubs.GetSubscriptionList();

     ...

}

[/code]

This code isn't rocket science. It initializes an object of type AzureSubscriptions and calls the method GetSubscriptionList. Let's go have a look at this method, particularly the second line:

[code lang="csharp"]

string token = AuthHelper.GetAuthorizationHeader();

[/code]

Off to look at the AuthHelper class and it's static method GetAuthorizationHeader…

[code lang="csharp"]

public static string GetAuthorizationHeader()

{

     AuthenticationResult result = null;

     var context = new AuthenticationContext("https://login.windows.net/common"); // tenant agnostic endpooint

     result = context.AcquireToken("https://management.core.windows.net/",

                                   "1950a258-227b-4e31-a9cf-717495945fc2", // Windows Azure Management API's Client ID

                                   new Uri("urn:ietf:wg:oauth:2.0:oob")); // standard redirect for native apps (console, desktop, mobile, etc)

     if (result == null)

     {

         throw new InvalidOperationException("Failed to obtain the JWT token");

     }

     return result.AccessToken;

}

[/code]

And here finally we se some good stuff. We got all this good ness by pulling in the ADAL nuget package and writing a couple of lines of code. We pulled the "Client ID" being passed to the AcquireToken method using fiddler and tracing a "promoted" app and borrowing it's ID. This is why my note above states that this probably isn't supported. From here we are returned a token. We construct our Auth Header in the HttpHelper class using this line of code:

[code lang="csharp"]

request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);

[/code]

Well that's that. Using the ADAL library and a common auth endpoint. Now any app can authenticate to any subscriptions service management API given the right credentials. Awesome!!

Please enable JavaScript to view the comments powered by Disqus.

Powered by Jekyll with Type Theme


text:
require 'spec_helper_min'
require 'support/helpers'

describe Carto::Api::MetricsController do
  include Warden::Test::Helpers
  include HelperMethods

  before(:all) do
    @user = create(:carto_user)
    @intruder = create(:carto_user)

    login(@user)
  end

  after(:all) do
    logout(@user)

    @user.destroy
    @instruder&.destroy
  end

  it 'should accept all existing events' do
    user_id = @user.id
    user_properties = { user_id: user_id, api_key: @user.api_key }

    Carto::Tracking::Events::Event.descendants.each do |event_class|
      next unless event_class.public_methods.include?(:new)

      event = event_class.new(user_id, user_id: user_id)

      event_class.any_instance.stubs(:report!)

      post_json metrics_url, name: event.name, properties: user_properties do |response|
        response.status.should eq 201
      end
    end
  end

  it 'should reject non existing events' do
    event_name = 'Everything was a lie'

    post_json metrics_url, name: event_name do |response|
      response.status.should eq 404
      response.body[:errors].should eq "Event not found: #{event_name}"
    end
  end

  describe 'validations' do
    it 'should require properties' do
      Carto::Tracking::Events::Event.descendants.each do |event_class|
        next unless event_class.public_methods.include?(:new)

        event = event_class.new(@user.id, {})

        unless event.required_properties.empty?
          post_json metrics_url, name: event.name, properties: {} do |response|
            response.status.should eq 422
            response.body[:errors].should eq "#{event.name} is missing the following properties: #{event.required_properties.join(', ')}"
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using FlatRedBall.IO;
namespace BuildServerUploaderConsole.Processes
{
    public class ZipFrbdk : ProcessStep
    {
        static string mDestinationDirectory = DirectoryHelper.ReleaseDirectory;
        static string mFrbdkZipFile = "FRBDK";

        public static string DestinationFile
        {
            get
            {

                return FileManager.Standardize(
                    mDestinationDirectory + mFrbdkZipFile + ".zip");

            }
        }

        public ZipFrbdk(IResults results)
            : base(
                @"Zip copied FRBDK files", results)
        { }

        public override void ExecuteStep()
        {
            string frbdkForZipDirectory = DirectoryHelper.ReleaseDirectory + @"\FRBDK For Zip\";

            ZipHelper.CreateZip(Results, mDestinationDirectory, frbdkForZipDirectory, mFrbdkZipFile);
        }
    }
}


text:
package com.dev4free.devbuy.devbuyWeb.serviceImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.dev4free.devbuy.devbuyWeb.mapper.UserMapper;
import com.dev4free.devbuy.devbuyWeb.poCustom.UserCustom;
import com.dev4free.devbuy.devbuyWeb.service.UserService;

/**
 *
 * @author syd
 * @date:2016年12月5日
 * @project_name:devbuy_web
 * @description:
 */
public class UserServiceImpl implements UserService{

	@Autowired
	UserMapper userMapper;

	public List<UserCustom> queryAllUsers() {
		// TODO Auto-generated method stub
		return userMapper.queryAllUsers();
	}

	public void deleteUserByIds(String[] userIds) {
		// TODO Auto-generated method stub
		userMapper.deleteUserByIds(userIds);
	}

	public UserCustom queryUsersByPrimarykey(String userId) {
		// TODO Auto-generated method stub
		return userMapper.queryUsersByPrimarykey(userId);
	}

}


text:
import { defineComponent, PropType } from 'vue'
import * as common from 'schema-based-json-editor'
import { Select2 } from "select2-vue-component"
import { Icon } from './icon'
import { Optional } from './optional'
import { Description } from './description'
import { numberEditorTemplateHtml } from './variables'

export const NumberEditor = defineComponent({
  render: numberEditorTemplateHtml,
  components: {
    icon: Icon,
    optional: Optional,
    description: Description,
    select2: Select2,
  },
  props: {
    schema: {
      type: Object as PropType<common.NumberSchema>,
      required: true,
    },
    initialValue: Number,
    title: [String, Number],
    theme: {
      type: Object as PropType<common.Theme>,
      required: true,
    },
    icon: {
      type: Object as PropType<common.Icon>,
      requried: true,
    },
    locale: {
      type: Object as PropType<common.Locale>,
      required: true,
    },
    readonly: Boolean,
    required: Boolean,
    hasDeleteButton: {
      type: Boolean,
      required: true,
    },
    noSelect2: {
      type: Boolean,
      required: true,
    },
  },
  data: () => {
    return {
      value: 0 as number | undefined,
      errorMessage: '' as string | undefined,
      buttonGroupStyle: common.buttonGroupStyleString,
    }
  },
  beforeMount() {
    this.value = common.getDefaultValue(this.required, this.schema, this.initialValue) as number
    this.validate()
    this.$emit('update-value', { value: this.value, isValid: !this.errorMessage })
  },
  computed: {
    useInput(): boolean | undefined {
      return this.value !== undefined && (this.schema.enum === undefined || this.isReadOnly)
    },
    useSelect(): boolean {
      return this.value !== undefined && (this.schema.enum !== undefined && !this.isReadOnly)
    },
    useSelect2Component(): boolean {
      return this.useSelect && !this.noSelect2 && this.schema.format !== 'select' && this.schema.format !== 'radiobox'
    },
    useSelectComponent(): boolean {
      return this.useSelect && (this.schema.format === 'select' || this.noSelect2)
    },
    useRadioBoxComponent(): boolean {
      return this.useSelect && this.schema.format === 'radiobox'
    },
    isReadOnly(): boolean | undefined {
      return this.readonly || this.schema.readonly
    },
    hasDeleteButtonFunction(): boolean {
      return this.hasDeleteButton && !this.isReadOnly
    },
    titleToShow(): string {
      return common.getTitle(this.title, this.schema.title)
    },
    options(): {
      value: string | number;
      label: string | number;
    }[] {
      return common.getOptions(this.schema)
    },
    className(): string {
      const rowClass = this.errorMessage ? this.theme.errorRow : this.theme.row
      return this.schema.className ? rowClass + ' ' + this.schema.className : rowClass
    },
    step(): number | "any" | undefined {
      return common.getNumberStep(this.schema)
    },
  },
  methods: {
    onChange(e: { target: { value: string } }) {
      this.value = this.schema.type === 'integer' ? common.toInteger(e.target.value) : common.toNumber(e.target.value)
      this.validate()
      this.$emit('update-value', { value: this.value, isValid: !this.errorMessage })
    },
    updateSelection(value: number) {
      this.value = value
      this.validate()
      this.$emit('update-value', { value: this.value, isValid: !this.errorMessage })
    },
    toggleOptional() {
      this.value = common.toggleOptional(this.value, this.schema, this.initialValue) as number | undefined
      this.validate()
      this.$emit('update-value', { value: this.value, isValid: !this.errorMessage })
    },
    validate() {
      this.errorMessage = common.getErrorMessageOfNumber(this.value, this.schema, this.locale)
    },
  }
})


text:
/*

package org.apache.taverna.workflow.edits;

import java.net.URI;

import org.apache.taverna.scufl2.api.container.WorkflowBundle;

public class UpdateDataflowInternalIdentifierEdit extends
		AbstractEdit<WorkflowBundle> {
	private URI newId;
	private URI oldId;

	public UpdateDataflowInternalIdentifierEdit(WorkflowBundle dataflow,
			URI newId) {
		super(dataflow);
		this.newId = newId;
		this.oldId = dataflow.getGlobalBaseURI();
	}

	@Override
	protected void doEditAction(WorkflowBundle dataflow) {
		dataflow.setGlobalBaseURI(newId);
	}

	@Override
	protected void undoEditAction(WorkflowBundle dataflow) {
		dataflow.setGlobalBaseURI(oldId);
	}
}


text:
import Vector from './vector.js'
import EPSILON from 'number-epsilon'

Vector.equals = function (one, another) {
  return one.equals(another)
}

Vector.prototype.equals = function (vector) {
  return (
    Math.abs(this.x - vector.x) < EPSILON &&
    Math.abs(this.y - vector.y) < EPSILON
  )
}

Vector.compare = function (one, another) {
  return one.compare(another)
}

Vector.prototype.compare = function (vector) {
  var thisMagnitude = this.magnitude()
  var vectorMagnitude = vector.magnitude()
  return (thisMagnitude > vectorMagnitude) - (vectorMagnitude > thisMagnitude)
}

export default Vector


text: Hello world example


text:
package org.onosproject.driver.extensions;

import org.onlab.packet.VlanId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.behaviour.ExtensionSelectorResolver;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.flow.criteria.ExtensionSelector;
import org.onosproject.net.flow.criteria.ExtensionSelectorType;
import org.onosproject.net.flow.criteria.ExtensionSelectorType.ExtensionSelectorTypes;
import org.onosproject.openflow.controller.ExtensionSelectorInterpreter;
import org.projectfloodlight.openflow.protocol.OFFactory;
import org.projectfloodlight.openflow.protocol.match.MatchField;
import org.projectfloodlight.openflow.protocol.oxm.OFOxm;
import org.projectfloodlight.openflow.protocol.oxm.OFOxmOfdpaActsetOutput;
import org.projectfloodlight.openflow.protocol.oxm.OFOxmOfdpaAllowVlanTranslation;
import org.projectfloodlight.openflow.protocol.oxm.OFOxmVlanVid;
import org.projectfloodlight.openflow.protocol.oxm.OFOxmVlanVidMasked;
import org.projectfloodlight.openflow.types.OFVlanVidMatch;
import org.projectfloodlight.openflow.types.U32;
import org.projectfloodlight.openflow.types.U8;
import org.projectfloodlight.openflow.types.VlanVid;

/**
 * Interpreter for OFDPA OpenFlow selector extensions.
 */
public class OfdpaExtensionSelectorInterpreter extends AbstractHandlerBehaviour
        implements ExtensionSelectorInterpreter, ExtensionSelectorResolver {

    @Override
    public boolean supported(ExtensionSelectorType extensionSelectorType) {
        if (extensionSelectorType.equals(ExtensionSelectorTypes.OFDPA_MATCH_VLAN_VID.type())) {
            return true;
        } else if (extensionSelectorType.equals(
                ExtensionSelectorType.ExtensionSelectorTypes.OFDPA_MATCH_ACTSET_OUTPUT.type())) {
            return true;
        } else if (extensionSelectorType.equals(
                ExtensionSelectorTypes.OFDPA_MATCH_ALLOW_VLAN_TRANSLATION.type())) {
            return true;
        }
        return false;
    }

    @Override
    public OFOxm<?> mapSelector(OFFactory factory, ExtensionSelector extensionSelector) {
        ExtensionSelectorType type = extensionSelector.type();
        if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.OFDPA_MATCH_VLAN_VID.type())) {
            VlanId vlanId = ((OfdpaMatchVlanVid) extensionSelector).vlanId();
            // Special VLAN 0x0000/0x1FFF required by OFDPA
            if (vlanId.equals(VlanId.NONE)) {
                OFVlanVidMatch vid = OFVlanVidMatch.ofRawVid((short) 0x0000);
                OFVlanVidMatch mask = OFVlanVidMatch.ofRawVid((short) 0x1FFF);
                return factory.oxms().vlanVidMasked(vid, mask);
            // Normal case
            } else if (vlanId.equals(VlanId.ANY)) {
                return factory.oxms().vlanVidMasked(OFVlanVidMatch.PRESENT, OFVlanVidMatch.PRESENT);
            } else {
                return factory.oxms().vlanVid(OFVlanVidMatch.ofVlanVid(VlanVid.ofVlan(vlanId.toShort())));
            }
        } else if (type.equals(
                ExtensionSelectorType.ExtensionSelectorTypes.OFDPA_MATCH_ACTSET_OUTPUT.type())) {
            PortNumber port = ((OfdpaMatchActsetOutput) extensionSelector).port();
            return factory.oxms().ofdpaActsetOutput(U32.of(port.toLong()));
        } else if (type.equals(ExtensionSelectorTypes.OFDPA_MATCH_ALLOW_VLAN_TRANSLATION.type())) {

            Short allowVlanTranslation =
                    ((OfdpaMatchAllowVlanTranslation) extensionSelector).allowVlanTranslation();

            return factory.oxms().ofdpaAllowVlanTranslation(U8.of(allowVlanTranslation));
        }
        throw new UnsupportedOperationException(
                "Unexpected ExtensionSelector: " + extensionSelector.toString());
    }

    @Override
    public ExtensionSelector mapOxm(OFOxm<?> oxm) {
        VlanId vlanId;

        if (oxm.getMatchField().equals(MatchField.VLAN_VID)) {
            if (oxm.isMasked()) {
                OFVlanVidMatch vid = ((OFOxmVlanVidMasked) oxm).getValue();
                OFVlanVidMatch mask = ((OFOxmVlanVidMasked) oxm).getMask();

                if (vid.equals(OFVlanVidMatch.ofRawVid((short) 0))) {
                    vlanId = VlanId.NONE;
                } else if (vid.equals(OFVlanVidMatch.PRESENT) &&
                        mask.equals(OFVlanVidMatch.PRESENT)) {
                    vlanId = VlanId.ANY;
                } else {
                    vlanId = VlanId.vlanId(vid.getVlan());
                }
            } else {
                OFVlanVidMatch vid = ((OFOxmVlanVid) oxm).getValue();

                if (!vid.isPresentBitSet()) {
                    vlanId = VlanId.NONE;
                } else {
                    vlanId = VlanId.vlanId(vid.getVlan());
                }
            }
            return new OfdpaMatchVlanVid(vlanId);
        } else if (oxm.getMatchField().equals(MatchField.OFDPA_ACTSET_OUTPUT)) {
            U32 portNumberU32 = ((OFOxmOfdpaActsetOutput) oxm).getValue();
            PortNumber portNumber = PortNumber.portNumber(portNumberU32.getValue());
            return new OfdpaMatchActsetOutput(portNumber);
        } else if (oxm.getMatchField().equals(MatchField.OFDPA_ALLOW_VLAN_TRANSLATION)) {
            U8 value = ((OFOxmOfdpaAllowVlanTranslation) oxm).getValue();
            return new OfdpaMatchAllowVlanTranslation(value.getValue());
        }
        throw new UnsupportedOperationException(
                "Unexpected OXM: " + oxm.toString());
    }

    @Override
    public ExtensionSelector getExtensionSelector(ExtensionSelectorType type) {
        if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.OFDPA_MATCH_VLAN_VID.type())) {
            return new OfdpaMatchVlanVid();
        } else if (type.equals(ExtensionSelectorType.ExtensionSelectorTypes.OFDPA_MATCH_ACTSET_OUTPUT.type())) {
            return new OfdpaMatchActsetOutput();
        } else if (type.equals(ExtensionSelectorTypes.OFDPA_MATCH_ALLOW_VLAN_TRANSLATION.type())) {
            return new OfdpaMatchAllowVlanTranslation();
        }
        throw new UnsupportedOperationException(
                "Driver does not support extension type " + type.toString());
    }
}


text:
package sample.table.datamodel.gen;
//template:dataModel.vm
import org.codehaus.jackson.annotate.JsonProperty;

public class 	LtPlan
{
    /**
     * プランID
     */
 	@JsonProperty("planId")
	private String planId;
    /**
     * 取扱者ID
     */
 	@JsonProperty("toriatsukaishaId")
	private String toriatsukaishaId;
    /**
     * 顧客ID
     */
 	@JsonProperty("kokyakuId")
	private String kokyakuId;
    /**
     * 分析種別
     */
 	@JsonProperty("bunsekiShubetsu")
	private String bunsekiShubetsu;
    /**
     * コメント
     */
 	@JsonProperty("comment")
	private String comment;
    /**
     * プラン作成日時
     */
 	@JsonProperty("planCreated")
	private String planCreated;
    /**
     * プラン更新日時
     */
 	@JsonProperty("planUpdated")
	private String planUpdated;
    /**
     * 役員報酬引下額
     */
 	@JsonProperty("amountOfExecutiveCompensationReduction")
	private String amountOfExecutiveCompensationReduction;
    /**
     * 保険種類
     */
 	@JsonProperty("insuranceKind")
	private String insuranceKind;

	/**
	 * プランIDを取得します。
	 * @return プランID
	 */
	public String getPlanId() {
		return planId;
	}

	/**
	 * プランIDを設定します。
	 * @param planId プランID
	 */
	public void setPlanId(String planId) {
		this.planId = planId;
	}

	/**
	 * 取扱者IDを取得します。
	 * @return 取扱者ID
	 */
	public String getToriatsukaishaId() {
		return toriatsukaishaId;
	}

	/**
	 * 取扱者IDを設定します。
	 * @param toriatsukaishaId 取扱者ID
	 */
	public void setToriatsukaishaId(String toriatsukaishaId) {
		this.toriatsukaishaId = toriatsukaishaId;
	}

	/**
	 * 顧客IDを取得します。
	 * @return 顧客ID
	 */
	public String getKokyakuId() {
		return kokyakuId;
	}

	/**
	 * 顧客IDを設定します。
	 * @param kokyakuId 顧客ID
	 */
	public void setKokyakuId(String kokyakuId) {
		this.kokyakuId = kokyakuId;
	}

	/**
	 * 分析種別を取得します。
	 * @return 分析種別
	 */
	public String getBunsekiShubetsu() {
		return bunsekiShubetsu;
	}

	/**
	 * 分析種別を設定します。
	 * @param bunsekiShubetsu 分析種別
	 */
	public void setBunsekiShubetsu(String bunsekiShubetsu) {
		this.bunsekiShubetsu = bunsekiShubetsu;
	}

	/**
	 * コメントを取得します。
	 * @return コメント
	 */
	public String getComment() {
		return comment;
	}

	/**
	 * コメントを設定します。
	 * @param comment コメント
	 */
	public void setComment(String comment) {
		this.comment = comment;
	}

	/**
	 * プラン作成日時を取得します。
	 * @return プラン作成日時
	 */
	public String getPlanCreated() {
		return planCreated;
	}

	/**
	 * プラン作成日時を設定します。
	 * @param planCreated プラン作成日時
	 */
	public void setPlanCreated(String planCreated) {
		this.planCreated = planCreated;
	}

	/**
	 * プラン更新日時を取得します。
	 * @return プラン更新日時
	 */
	public String getPlanUpdated() {
		return planUpdated;
	}

	/**
	 * プラン更新日時を設定します。
	 * @param planUpdated プラン更新日時
	 */
	public void setPlanUpdated(String planUpdated) {
		this.planUpdated = planUpdated;
	}

	/**
	 * 役員報酬引下額を取得します。
	 * @return 役員報酬引下額
	 */
	public String getAmountOfExecutiveCompensationReduction() {
		return amountOfExecutiveCompensationReduction;
	}

	/**
	 * 役員報酬引下額を設定します。
	 * @param amountOfExecutiveCompensationReduction 役員報酬引下額
	 */
	public void setAmountOfExecutiveCompensationReduction(String amountOfExecutiveCompensationReduction) {
		this.amountOfExecutiveCompensationReduction = amountOfExecutiveCompensationReduction;
	}

	/**
	 * 保険種類を取得します。
	 * @return 保険種類
	 */
	public String getInsuranceKind() {
		return insuranceKind;
	}

	/**
	 * 保険種類を設定します。
	 * @param insuranceKind 保険種類
	 */
	public void setInsuranceKind(String insuranceKind) {
		this.insuranceKind = insuranceKind;
	}
}


text:
package com.intellij.codeInsight.daemon.impl.actions;

import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInspection.JavaSuppressionUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiModifierList;
import com.intellij.psi.PsiModifierListOwner;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author ven
 */
public class SuppressParameterFix extends AbstractBatchSuppressByNoInspectionCommentFix {
  private String myAlternativeID;

  public SuppressParameterFix(@NotNull HighlightDisplayKey key) {
    this(key.getID());
    myAlternativeID = HighlightDisplayKey.getAlternativeID(key);
  }

  public SuppressParameterFix(String ID) {
    super(ID, false);
  }

  @Override
  @NotNull
  public String getText() {
    return "Suppress for parameter";
  }

  @Nullable
  @Override
  public PsiElement getContainer(PsiElement context) {
    PsiParameter psiParameter = PsiTreeUtil.getParentOfType(context, PsiParameter.class, false);
    return psiParameter != null && psiParameter.getTypeElement() != null && JavaSuppressionUtil.canHave15Suppressions(psiParameter) ? psiParameter : null;
  }

  @Override
  protected boolean replaceSuppressionComments(PsiElement container) {
    return false;
  }

  @Override
  protected void createSuppression(@NotNull Project project, @NotNull PsiElement element, @NotNull PsiElement cont)
    throws IncorrectOperationException {
    PsiModifierListOwner container = (PsiModifierListOwner)cont;
    final PsiModifierList modifierList = container.getModifierList();
    if (modifierList != null) {
      final String id = SuppressFix.getID(container, myAlternativeID);
      JavaSuppressionUtil.addSuppressAnnotation(project, container, container, id != null ? id : myID);
    }
  }
}


text:
class PDF::Reader
  # A value object that represents one or more consecutive characters on a page.
  class TextRun
    include Comparable

    attr_reader :x, :y, :width, :font_size, :text

    alias :to_s :text

    def initialize(x, y, width, font_size, text)
      @x = x
      @y = y
      @width = width
      @font_size = font_size.floor
      @text = text
    end

    # Allows collections of TextRun objects to be sorted. They will be sorted
    # in order of their position on a cartesian plain - Top Left to Bottom Right
    def <=>(other)
      if x == other.x && y == other.y
        0
      elsif y < other.y
        1
      elsif y > other.y
        -1
      elsif x < other.x
        -1
      elsif x > other.x
        1
      end
    end

    def endx
      @endx ||= x + width
    end

    def mean_character_width
      @width / character_count
    end

    def mergable?(other)
      y.to_i == other.y.to_i && font_size == other.font_size && mergable_range.include?(other.x)
    end

    def +(other)
      raise ArgumentError, "#{other} cannot be merged with this run" unless mergable?(other)

      if (other.x - endx) <( font_size * 0.2)
        TextRun.new(x, y, other.endx - x, font_size, text + other.text)
      else
        TextRun.new(x, y, other.endx - x, font_size, "#{text} #{other.text}")
      end
    end

    def inspect
      "#{text} w:#{width} f:#{font_size} @#{x},#{y}"
    end

    private

    def mergable_range
      @mergable_range ||= Range.new(endx - 3, endx + font_size)
    end

    def character_count
      if @text.size == 1
        1.0
      elsif @text.respond_to?(:bytesize)
        # M17N aware VM
        # so we can trust String#size to return a character count
        @text.size.to_f
      else
        text.unpack("U*").size.to_f
      end
    end
  end
end


text:
//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SqLiteEntities
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class TaxesEntities : DbContext
    {
        public TaxesEntities()
            : base("name=TaxesEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<Tax> Taxes { get; set; }
    }
}


text:
call castor.bat POReadAllCastor filename 1
call castor.bat POReadAllCastor filename 2
call castor.bat POReadAllCastor filename 3
call castor.bat POReadAllCastor filename 4
call castor.bat POReadAllCastor filename 5
call castor.bat POReadAllCastor filename 6
call castor.bat POReadAllCastor filename 7
call castor.bat POReadOneCastor filename 1
call castor.bat POReadOneCastor filename 2
call castor.bat POReadOneCastor filename 3
call castor.bat POReadOneCastor filename 4
call castor.bat POReadOneCastor filename 5
call castor.bat POReadOneCastor filename 6
call castor.bat POReadOneCastor filename 7
call castor.bat POGetCustNameCastor filename 1
call castor.bat POGetCustNameCastor filename 2
call castor.bat POGetCustNameCastor filename 3
call castor.bat POGetCustNameCastor filename 4
call castor.bat POGetCustNameCastor filename 5
call castor.bat POGetCustNameCastor filename 6
call castor.bat POGetCustNameCastor filename 7
call castor.bat POGetSetGetCustNameCastor filename 1
call castor.bat POGetSetGetCustNameCastor filename 2
call castor.bat POGetSetGetCustNameCastor filename 3
call castor.bat POGetSetGetCustNameCastor filename 4
call castor.bat POGetSetGetCustNameCastor filename 5
call castor.bat POGetSetGetCustNameCastor filename 6
call castor.bat POGetSetGetCustNameCastor filename 7
call castor.bat POTopDownCastor
call castor.bat POTopDownSaveCastor
call castor.bat PrimTopDownCastor
call castor.bat NPrimTopDownCastor


text:
[![Build Status](https://travis-ci.org/Vidada-Project/vidada-server.svg?branch=master)](https://travis-ci.org/Vidada-Project/vidada-server)
[![Docker Pulls](https://img.shields.io/docker/pulls/elderbyte/vidada-server.svg)](https://hub.docker.com/r/elderbyte/vidada-server/)

Vidada Server
=======

Vidada is a cloud first media manager, supporting a wide array of storage backends - from local storage up to S3 / minio blobstores.

The media blobs are indexed by a smart hash and metadata is linked only to the hash. This leaves the underling data with maximum flexibility.

Organisation is exclusively based on a powerful tag system, which supports even complex queries.

Vidada acts as a media server and streams your media over the network (HTTP/S). The Vidada Server provides a REST API which is used by the web-app and can be used by 3th parties.

## Preview

# Configuration & Env Variables

You can configure the most important aspects using ENV variables. They are valid using the jar directly or the docker container.

| Env               |      Description                  |  Hint              |
|-------------------|:---------------------------------:|-------------------:|
| PORT              |  Url of Eureka server             | 80                 |
| DATASOURCE_URL    |  jdbc connection string           | (local by default) |
| EUREKA_URL        |  Url of Eureka discovery server   | (optional)         |

## Technology stack

* The backend is written with Java 9, Spring Boot 2, JPA / Hibernate  (supporting a wide array of relational dbs: H2 and PosgresSQL)
* The frontend is written with Angular 5 and Angular Material 5
* The actual media data is accessed/managed using object storage protocols such as S3.

Source Code is freely available at https://github.com/Vidada-Project under the Apache License.

2017


text:
import sys
from setuptools import setup, find_packages

classifiers = [
    "Development Status :: 4 - Beta",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: Apache Software License",
    "Programming Language :: Python",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 2.7",
    "Programming Language :: Python :: 3.2",
    "Programming Language :: Python :: 3.3",
    "Topic :: Database",
    "Topic :: Software Development",
    "Topic :: Software Development :: Testing",
]

install_requires = ['pg8000 >= 1.10']
if sys.version_info < (2, 7):
    install_requires.append('unittest2')

setup(
    name='testing.postgresql',
    version='1.2.1',
    description='automatically setups a postgresql instance in a temporary " \
        "directory, and destroys it after testing',
    long_description=open('README.rst').read(),
    classifiers=classifiers,
    keywords=[],
    author='Takeshi Komiya',
    author_email='i.tkomiya at gmail.com',
    url='https://github.com/tk0miya/testing.postgresql',
    license='Apache License 2.0',
    packages=find_packages('src'),
    package_dir={'': 'src'},
    package_data={'': ['buildout.cfg']},
    include_package_data=True,
    install_requires=install_requires,
    extras_require=dict(
        testing=[
            'nose',
            'psycopg2',
            'SQLAlchemy',
        ],
    ),
    test_suite='nose.collector',
)


text:
<?php

namespace Magento\Newsletter\Model\ResourceModel\Problem;

use Magento\Customer\Api\CustomerRepositoryInterface as CustomerRepository;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Newsletter problems collection
 *
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * True when subscribers info joined
     *
     * @var bool
     */
    protected $_subscribersInfoJoinedFlag = false;

    /**
     * True when grouped
     *
     * @var bool
     */
    protected $_problemGrouped = false;

    /**
     * Customer collection factory
     *
     * @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory
     */
    protected $_customerCollectionFactory;

    /**
     * @var CustomerRepository
     */
    protected $customerRepository;

    /**
     * Customer View Helper
     *
     * @var \Magento\Customer\Helper\View
     */
    protected $_customerView;

    /**
     * checks if customer data is loaded
     *
     * @var boolean
     */
    protected $_loadCustomersDataFlag = false;

    /**
     * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param CustomerRepository $customerRepository
     * @param \Magento\Customer\Helper\View $customerView
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource
     */
    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactory $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        CustomerRepository $customerRepository,
        \Magento\Customer\Helper\View $customerView,
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
        $this->customerRepository = $customerRepository;
        $this->_customerView = $customerView;
    }

    /**
     * Define resource model and model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('Magento\Newsletter\Model\Problem', 'Magento\Newsletter\Model\ResourceModel\Problem');
    }

    /**
     * Set customer loaded status
     *
     * @param bool $flag
     * @return $this
     */
    protected function _setIsLoaded($flag = true)
    {
        if (!$flag) {
            $this->_loadCustomersDataFlag = false;
        }
        return parent::_setIsLoaded($flag);
    }
    /**
     * Adds subscribers info
     *
     * @return $this
     */
    public function addSubscriberInfo()
    {
        $this->getSelect()->joinLeft(
            ['subscriber' => $this->getTable('newsletter_subscriber')],
            'main_table.subscriber_id = subscriber.subscriber_id',
            ['subscriber_email', 'customer_id', 'subscriber_status']
        );
        $this->addFilterToMap('subscriber_id', 'main_table.subscriber_id');
        $this->_subscribersInfoJoinedFlag = true;

        return $this;
    }

    /**
     * Adds queue info
     *
     * @return $this
     */
    public function addQueueInfo()
    {
        $this->getSelect()->joinLeft(
            ['queue' => $this->getTable('newsletter_queue')],
            'main_table.queue_id = queue.queue_id',
            ['queue_start_at', 'queue_finish_at']
        )->joinLeft(
            ['template' => $this->getTable('newsletter_template')],
            'queue.template_id = template.template_id',
            ['template_subject', 'template_code', 'template_sender_name', 'template_sender_email']
        );
        return $this;
    }

    /**
     * Loads customers info to collection
     *
     * @return void
     */
    protected function _addCustomersData()
    {
        if ($this->_loadCustomersDataFlag) {
            return;
        }
        $this->_loadCustomersDataFlag = true;
        foreach ($this->getItems() as $item) {
            if ($item->getCustomerId()) {
                $customerId = $item->getCustomerId();
                try {
                    $customer = $this->customerRepository->getById($customerId);
                    $problems = $this->getItemsByColumnValue('customer_id', $customerId);
                    $customerName = $this->_customerView->getCustomerName($customer);
                    foreach ($problems as $problem) {
                        $problem->setCustomerName($customerName)
                            ->setCustomerFirstName($customer->getFirstName())
                            ->setCustomerLastName($customer->getLastName());
                    }
                } catch (NoSuchEntityException $e) {
                    // do nothing if customer is not found by id
                }
            }
        }
    }

    /**
     * Loads collecion and adds customers info
     *
     * @param bool $printQuery
     * @param bool $logQuery
     * @return $this
     */
    public function load($printQuery = false, $logQuery = false)
    {
        parent::load($printQuery, $logQuery);
        if ($this->_subscribersInfoJoinedFlag) {
            $this->_addCustomersData();
        }
        return $this;
    }
}


text:
/**
 * Gives a single-word string description of the (native) type of a value, returning such
 * answers as 'Object', 'Number', 'Array', or 'Null'.  Does not attempt to distinguish user
 * Object types any further, reporting them all as 'Object'.
 *
 * @func
 * @memberOf R
 * @category Type
 * @sig (* -> {*}) -> String
 * @param {*} val The value to test
 * @return {String}
 * @example
 *
 *      R.type({}); //=> "Object"
 *      R.type(1); //=> "Number"
 *      R.type(false); //=> "Boolean"
 *      R.type('s'); //=> "String"
 *      R.type(null); //=> "Null"
 *      R.type([]); //=> "Array"
 *      R.type(/[A-z]/); //=> "RegExp"
 */
module.exports = function type(val) {
    return val === null      ? 'Null'      :
           val === undefined ? 'Undefined' :
           Object.prototype.toString.call(val).slice(8, -1);
};


text:
"""ICU (LEGO Island Configuration Utility).

Created 2015 Triangle717
<http://le717.github.io/>

Licensed under The MIT License
<http://opensource.org/licenses/MIT/>

"""

from src.core.utils import Utils
from src.registry.registry import Registry
from src.ui.responses import Responses

class ICU:

    def __init__(self):
        registry = Registry()
        self.firstLoad = []
        self._rmap = {}
        self._map = {
            "3D Device Name": "d3d",
            "3DSound": "sound",
            "Back Buffers in Video RAM": "draw3d",
            "Display Bit Depth": "color",
            "Draw Cursor": "cursor",
            "Flip Surfaces": "surface",
            "Full Screen": "windowed",
            "Island Quality": "model",
            "Island Texture": "texture",
            "Music": "music",
            "savepath": "savepath",
            "UseJoystick": "joystick",
            "Wide View Angle": "wideangle"
        }

        # Create a reverse conversion map
        for k, v in self._map.items():
            self._rmap[v] = k

        # Get the initial registry values
        for key in registry.readAll():
            self.firstLoad.append(
                Utils.makeAction(self.convertKeyNames(key[0]), key[1])
            )

        # Connect the buttons to the queue
        self.responses = Responses(self)

    def convertKeyNames(self, name):
        if name in self._map:
            return self._map[name]
        elif name in self._rmap:
            return self._rmap[name]


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.tagmanager.model;

/**
 * Response to quick previewing a workspace.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Tag Manager API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class QuickPreviewResponse extends com.google.api.client.json.GenericJson {

  /**
   * Were there compiler errors or not.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean compilerError;

  /**
   * The quick previewed container version.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ContainerVersion containerVersion;

  /**
   * Whether quick previewing failed when syncing the workspace to the latest container version.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private SyncStatus syncStatus;

  /**
   * Were there compiler errors or not.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getCompilerError() {
    return compilerError;
  }

  /**
   * Were there compiler errors or not.
   * @param compilerError compilerError or {@code null} for none
   */
  public QuickPreviewResponse setCompilerError(java.lang.Boolean compilerError) {
    this.compilerError = compilerError;
    return this;
  }

  /**
   * The quick previewed container version.
   * @return value or {@code null} for none
   */
  public ContainerVersion getContainerVersion() {
    return containerVersion;
  }

  /**
   * The quick previewed container version.
   * @param containerVersion containerVersion or {@code null} for none
   */
  public QuickPreviewResponse setContainerVersion(ContainerVersion containerVersion) {
    this.containerVersion = containerVersion;
    return this;
  }

  /**
   * Whether quick previewing failed when syncing the workspace to the latest container version.
   * @return value or {@code null} for none
   */
  public SyncStatus getSyncStatus() {
    return syncStatus;
  }

  /**
   * Whether quick previewing failed when syncing the workspace to the latest container version.
   * @param syncStatus syncStatus or {@code null} for none
   */
  public QuickPreviewResponse setSyncStatus(SyncStatus syncStatus) {
    this.syncStatus = syncStatus;
    return this;
  }

  @Override
  public QuickPreviewResponse set(String fieldName, Object value) {
    return (QuickPreviewResponse) super.set(fieldName, value);
  }

  @Override
  public QuickPreviewResponse clone() {
    return (QuickPreviewResponse) super.clone();
  }

}


text:
var path = require('path');
var Q = require('q');

function addTest(scope, name, callback) {
    scope[name] = function(test) {

        var that = this;

        if (typeof callback !== "function") {
            test.ok(false, "Not implemented");
            test.done();
            return;
        }

        Q()
        .then(function() {
            return callback.call(that);
        })
        .then(function() {
            test.done();
        }, function(err) {
            that.promiseErrorHandlers = that.promiseErrorHandlers || [];
            that.promiseErrorHandlers.reduce(Q.when, Q())
            .fin(function() {
                test.ok(false,err);
                test.done();
            });
        });
    };
}

function NodeunitBuilder(outer, name) {

    outer[name] = this;
}

NodeunitBuilder.prototype.test = function(name, callback) {

    addTest(this,name,callback);
};

function createTestScopeExtender (name, setUp, tearDown) {

    return function(outer) {
        var inner = new NodeunitBuilder(outer, name);

        inner.setUp = setUp;
        inner.tearDown = tearDown;

        return inner;
    };
}

module.exports = NodeunitBuilder;
module.exports.createTestScopeExtender = createTestScopeExtender;
module.exports.addTest = addTest;


text:
#include "itreestateremove.h"

/* Perform a removal operation on a tree state */
bool ITreeStateRemove::execute()
{
    // Remember the old selections and highlight
    prevHighlighted = tree->getHighlighted();
    prevSelected = tree->getSelectionList();

    // Perform the remove call
    remove();

    removedNodes = tree->popRecentNodes();
    oldParents = tree->popRecentParents();

    // Verify that the removed nodes match up evenly with the old parents. If
    // something goes wrong, we know we have an issue with the remove() call
    if (removedNodes.size() != oldParents.size())
    {
        qDebug() << "ERROR: nodes not correctly matched with parents";
        return false;
    }

    // Check if anything changed
    if (removedNodes.size() == 0 || oldParents.size() == 0)
        return false;

    tree->redraw();
    return true;
}

/* Puts the detached nodes back into place */
void ITreeStateRemove::undo()
{
    // Move the nodes back into place
    QList<TreeNode*>::iterator nodeIt = removedNodes.begin();
    QList<TreeNode*>::iterator parentIt = oldParents.begin();

    for (; nodeIt != removedNodes.end(); ++nodeIt, ++parentIt)
        TreeNode::move((*nodeIt),(*parentIt));

    // Reselect and rehighlight
    tree->highlightSpecific(prevHighlighted);
    for (TreeNode* node : prevSelected)
         tree->selectSpecific(node);

    tree->redraw();
}


text:
package org.wso2.carbon.bpel.b4p.coordination.context;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.addressing.EndpointReference;
import org.wso2.carbon.bpel.b4p.coordination.context.impl.SimpleCoordinationContext;

/**
 * This is a representation of the ws-c coordination context.
 */
public interface CoordinationContext {

    public abstract String getIdentifier();

    public abstract void setIdentifier(String identifier);

    public abstract String getCoordinationType();

    public abstract void setCoordinationType(String coordinationType);

    public abstract long getExpires();

    public abstract void setExpires(long expires);

    public abstract EndpointReference getRegistrationService();

    public abstract void getRegistrationService(EndpointReference endpointReference);

    public abstract OMElement toOM();

    /**
     * Factory method for creating Coordination Context.
     */
    public static final class Factory {
        public static CoordinationContext newContext(OMElement context) {
            return new SimpleCoordinationContext(context);
        }

        public static CoordinationContext newContext(String identifier, String coordinationType, EndpointReference
                endpointReference) {
            return new SimpleCoordinationContext(identifier, coordinationType, endpointReference);
        }

        public static CoordinationContext newContext(String identifier, String coordinationType, long expires,
                                                     EndpointReference endpointReference) {
            return new SimpleCoordinationContext(identifier, coordinationType, expires, endpointReference);
        }
    }

}


text:
#
# Script.ps1
#

$file_path ="D:\My Documents\GitHub\KcvExtension\KcvExtension(Release)";
$copy_path ="D:\My Documents\GitHub\KcvExtension\KcvExtension(Release)\All";
function copy-to($path, $filename) {
	Copy-Item "$file_path\$path\$filename" "$copy_path\$filename"
}
function copy-to-kcv($name){
	copy-to $name "AMing.KcvExtension.$name.dll"
}

copy-to-kcv "Core"
copy-to-kcv "Debug"
copy-to-kcv "Settings"
copy-to-kcv "Logger"
copy-to-kcv "Keys"


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

/*----------------------------------------------------------------
    Copyright (C) 2017 Senparc

    文件名:Post.cs
    文件功能描述:Post

    创建标识:Senparc - 20150211

    修改标识:Senparc - 20150303
    修改描述:整理接口

    修改标识:Senparc - 20150312
    修改描述:开放代理请求超时时间

    修改标识:zhanghao-kooboo - 20150316
    修改描述:增加

    修改标识:Senparc - 20150407
    修改描述:发起Post请求方法修改,为了上传永久视频素材

    修改标识:Senparc - 20160720
    修改描述:增加了PostFileGetJsonAsync的异步方法(与之前的方法多一个参数)

    修改标识:Senparc - 20170409
    修改描述:v4.11.9 修改Download方法
----------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.Entities;
using Senparc.Weixin.Exceptions;

#if NET35 || NET40 || NET45
using System.Web.Script.Serialization;
#endif
#if !NET35 && !NET40
using System.Net.Http;
#endif

namespace Senparc.Weixin.HttpUtility
{
    /// <summary>
    /// Post 请求处理
    /// </summary>
    public static class Post
    {
        /// <summary>
        /// 获取Post结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="returnText"></param>
        /// <returns></returns>
        public static T GetResult<T>(string returnText)
        {
#if NET35 || NET40 || NET45
            JavaScriptSerializer js = new JavaScriptSerializer();
#endif

            if (returnText.Contains("errcode"))
            {
                //可能发生错误
#if NET35 || NET40 || NET45
                WxJsonResult errorResult = js.Deserialize<WxJsonResult>(returnText);
#else
                WxJsonResult errorResult = Newtonsoft.Json.JsonConvert.DeserializeObject<WxJsonResult>(returnText);
#endif
                if (errorResult.errcode != ReturnCode.请求成功)
                {
                    //发生错误
                    throw new ErrorJsonResultException(
                        string.Format("微信Post请求发生错误!错误代码:{0},说明:{1}",
                                      (int)errorResult.errcode,
                                      errorResult.errmsg),
                        null, errorResult);
                }
            }

#if NET35 || NET40 || NET45
            T result = js.Deserialize<T>(returnText);
#else
            T result = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(returnText);
#endif

            //TODO:加入特殊情况下的回调处理

            return result;
        }

        #region 同步方法

        /// <summary>
        /// 发起Post请求,可上传文件
        /// </summary>
        /// <typeparam name="T">返回数据类型(Json对应的实体)</typeparam>
        /// <param name="url">请求Url</param>
        /// <param name="cookieContainer">CookieContainer,如果不需要则设为null</param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax"></param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <param name="fileDictionary"></param>
        /// <param name="postDataDictionary"></param>
        /// <returns></returns>
        public static T PostFileGetJson<T>(string url, CookieContainer cookieContainer = null, Dictionary<string, string> fileDictionary = null, Dictionary<string, string> postDataDictionary = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                postDataDictionary.FillFormDataStream(ms); //填充formData
                string returnText = RequestUtility.HttpPost(url, cookieContainer, ms, fileDictionary, null, encoding, cer, useAjax, timeOut);
                var result = GetResult<T>(returnText);
                return result;
            }
        }

        /// <summary>
        /// 发起Post请求
        /// </summary>
        /// <typeparam name="T">返回数据类型(Json对应的实体)</typeparam>
        /// <param name="url">请求Url</param>
        /// <param name="cookieContainer">CookieContainer,如果不需要则设为null</param>
        /// <param name="fileStream">文件流</param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax">是否使用Ajax请求</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <param name="checkValidationResult">验证服务器证书回调自动验证</param>
        /// <returns></returns>
        public static T PostGetJson<T>(string url, CookieContainer cookieContainer = null, Stream fileStream = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT, bool checkValidationResult = false)
        {
            string returnText = RequestUtility.HttpPost(url, cookieContainer, fileStream, null, null, encoding, cer, useAjax, timeOut, checkValidationResult);

            WeixinTrace.SendApiLog(url, returnText);

            var result = GetResult<T>(returnText);
            return result;
        }

        /// <summary>
        /// PostGetJson
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="formData"></param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax">是否使用Ajax请求</param>
        /// <param name="timeOut"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T PostGetJson<T>(string url, CookieContainer cookieContainer = null, Dictionary<string, string> formData = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT)
        {
            string returnText = RequestUtility.HttpPost(url, cookieContainer, formData, encoding, cer, useAjax, timeOut);
            var result = GetResult<T>(returnText);
            return result;
        }

        /// <summary>
        /// 使用Post方法上传数据并下载文件或结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="stream"></param>
        public static void Download(string url, string data, Stream stream)
        {
#if NET35 || NET40 || NET45
            WebClient wc = new WebClient();
            var file = wc.UploadData(url, "POST", Encoding.UTF8.GetBytes(string.IsNullOrEmpty(data) ? "" : data));
            stream.Write(file, 0, file.Length);

            //foreach (var b in file)
            //{
            //    stream.WriteByte(b);
            //}
#else
            HttpClient httpClient = new HttpClient();
            HttpContent hc = new StringContent(data);
            var ht = httpClient.PostAsync(url, hc);
            ht.Wait();
            var ft = ht.Result.Content.ReadAsByteArrayAsync();
            ft.Wait();
            var file = ft.Result;
            stream.Write(file, 0, file.Length);
#endif

        }

        #endregion

#if !NET35 && !NET40
        #region 异步方法

        /// <summary>
        /// 【异步方法】发起Post请求,可上传文件
        /// </summary>
        /// <typeparam name="T">返回数据类型(Json对应的实体)</typeparam>
        /// <param name="url">请求Url</param>
        /// <param name="cookieContainer">CookieContainer,如果不需要则设为null</param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax">是否使用Ajax请求</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <param name="fileDictionary"></param>
        /// <param name="postDataDictionary"></param>
        /// <returns></returns>
        public static async Task<T> PostFileGetJsonAsync<T>(string url, CookieContainer cookieContainer = null, Dictionary<string, string> fileDictionary = null, Dictionary<string, string> postDataDictionary = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                postDataDictionary.FillFormDataStream(ms); //填充formData
                string returnText = await RequestUtility.HttpPostAsync(url, cookieContainer, ms, fileDictionary, null, encoding, cer, useAjax, timeOut);
                var result = GetResult<T>(returnText);
                return result;
            }
        }

        /// <summary>
        /// 【异步方法】PostGetJson的异步版本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="fileStream"></param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax">是否使用Ajax请求</param>
        /// <param name="timeOut"></param>
        /// <param name="checkValidationResult"></param>
        /// <returns></returns>
        public static async Task<T> PostGetJsonAsync<T>(string url, CookieContainer cookieContainer = null, Stream fileStream = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT, bool checkValidationResult = false)
        {
            string returnText = await RequestUtility.HttpPostAsync(url, cookieContainer, fileStream, null, null, encoding, cer, useAjax, timeOut, checkValidationResult);

            WeixinTrace.SendApiLog(url, returnText);

            var result = GetResult<T>(returnText);
            return result;
        }

        /// <summary>
        /// PostGetJson的异步版本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="formData"></param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="useAjax">是否使用Ajax请求</param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static async Task<T> PostGetJsonAsync<T>(string url, CookieContainer cookieContainer = null, Dictionary<string, string> formData = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT)
        {
            string returnText = await RequestUtility.HttpPostAsync(url, cookieContainer, formData, encoding, cer, useAjax, timeOut);
            var result = GetResult<T>(returnText);
            return result;
        }

        ///// <summary>
        ///// PostFileGetJson的异步版本
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="url"></param>
        ///// <param name="cookieContainer"></param>
        ///// <param name="fileDictionary"></param>
        ///// <param name="encoding"></param>
        ///// <param name="cer">证书,如果不需要则保留null</param>
        ///// <param name="timeOut"></param>
        ///// <returns></returns>
        //public static async Task<T> PostFileGetJsonAsync<T>(string url, CookieContainer cookieContainer = null, Dictionary<string, string> fileDictionary = null, Encoding encoding = null, X509Certificate cer = null, int timeOut = Config.TIME_OUT)
        //{
        //    string returnText = await RequestUtility.HttpPostAsync(url, cookieContainer, null, fileDictionary, null, encoding, cer, timeOut);
        //    var result = GetResult<T>(returnText);
        //    return result;
        //}

        /// <summary>
        /// 使用Post方法上传数据并下载文件或结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="stream"></param>
        public static async Task DownloadAsync(string url, string data, Stream stream)
        {
#if NET35 || NET40 || NET45
            WebClient wc = new WebClient();

            var fileBytes = await wc.UploadDataTaskAsync(url, "POST", Encoding.UTF8.GetBytes(string.IsNullOrEmpty(data) ? "" : data));
            await stream.WriteAsync(fileBytes, 0, fileBytes.Length);//也可以分段写入
#else
            HttpClient httpClient = new HttpClient();
            HttpContent hc = new StringContent(data);
            var ht = await httpClient.PostAsync(url, hc);
            var fileBytes = await ht.Content.ReadAsByteArrayAsync();
            await stream.WriteAsync(fileBytes, 0, fileBytes.Length);//也可以分段写入
#endif

        }

        #endregion
#endif
    }
}


text:
package org.adridadou.ethereum;

import static java.lang.reflect.Proxy.newProxyInstance;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.google.common.base.Charsets;
import org.adridadou.ethereum.converters.future.FutureConverter;
import org.adridadou.ethereum.converters.input.InputTypeConverter;
import org.adridadou.ethereum.converters.input.InputTypeHandler;
import org.adridadou.ethereum.converters.output.OutputTypeConverter;
import org.adridadou.ethereum.converters.output.OutputTypeHandler;
import org.adridadou.ethereum.event.EthereumEventHandler;
import org.adridadou.ethereum.swarm.SwarmHash;
import org.adridadou.ethereum.swarm.SwarmService;
import org.adridadou.ethereum.values.*;
import org.adridadou.ethereum.values.smartcontract.SmartContractMetadata;
import org.adridadou.exception.EthereumApiException;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.solidity.compiler.SolidityCompiler;
import rx.Observable;

/**
 * Created by davidroon on 31.03.16.
 * This code is released under Apache 2 license
 */
public class EthereumFacade {
    public static final Charset CHARSET = Charsets.UTF_8;
    private final EthereumContractInvocationHandler handler;
    private final OutputTypeHandler outputTypeHandler;
    private final InputTypeHandler inputTypeHandler;
    private final EthereumProxy ethereumProxy;
    private final SwarmService swarmService;
    private final SolidityCompiler solidityCompiler;

    public EthereumFacade(EthereumProxy ethereumProxy, InputTypeHandler inputTypeHandler, OutputTypeHandler outputTypeHandler, SwarmService swarmService, SolidityCompiler solidityCompiler) {
        this.inputTypeHandler = inputTypeHandler;
        this.outputTypeHandler = outputTypeHandler;
        this.swarmService = swarmService;
        this.solidityCompiler = solidityCompiler;
        this.handler = new EthereumContractInvocationHandler(ethereumProxy, inputTypeHandler, outputTypeHandler);
        this.ethereumProxy = ethereumProxy;
    }

    public EthereumFacade addInputHandlers(final List<InputTypeConverter> handlers) {
        inputTypeHandler.addConverters(handlers);
        return this;
    }

    public EthereumFacade addOutputHandlers(final List<OutputTypeConverter> handlers) {
        outputTypeHandler.addConverters(handlers);
        return this;
    }

    public EthereumFacade addFutureConverter(final FutureConverter futureConverter) {
        handler.addFutureConverter(futureConverter);
        return this;
    }

    public <T> T createContractProxy(CompiledContract contract, EthAddress address, EthAccount account, Class<T> contractInterface) {
        return createContractProxy(contract.getAbi(), address, account, contractInterface);
    }

    public <T> T createContractProxy(EthAddress address, EthAccount account, Class<T> contractInterface) {
        return createContractProxy(getAbi(address), address, account, contractInterface);
    }

    public <T> T createContractProxy(ContractAbi abi, EthAddress address, EthAccount account, Class<T> contractInterface) {
        T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler);
        handler.register(proxy, contractInterface, abi, address, account);
        return proxy;
    }

    public <T> Builder<T> createContractProxy(EthAddress address, Class<T> contractInterface) {
        return new Builder<>(contractInterface, address, getAbi(address));
    }

    public <T> Builder<T> createContractProxy(EthAddress address, ContractAbi abi, Class<T> contractInterface) {
        return new Builder<>(contractInterface, address, abi);
    }

    public <T> Builder<T> createContractProxy(CompiledContract contract, EthAddress address, Class<T> contractInterface) {
        return new Builder<>(contractInterface, address, contract.getAbi());
    }

    public ContractAbi getAbi(final EthAddress address) {
        SmartContractByteCode code = ethereumProxy.getCode(address);
        SmartContractMetadata metadata = getMetadata(code.getMetadaLink().orElseThrow(() -> new EthereumApiException("no metadata link found for smart contract on address " + address.toString())));
        return metadata.getAbi();
    }

    public CompletableFuture<EthAddress> publishContract(CompiledContract contract, EthAccount account, Object... constructorArgs) {
        return ethereumProxy.publish(contract, account, constructorArgs);
    }

    public SwarmHash publishMetadataToSwarm(CompiledContract contract) {
        return swarmService.publish(contract.getMetadata().getValue());
    }

    public boolean addressExists(final EthAddress address) {
        return ethereumProxy.addressExists(address);
    }

    public EthValue getBalance(final EthAddress addr) {
        return ethereumProxy.getBalance(addr);
    }

    public EthValue getBalance(final EthAccount account) {
        return ethereumProxy.getBalance(account.getAddress());
    }

    public EthereumEventHandler events() {
        return ethereumProxy.events();
    }

    public CompletableFuture<EthExecutionResult> sendEther(EthAccount fromAccount, EthAddress to, EthValue value) {
        return ethereumProxy.sendTx(value, EthData.empty(), fromAccount, to);
    }

    public BigInteger getNonce(EthAddress address) {
        return ethereumProxy.getNonce(address);
    }

    public SmartContractByteCode getCode(EthAddress address) {
        return ethereumProxy.getCode(address);
    }

    public SmartContractMetadata getMetadata(SwarmMetadaLink swarmMetadaLink) {
        try {
            return swarmService.getMetadata(swarmMetadaLink.getHash());
        } catch (IOException e) {
            throw new EthereumApiException("error while getting metadata", e);
        }
    }

    public CompletableFuture<Map<String, CompiledContract>> compile(SoliditySource src) {
        if(src instanceof SoliditySourceString){
            return CompletableFuture.supplyAsync(() -> compileInternal((SoliditySourceString)src));
        }

        if(src instanceof  SoliditySourceFile) {
            return CompletableFuture.supplyAsync(() -> compileInternal((SoliditySourceFile)src));
        }

        throw new EthereumApiException("error while trying to compile " + src);
    }

    private Map<String, CompiledContract> compileInternal(SoliditySourceFile src) {
        try {
            SolidityCompiler.Result result = solidityCompiler.compileSrc(src.getSource(), true, true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.METADATA);
            if (result.isFailed()) {
                throw new EthereumApiException("Contract compilation failed:\n" + result.errors);
            }
            CompilationResult res = CompilationResult.parse(result.output);
            if (res.contracts == null || res.contracts.isEmpty()) {
                throw new EthereumApiException("Compilation failed, no contracts returned:\n" + result.errors);
            }
            return res.contracts.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> CompiledContract.from(src, e.getKey(), e.getValue())));
        } catch (IOException e) {
            throw new EthereumApiException("error while compiling solidity smart contract", e);
        }
    }

    private Map<String, CompiledContract> compileInternal(SoliditySourceString src) {
        try {
            SolidityCompiler.Result result = solidityCompiler.compileSrc(src.getSource().getBytes(EthereumFacade.CHARSET), true, true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.METADATA);
            if (result.isFailed()) {
                throw new EthereumApiException("Contract compilation failed:\n" + result.errors);
            }
            CompilationResult res = CompilationResult.parse(result.output);
            if (res.contracts.isEmpty()) {
                throw new EthereumApiException("Compilation failed, no contracts returned:\n" + result.errors);
            }
            return res.contracts.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> CompiledContract.from(src, e.getKey(), e.getValue())));
        } catch (IOException e) {
            throw new EthereumApiException("error while compiling solidity smart contract", e);
        }
    }

    public <T> Observable<T> observeEvents(ContractAbi abi, EthAddress address, String eventName, Class<T> cls) {
        return ethereumProxy.observeEvents(abi, address, eventName, cls);
    }

    public class Builder<T> {
        private final Class<T> contractInterface;
        private final EthAddress address;
        private final ContractAbi abi;

        public Builder(Class<T> contractInterface, EthAddress address, ContractAbi abi) {
            this.contractInterface = contractInterface;
            this.address = address;
            this.abi = abi;
        }

        public T forAccount(final EthAccount account) {
            T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler);
            EthereumFacade.this.handler.register(proxy, contractInterface, abi, address, account);
            return proxy;
        }
    }
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved.                        */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package edu.wpi.first.wpilibj.communication;

import com.sun.cldc.jna.Structure;

/**
 * Structure for data exchanged between the robot and the driver station.
 */
public final class FRCCommonControlData extends Structure {

    public static final short RESET_BIT = 0x80;
    public static final short ESTOP_BIT = 0x40;
    public static final short ENABLED_BIT = 0x20;
    public static final short AUTONOMOUS_BIT = 0x10;
    public static final short FMS_ATTATCHED = 0x08;
    public static final short RESYNCH = 0x04;
    public static final short TEST_MODE_BIT = 0x02;
    public static final short CHECK_VERSIONS_BIT = 0x01;

    /**
     * The index of the packet
     */
    public /*UINT16*/ int packetIndex;
    /**
     * The control mode e.g. Autonomous, E-stop, enabled ...
     */
    public /*UINT8*/ short control;
    // { reset, notEStop, enabled, autonomous, fmsAttached, resync, cRIOChkSum, fpgaChkSum }

    /**
     * Determine if the robot should be enabled
     * @return true if the robot is enabled
     */
    public boolean enabled() {
        return (control & ENABLED_BIT) == ENABLED_BIT;
    }

    /**
     * Determine if the robot is in test mode
     * @return true if the robot is in test mode
     */
    public boolean testMode() {
        return (control & TEST_MODE_BIT) == TEST_MODE_BIT;
    }

    /**
     * Determine if the robot should be in autonomous
     * @return true if the robot is in autonomous
     */
    public boolean autonomous() {
        return (control & AUTONOMOUS_BIT) == AUTONOMOUS_BIT;
    }
    /**
     * The state of the digital inputs on the ds
     */
    public /*UINT8*/ short dsDigitalIn;
    /**
     * The team number from the ds
     */
    public /*UINT16*/ int teamID;
    /**
     * Which alliance the robot is on
     */
    public char dsID_Alliance;
    /**
     * The position of the controls on the alliance station wall.
     */
    public char dsID_Position;
    /**
     * Position of the axes of the first js
     */
    public byte[] stick0Axes = new byte[6];
    /**
     * Button state of the first js
     */
    public short stick0Buttons;		// Left-most 4 bits are unused
    /**
     * Position of the axes of the second js
     */
    public byte[] stick1Axes = new byte[6];
    /**
     * Button state of the second js
     */
    public short stick1Buttons;		// Left-most 4 bits are unused
    /**
     * Position of the axes of the third js
     */
    public byte[] stick2Axes = new byte[6];
    /**
     * Button state of the third js
     */
    public short stick2Buttons;		// Left-most 4 bits are unused
    /**
     * Position of the axes of the fourth js
     */
    public byte[] stick3Axes = new byte[6];
    /**
     * Button state of the fourth js
     */
    public short stick3Buttons;		// Left-most 4 bits are unused
    //Analog inputs are 10 bit right-justified
    /** Driver Station analog input */
    public short analog1;
    /** Driver Station analog input */
    public short analog2;
    /** Driver Station analog input */
    public short analog3;
    /** Driver Station analog input */
    public short analog4;

    // Other fields are used by the lower-level comm system and not needed by robot code:

    /**
     * Create a new FRCControlData structure
     */
    public FRCCommonControlData() {
        allocateMemory();
    }

    /**
     * Method to free the memory used by this structure
     */
    protected void free() {
        freeMemory();
    }

    /**
     * Read new data in the structure
     */
    public void read() {
        packetIndex = backingNativeMemory.getShort(0) & 0xFFFF;
        control = (short)(backingNativeMemory.getByte(2) & 0xFF);

        dsDigitalIn = (short)(backingNativeMemory.getByte(3) & 0xFF);
        teamID = backingNativeMemory.getShort(4) & 0xFFFF;

        dsID_Alliance = (char) backingNativeMemory.getByte(6);
        dsID_Position = (char) backingNativeMemory.getByte(7);

        backingNativeMemory.getBytes(8, stick0Axes, 0, 6);
        stick0Buttons = backingNativeMemory.getShort(14);

        backingNativeMemory.getBytes(16, stick1Axes, 0, 6);
        stick1Buttons = backingNativeMemory.getShort(22);

        backingNativeMemory.getBytes(24, stick2Axes, 0, 6);
        stick2Buttons = backingNativeMemory.getShort(30);

        backingNativeMemory.getBytes(32, stick3Axes, 0, 6);
        stick3Buttons = backingNativeMemory.getShort(38);

        analog1 = backingNativeMemory.getShort(40);
        analog2 = backingNativeMemory.getShort(42);
        analog3 = backingNativeMemory.getShort(44);
        analog4 = backingNativeMemory.getShort(46);

        // Other fields are used by the lower-level comm system and not needed by robot code
    }

    /**
     * Write new data in the structure
     */
    public void write() {
        throw new IllegalStateException("FRCCommonControlData is not writable");
    }

    /**
     * Get the size of the structure
     * @return size of the structure
     */
    public int size() {
        return 80;
    }

}


text:
#region UrlBuilder

/// <summary>
/// This simple class aids you in the fluid creation of urls and url parameters
/// </summary>
using System.Collections.Specialized;
using System.Text;
using System.Web;
public class UrlBuilder
{
    private readonly string _url = "";
    private readonly NameValueCollection _params = new NameValueCollection();

    public UrlBuilder() { }

    public UrlBuilder(string url)
    {
        _url = url;
    }

    /// <summary>
    /// Adds a Url parameter to the querystring
    /// </summary>
    /// <param name="param">parameter name</param>
    /// <param name="value">value</param>
    /// <returns>The UrlBulder object to continue to add paramters etc. Call ToString to finish</returns>
    public UrlBuilder Add(string param, string value)
    {
        _params.Add(param, value);
        return this;
    }

    /// <summary>
    /// Adds a Url parameter to the querystring
    /// </summary>
    /// <param name="param">parameter name</param>
    /// <param name="value">adds an integer parameter</param>
    /// <returns>The UrlBulder object to continue to add paramters etc. Call ToString to finish</returns>
    public UrlBuilder Add(string param, int value)
    {
        _params.Add(param, value.ToString());
        return this;
    }

    /// <summary>
    /// Builds your url with the parameters etc. By default it does not urlencode your parameters
    /// </summary>
    public override string ToString()
    {
        return ToString(false);
    }

    /// <summary>
    /// Builds your url with the parameters etc. You can optionally urlencode your url parametes
    /// </summary>
    /// <param name="encode">UrlEncode or not your parameters</param>
    public string ToString(bool encode)
    {
        var qs = new StringBuilder();
        foreach (var key in _params.AllKeys)
        {
            var value = _params[key];
            // Encode if requested
            if (encode) value = HttpUtility.UrlEncode(value);
            if (qs.Length > 0) qs.Append("&");
            qs.AppendFormat("{0}={1}", key, value);
        }

        // When building a full url determine weather there are already parameters in it, or this is the first set of parameters
        var returnUrl = _url;
        if (returnUrl.Length > 0) returnUrl += returnUrl.Contains("?") ? "&" : "?";

        return returnUrl + qs;
    }

    /// <summary>
    /// UrlEncodes a certain value
    /// </summary>
    public static string UrlEncode(string value)
    {
        return HttpUtility.UrlEncode(value);
    }

    /// <summary>
    /// UrlDecodes a certain value
    /// </summary>
    public static string UrlDecode(string value)
    {
        return HttpUtility.UrlDecode(value);
    }

    /// <summary>
    /// Creates a url parameter
    /// </summary>
    public static string UrlP(string parameterName, string parameterValue)
    {
        return UrlP(parameterName, parameterValue, false);
    }

    /// <summary>
    /// Creates a url parameter
    /// </summary>
    public static string UrlP(string parameterName, string parameterValue, bool encode)
    {
        if (encode) parameterValue = UrlEncode(parameterValue);
        return parameterName + "=" + parameterValue;
    }

}
#endregion


text:
namespace {

#if defined(OS_CHROMEOS)
typedef std::map<int, FilePath> SequenceToPathMap;

struct PrintingSequencePathMap {
  SequenceToPathMap map;
  int sequence;
};

// No locking, only access on the FILE thread.
static base::LazyInstance<PrintingSequencePathMap>
    g_printing_file_descriptor_map(base::LINKER_INITIALIZED);
#endif

void RenderParamsFromPrintSettings(const printing::PrintSettings& settings,
                                   PrintMsg_Print_Params* params) {
  params->page_size = settings.page_setup_device_units().physical_size();
  params->printable_size.SetSize(
      settings.page_setup_device_units().content_area().width(),
      settings.page_setup_device_units().content_area().height());
  params->margin_top = settings.page_setup_device_units().content_area().x();
  params->margin_left = settings.page_setup_device_units().content_area().y();
  params->dpi = settings.dpi();
  // Currently hardcoded at 1.25. See PrintSettings' constructor.
  params->min_shrink = settings.min_shrink;
  // Currently hardcoded at 2.0. See PrintSettings' constructor.
  params->max_shrink = settings.max_shrink;
  // Currently hardcoded at 72dpi. See PrintSettings' constructor.
  params->desired_dpi = settings.desired_dpi;
  // Always use an invalid cookie.
  params->document_cookie = 0;
  params->selection_only = settings.selection_only;
  params->supports_alpha_blend = settings.supports_alpha_blend();
}

}  // namespace

PrintingMessageFilter::PrintingMessageFilter()
    : print_job_manager_(g_browser_process->print_job_manager()) {
#if defined(OS_CHROMEOS)
  cloud_print_enabled_ = true;
#else
  cloud_print_enabled_ = CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableCloudPrint);
#endif
}

PrintingMessageFilter::~PrintingMessageFilter() {
}

void PrintingMessageFilter::OverrideThreadForMessage(
    const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(OS_CHROMEOS)
  if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID ||
      message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) {
    *thread = BrowserThread::FILE;
  }
#endif
}

bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message,
                                              bool* message_was_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(PrintingMessageFilter, message, *message_was_ok)
#if defined(OS_WIN)
    IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_CHROMEOS)
    IPC_MESSAGE_HANDLER(PrintHostMsg_AllocateTempFileForPrinting,
                        OnAllocateTempFileForPrinting)
    IPC_MESSAGE_HANDLER(PrintHostMsg_TempFileForPrintingWritten,
                        OnTempFileForPrintingWritten)
#endif
    IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings,
                                    OnGetDefaultPrintSettings)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_UpdatePrintSettings,
                                    OnUpdatePrintSettings)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

#if defined(OS_WIN)
void PrintingMessageFilter::OnDuplicateSection(
    base::SharedMemoryHandle renderer_handle,
    base::SharedMemoryHandle* browser_handle) {
  // Duplicate the handle in this process right now so the memory is kept alive
  // (even if it is not mapped)
  base::SharedMemory shared_buf(renderer_handle, true, peer_handle());
  shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);
}
#endif

#if defined(OS_CHROMEOS)
void PrintingMessageFilter::OnAllocateTempFileForPrinting(
    base::FileDescriptor* temp_file_fd, int* sequence_number) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  temp_file_fd->fd = *sequence_number = -1;
  temp_file_fd->auto_close = false;

  SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
  *sequence_number = g_printing_file_descriptor_map.Get().sequence++;

  FilePath path;
  if (file_util::CreateTemporaryFile(&path)) {
    int fd = open(path.value().c_str(), O_WRONLY);
    if (fd >= 0) {
      SequenceToPathMap::iterator it = map->find(*sequence_number);
      if (it != map->end()) {
        NOTREACHED() << "Sequence number already in use. seq=" <<
            *sequence_number;
      } else {
        (*map)[*sequence_number] = path;
        temp_file_fd->fd = fd;
        temp_file_fd->auto_close = true;
      }
    }
  }
}

void PrintingMessageFilter::OnTempFileForPrintingWritten(int sequence_number) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
  SequenceToPathMap::iterator it = map->find(sequence_number);
  if (it == map->end()) {
    NOTREACHED() << "Got a sequence that we didn't pass to the "
                    "renderer: " << sequence_number;
    return;
  }

  if (cloud_print_enabled_)
    print_dialog_cloud::CreatePrintDialogForFile(
        it->second,
        string16(),
        std::string("application/pdf"),
        true);
  else
    NOTIMPLEMENTED();

  // Erase the entry in the map.
  map->erase(it);
}
#endif  // defined(OS_CHROMEOS)

void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
  scoped_refptr<printing::PrinterQuery> printer_query;
  if (!print_job_manager_->printing_enabled()) {
    // Reply with NULL query.
    OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
    return;
  }

  print_job_manager_->PopPrinterQuery(0, &printer_query);
  if (!printer_query.get()) {
    printer_query = new printing::PrinterQuery;
  }

  CancelableTask* task = NewRunnableMethod(
      this,
      &PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
      printer_query,
      reply_msg);
  // Loads default settings. This is asynchronous, only the IPC message sender
  // will hang until the settings are retrieved.
  printer_query->GetSettings(printing::PrinterQuery::DEFAULTS,
                             NULL,
                             0,
                             false,
                             true,
                             task);
}

void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  PrintMsg_Print_Params params;
  if (!printer_query.get() ||
      printer_query->last_status() != printing::PrintingContext::OK) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params);
    params.document_cookie = printer_query->cookie();
  }
  PrintHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  // If printing was enabled.
  if (printer_query.get()) {
    // If user hasn't cancelled.
    if (printer_query->cookie() && printer_query->settings().dpi()) {
      print_job_manager_->QueuePrinterQuery(printer_query.get());
    } else {
      printer_query->StopWorker();
    }
  }
}

void PrintingMessageFilter::OnScriptedPrint(
    const PrintHostMsg_ScriptedPrint_Params& params,
    IPC::Message* reply_msg) {
  gfx::NativeView host_view =
      gfx::NativeViewFromIdInBrowser(params.host_window_id);

  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager_->PopPrinterQuery(params.cookie, &printer_query);
  if (!printer_query.get()) {
    printer_query = new printing::PrinterQuery;
  }

  CancelableTask* task = NewRunnableMethod(
      this,
      &PrintingMessageFilter::OnScriptedPrintReply,
      printer_query,
      params.routing_id,
      reply_msg);

  printer_query->GetSettings(printing::PrinterQuery::ASK_USER,
                             host_view,
                             params.expected_pages_count,
                             params.has_selection,
                             params.use_overlays,
                             task);
}

void PrintingMessageFilter::OnScriptedPrintReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    int routing_id,
    IPC::Message* reply_msg) {
  PrintMsg_PrintPages_Params params;
  if (printer_query->last_status() != printing::PrintingContext::OK ||
      !printer_query->settings().dpi()) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
    params.params.document_cookie = printer_query->cookie();
    params.pages =
        printing::PageRange::GetPages(printer_query->settings().ranges);
  }
  PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  if (params.params.dpi && params.params.document_cookie) {
    print_job_manager_->QueuePrinterQuery(printer_query.get());
  } else {
    printer_query->StopWorker();
  }
}

void PrintingMessageFilter::OnUpdatePrintSettings(
    int document_cookie, const DictionaryValue& job_settings,
    IPC::Message* reply_msg) {
  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager_->PopPrinterQuery(document_cookie, &printer_query);
  if (printer_query.get()) {
    CancelableTask* task = NewRunnableMethod(
        this,
        &PrintingMessageFilter::OnUpdatePrintSettingsReply,
        printer_query,
        reply_msg);
    printer_query->SetSettings(job_settings, task);
  }
}

void PrintingMessageFilter::OnUpdatePrintSettingsReply(
    scoped_refptr<printing::PrinterQuery> printer_query,
    IPC::Message* reply_msg) {
  PrintMsg_PrintPages_Params params;
  if (printer_query->last_status() != printing::PrintingContext::OK) {
    memset(&params, 0, sizeof(params));
  } else {
    RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
    params.params.document_cookie = printer_query->cookie();
    params.pages =
        printing::PageRange::GetPages(printer_query->settings().ranges);
  }
  PrintHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);
  Send(reply_msg);
  // If user hasn't cancelled.
  if (printer_query->cookie() && printer_query->settings().dpi())
    print_job_manager_->QueuePrinterQuery(printer_query.get());
  else
    printer_query->StopWorker();
}


text:
Letter Detail

<form action="addedit.php" method="post">

<?php
$order_id= $_GET["order_id"];

$db = mysql_connect("localhost", "root", "");
mysql_select_db("lestari_fd",$db);
$result = mysql_query("SELECT * FROM ordermenu WHERE order_id=$order_id",$db);
$myrow = mysql_fetch_array($result);

echo "order_id: ".$myrow["order_id"];
echo "
quantity: ".$myrow["quantity"];
echo "
menu_id: ".$myrow["menu_id"];
echo "
price: ".$myrow["price"];

?>


text:
package io.opentracing.testbed.concurrent_common_request_handler;

import io.opentracing.testbed.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Client {

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

    private final ExecutorService executor = Executors.newCachedThreadPool();

    private final RequestHandler requestHandler;

    public Client(RequestHandler requestHandler) {
        this.requestHandler = requestHandler;
    }

    public Future<String> send(final Object message) {

        final Context context = new Context();
        return executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                logger.info("send {}", message);
                TestUtils.sleep();
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        TestUtils.sleep();
                        requestHandler.beforeRequest(message, context);
                    }
                }).get();

                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        TestUtils.sleep();
                        requestHandler.afterResponse(message, context);
                    }
                }).get();

                return message + ":response";
            }
        });

    }
}


text:
set (python_cmd "python")
set (python_arg "tools/hardcode_shaders.py")
message(STATUS "\n\nGenerating shader include file...")
execute_process(COMMAND ${python_cmd} ${python_arg}
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    RESULT_VARIABLE python_result
    OUTPUT_VARIABLE python_ver)
message(STATUS "${python_result}: ${python_ver}\n\n")
INCLUDE_DIRECTORIES("autogen/")


text:
#include "engine.h"
#include "engineimp.h"
#include "item.h"
#include "input.h"
#include "native_item.hpp"

void write_data(std::mutex& wait_m, std::mutex& data,
        std::condition_variable& write_notify, data_io_info invals);

char f_is_empty(std::ifstream& fstr){
    return fstr.peek()==std::ifstream::traits_type::eof();
}
engineimp::engineimp(const std::string& fname, const std::string& outname,
        const std::string& start_index):datas_queued(0), data_size(0), is_over(0),
    cur_blob(std::make_shared<data_blob>()){
        cur_blob->size=0;
        values["!out_file"] =  std::make_shared<string>();
        ((native_item*)(values["!out_file"].get()))->parse(outname);
        values["!out_file"]->setname("!out_file");
        ofile.open(outname.c_str(), std::ofstream::out | std::ofstream::trunc);
        auto p = std::make_shared<integer>();
        p->parse(start_index);
        p->setname("!start_ind");
        values["!start_ind"]=p;
        std::ifstream fstr(fname.c_str());
        if(f_is_empty(fstr)){
            err("Empty/non-existant file passed as configuration parameter",
                    "engineimp::engineimp(std::string)", "engine/engine.cpp", FATAL_ERROR);
        }
        read(fstr);
        datas_queued=0;
#ifdef ASYNC_IO
        data_io_info dat_inf;
        dat_inf.data_size=&data_size;
        dat_inf.datas_queued = &datas_queued;
        dat_inf.file = &ofile;
        dat_inf.writers = &async_write_queue;
        dat_inf.is_over = &is_over;
        write_thread = std::thread(
                [dat_inf, this](){
                ::write_data(this->condition_lock, this->data_lock, this->write_cond, dat_inf);
                });
#endif
    };

engineimp::~engineimp(){
    this->_write_dat(true);
#ifdef ASYNC_IO
    is_over++;
    while(datas_queued > 0){
    }
    std::unique_lock<std::mutex> lock(condition_lock);
    write_cond.notify_all();
    write_thread.join();
#endif
}
bool engineimp::item_exists(std::shared_ptr<item> p) const{
    if(!p){
        return false;
    }
    for(auto& val : values){
        if(val.second.get_shared() == p){
            return true;
        }
    }
    return false;
}
bool engineimp::item_exists(const std::string& val) const{
    return values.count(val);
}
/*!
 * Updates items which reference variables that require changing,
 * and resets the list of items which require updating
 */
void engineimp::update(){
    for(auto& val : update_vars){
        val->update();
    }
    update_vars.clear();
}
/*!
 * Adds an item to the list of items that require updating
 * @param name Name of the item that requires updating
 */
void engineimp::needs_updating(std::string name){
    auto pos = values.find(name);
    if(pos == values.end()){
        std::string errmess = "Lookup for item \"";
        errmess.append(name);
        errmess.append("\" has failed");
        err(errmess, "engineimp::needs_updating", "engine/engine.cpp", WARNING);
        return;
    }
    needs_updating(pos->second);
}
/*!
 * Adds an item to the list of items that require updating
 * Goes by pointer so that items that are not part of the engine
 * can be updated. Useful for wrapper classes such as the integrators
 * @param inval Pointer to the item that requires updating
 */
void engineimp::needs_updating(std::shared_ptr<item> inval){
    if(!inval){
        err("Null pointer passed to needs_updating", "engineimp::needs_updating",
                "engine/engine.cpp", WARNING);
        return;
    }
    update_vars.insert(inval);
}
/*
 *
 *Engine wrapper functions
 *
 *
 *
 *
 */

/*!
 * Constructs an engine object, a wrapper for engimeimp
 * \sa engineimp
 */
engine::engine(const std::string fname, const std::string outname, std::string index){
    eng = new engineimp(fname, outname, index);
}
engine::~engine(){
    if(eng){
        delete eng;
    }
}
void engine::run(){
    eng->run();
}


text:
    [#include"/mall/common/head.html"/]
    [#include"/mall/common/navigator.html"/]


text:
<?php

namespace Symfony\Bundle\DoctrineBundle\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\DoctrineBundle\Logger\DbalLogger;

/**
 * DoctrineDataCollector.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class DoctrineDataCollector extends DataCollector
{
    protected $logger;

    public function __construct(DbalLogger $logger = null)
    {
        $this->logger = $logger;
    }

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $this->data = array(
            'queries' => null !== $this->logger ? $this->logger->queries : array(),
        );
    }

    public function getQueryCount()
    {
        return count($this->data['queries']);
    }

    public function getQueries()
    {
        return $this->data['queries'];
    }

    public function getTime()
    {
        $time = 0;
        foreach ($this->data['queries'] as $query) {
            $time += $query['executionMS'];
        }

        return $time;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'db';
    }
}