text:
#include "utils/includes.h"

#ifndef CONFIG_NATIVE_WINDOWS

#include "utils/common.h"
#include "utils/eloop.h"
#include "crypto/crypto.h"
#include "drivers/driver.h"
#include "common/ieee802_11_defs.h"
#include "common/ieee802_11_common.h"
#include "common/wpa_ctrl.h"
#include "radius/radius.h"
#include "radius/radius_client.h"
#include "wps/wps.h"
#include "hostapd.h"
#include "beacon.h"
#include "ieee802_11_auth.h"
#include "sta_info.h"
#include "ieee802_1x.h"
#include "wpa_auth.h"
#include "wmm.h"
#include "ap_list.h"
#include "accounting.h"
#include "ap_config.h"
#include "ap_mlme.h"
#include "ieee802_11.h"

u8 * hostapd_eid_supp_rates(struct hostapd_data *hapd, u8 *eid)
{
	u8 *pos = eid;
	int i, num, count;

	if (hapd->iface->current_rates == NULL)
		return eid;

	*pos++ = WLAN_EID_SUPP_RATES;
	num = hapd->iface->num_rates;
	if (num > 8) {
		/* rest of the rates are encoded in Extended supported
		 * rates element */
		num = 8;
	}

	*pos++ = num;
	count = 0;
	for (i = 0, count = 0; i < hapd->iface->num_rates && count < num;
	     i++) {
		count++;
		*pos = hapd->iface->current_rates[i].rate / 5;
		if (hapd->iface->current_rates[i].flags & HOSTAPD_RATE_BASIC)
			*pos |= 0x80;
		pos++;
	}

	return pos;
}

u8 * hostapd_eid_ext_supp_rates(struct hostapd_data *hapd, u8 *eid)
{
	u8 *pos = eid;
	int i, num, count;

	if (hapd->iface->current_rates == NULL)
		return eid;

	num = hapd->iface->num_rates;
	if (num <= 8)
		return eid;
	num -= 8;

	*pos++ = WLAN_EID_EXT_SUPP_RATES;
	*pos++ = num;
	count = 0;
	for (i = 0, count = 0; i < hapd->iface->num_rates && count < num + 8;
	     i++) {
		count++;
		if (count <= 8)
			continue; /* already in SuppRates IE */
		*pos = hapd->iface->current_rates[i].rate / 5;
		if (hapd->iface->current_rates[i].flags & HOSTAPD_RATE_BASIC)
			*pos |= 0x80;
		pos++;
	}

	return pos;
}

u16 hostapd_own_capab_info(struct hostapd_data *hapd, struct sta_info *sta,
			   int probe)
{
	int capab = WLAN_CAPABILITY_ESS;
	int privacy;

	if (hapd->iface->num_sta_no_short_preamble == 0 &&
	    hapd->iconf->preamble == SHORT_PREAMBLE)
		capab |= WLAN_CAPABILITY_SHORT_PREAMBLE;

	privacy = hapd->conf->ssid.wep.keys_set;

	if (hapd->conf->ieee802_1x &&
	    (hapd->conf->default_wep_key_len ||
	     hapd->conf->individual_wep_key_len))
		privacy = 1;

	if (hapd->conf->wpa)
		privacy = 1;

	if (sta) {
		int policy, def_klen;
		if (probe && sta->ssid_probe) {
			policy = sta->ssid_probe->security_policy;
			def_klen = sta->ssid_probe->wep.default_len;
		} else {
			policy = sta->ssid->security_policy;
			def_klen = sta->ssid->wep.default_len;
		}
		privacy = policy != SECURITY_PLAINTEXT;
		if (policy == SECURITY_IEEE_802_1X && def_klen == 0)
			privacy = 0;
	}

	if (privacy)
		capab |= WLAN_CAPABILITY_PRIVACY;

	if (hapd->iface->current_mode &&
	    hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211G &&
	    hapd->iface->num_sta_no_short_slot_time == 0)
		capab |= WLAN_CAPABILITY_SHORT_SLOT_TIME;

	return capab;
}

#ifdef CONFIG_IEEE80211W
static u8 * hostapd_eid_assoc_comeback_time(struct hostapd_data *hapd,
					    struct sta_info *sta, u8 *eid)
{
	u8 *pos = eid;
	u32 timeout, tu;
	struct os_time now, passed;

	*pos++ = WLAN_EID_TIMEOUT_INTERVAL;
	*pos++ = 5;
	*pos++ = WLAN_TIMEOUT_ASSOC_COMEBACK;
	os_get_time(&now);
	os_time_sub(&now, &sta->sa_query_start, &passed);
	tu = (passed.sec * 1000000 + passed.usec) / 1024;
	if (hapd->conf->assoc_sa_query_max_timeout > tu)
		timeout = hapd->conf->assoc_sa_query_max_timeout - tu;
	else
		timeout = 0;
	if (timeout < hapd->conf->assoc_sa_query_max_timeout)
		timeout++; /* add some extra time for local timers */
	WPA_PUT_LE32(pos, timeout);
	pos += 4;

	return pos;
}
#endif /* CONFIG_IEEE80211W */

void ieee802_11_print_ssid(char *buf, const u8 *ssid, u8 len)
{
	int i;
	if (len > HOSTAPD_MAX_SSID_LEN)
		len = HOSTAPD_MAX_SSID_LEN;
	for (i = 0; i < len; i++) {
		if (ssid[i] >= 32 && ssid[i] < 127)
			buf[i] = ssid[i];
		else
			buf[i] = '.';
	}
	buf[len] = '\0';
}

static u16 auth_shared_key(struct hostapd_data *hapd, struct sta_info *sta,
			   u16 auth_transaction, const u8 *challenge,
			   int iswep)
{
	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_DEBUG,
		       "authentication (shared key, transaction %d)",
		       auth_transaction);

	if (auth_transaction == 1) {
		if (!sta->challenge) {
			/* Generate a pseudo-random challenge */
			u8 key[8];
			time_t now;
			int r;
			sta->challenge = os_zalloc(WLAN_AUTH_CHALLENGE_LEN);
			if (sta->challenge == NULL)
				return WLAN_STATUS_UNSPECIFIED_FAILURE;

			now = time(NULL);
			r = random();
			os_memcpy(key, &now, 4);
			os_memcpy(key + 4, &r, 4);
			rc4_skip(key, sizeof(key), 0,
				 sta->challenge, WLAN_AUTH_CHALLENGE_LEN);
		}
		return 0;
	}

	if (auth_transaction != 3)
		return WLAN_STATUS_UNSPECIFIED_FAILURE;

	/* Transaction 3 */
	if (!iswep || !sta->challenge || !challenge ||
	    os_memcmp(sta->challenge, challenge, WLAN_AUTH_CHALLENGE_LEN)) {
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_INFO,
			       "shared key authentication - invalid "
			       "challenge-response");
		return WLAN_STATUS_CHALLENGE_FAIL;
	}

	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_DEBUG,
		       "authentication OK (shared key)");
#ifdef IEEE80211_REQUIRE_AUTH_ACK
	/* Station will be marked authenticated if it ACKs the
	 * authentication reply. */
#else
	sta->flags |= WLAN_STA_AUTH;
	wpa_auth_sm_event(sta->wpa_sm, WPA_AUTH);
#endif
	os_free(sta->challenge);
	sta->challenge = NULL;

	return 0;
}

static void send_auth_reply(struct hostapd_data *hapd,
			    const u8 *dst, const u8 *bssid,
			    u16 auth_alg, u16 auth_transaction, u16 resp,
			    const u8 *ies, size_t ies_len)
{
	struct ieee80211_mgmt *reply;
	u8 *buf;
	size_t rlen;

	rlen = IEEE80211_HDRLEN + sizeof(reply->u.auth) + ies_len;
	buf = os_zalloc(rlen);
	if (buf == NULL)
		return;

	reply = (struct ieee80211_mgmt *) buf;
	reply->frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
					    WLAN_FC_STYPE_AUTH);
	os_memcpy(reply->da, dst, ETH_ALEN);
	os_memcpy(reply->sa, hapd->own_addr, ETH_ALEN);
	os_memcpy(reply->bssid, bssid, ETH_ALEN);

	reply->u.auth.auth_alg = host_to_le16(auth_alg);
	reply->u.auth.auth_transaction = host_to_le16(auth_transaction);
	reply->u.auth.status_code = host_to_le16(resp);

	if (ies && ies_len)
		os_memcpy(reply->u.auth.variable, ies, ies_len);

	wpa_printf(MSG_DEBUG, "authentication reply: STA=" MACSTR
		   " auth_alg=%d auth_transaction=%d resp=%d (IE len=%lu)",
		   MAC2STR(dst), auth_alg, auth_transaction,
		   resp, (unsigned long) ies_len);
	if (hapd->drv.send_mgmt_frame(hapd, reply, rlen) < 0)
		perror("send_auth_reply: send");

	os_free(buf);
}

#ifdef CONFIG_IEEE80211R
static void handle_auth_ft_finish(void *ctx, const u8 *dst, const u8 *bssid,
				  u16 auth_transaction, u16 status,
				  const u8 *ies, size_t ies_len)
{
	struct hostapd_data *hapd = ctx;
	struct sta_info *sta;

	send_auth_reply(hapd, dst, bssid, WLAN_AUTH_FT, auth_transaction,
			status, ies, ies_len);

	if (status != WLAN_STATUS_SUCCESS)
		return;

	sta = ap_get_sta(hapd, dst);
	if (sta == NULL)
		return;

	hostapd_logger(hapd, dst, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_DEBUG, "authentication OK (FT)");
	sta->flags |= WLAN_STA_AUTH;
	mlme_authenticate_indication(hapd, sta);
}
#endif /* CONFIG_IEEE80211R */

static void handle_auth(struct hostapd_data *hapd,
			const struct ieee80211_mgmt *mgmt, size_t len)
{
	u16 auth_alg, auth_transaction, status_code;
	u16 resp = WLAN_STATUS_SUCCESS;
	struct sta_info *sta = NULL;
	int res;
	u16 fc;
	const u8 *challenge = NULL;
	u32 session_timeout, acct_interim_interval;
	int vlan_id = 0;
	u8 resp_ies[2 + WLAN_AUTH_CHALLENGE_LEN];
	size_t resp_ies_len = 0;

	if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.auth)) {
		printf("handle_auth - too short payload (len=%lu)\n",
		       (unsigned long) len);
		return;
	}

	auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
	auth_transaction = le_to_host16(mgmt->u.auth.auth_transaction);
	status_code = le_to_host16(mgmt->u.auth.status_code);
	fc = le_to_host16(mgmt->frame_control);

	if (len >= IEEE80211_HDRLEN + sizeof(mgmt->u.auth) +
	    2 + WLAN_AUTH_CHALLENGE_LEN &&
	    mgmt->u.auth.variable[0] == WLAN_EID_CHALLENGE &&
	    mgmt->u.auth.variable[1] == WLAN_AUTH_CHALLENGE_LEN)
		challenge = &mgmt->u.auth.variable[2];

	wpa_printf(MSG_DEBUG, "authentication: STA=" MACSTR " auth_alg=%d "
		   "auth_transaction=%d status_code=%d wep=%d%s",
		   MAC2STR(mgmt->sa), auth_alg, auth_transaction,
		   status_code, !!(fc & WLAN_FC_ISWEP),
		   challenge ? " challenge" : "");

	if (hapd->tkip_countermeasures) {
		resp = WLAN_REASON_MICHAEL_MIC_FAILURE;
		goto fail;
	}

	if (!(((hapd->conf->auth_algs & WPA_AUTH_ALG_OPEN) &&
	       auth_alg == WLAN_AUTH_OPEN) ||
#ifdef CONFIG_IEEE80211R
	      (hapd->conf->wpa &&
	       (hapd->conf->wpa_key_mgmt &
		(WPA_KEY_MGMT_FT_IEEE8021X | WPA_KEY_MGMT_FT_PSK)) &&
	       auth_alg == WLAN_AUTH_FT) ||
#endif /* CONFIG_IEEE80211R */
	      ((hapd->conf->auth_algs & WPA_AUTH_ALG_SHARED) &&
	       auth_alg == WLAN_AUTH_SHARED_KEY))) {
		printf("Unsupported authentication algorithm (%d)\n",
		       auth_alg);
		resp = WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG;
		goto fail;
	}

	if (!(auth_transaction == 1 ||
	      (auth_alg == WLAN_AUTH_SHARED_KEY && auth_transaction == 3))) {
		printf("Unknown authentication transaction number (%d)\n",
		       auth_transaction);
		resp = WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION;
		goto fail;
	}

	if (os_memcmp(mgmt->sa, hapd->own_addr, ETH_ALEN) == 0) {
		printf("Station " MACSTR " not allowed to authenticate.\n",
		       MAC2STR(mgmt->sa));
		resp = WLAN_STATUS_UNSPECIFIED_FAILURE;
		goto fail;
	}

	res = hostapd_allowed_address(hapd, mgmt->sa, (u8 *) mgmt, len,
				      &session_timeout,
				      &acct_interim_interval, &vlan_id);
	if (res == HOSTAPD_ACL_REJECT) {
		printf("Station " MACSTR " not allowed to authenticate.\n",
		       MAC2STR(mgmt->sa));
		resp = WLAN_STATUS_UNSPECIFIED_FAILURE;
		goto fail;
	}
	if (res == HOSTAPD_ACL_PENDING) {
		wpa_printf(MSG_DEBUG, "Authentication frame from " MACSTR
			   " waiting for an external authentication",
			   MAC2STR(mgmt->sa));
		/* Authentication code will re-send the authentication frame
		 * after it has received (and cached) information from the
		 * external source. */
		return;
	}

	sta = ap_sta_add(hapd, mgmt->sa);
	if (!sta) {
		resp = WLAN_STATUS_UNSPECIFIED_FAILURE;
		goto fail;
	}

	if (vlan_id > 0) {
		if (hostapd_get_vlan_id_ifname(hapd->conf->vlan,
					       vlan_id) == NULL) {
			hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_RADIUS,
				       HOSTAPD_LEVEL_INFO, "Invalid VLAN ID "
				       "%d received from RADIUS server",
				       vlan_id);
			resp = WLAN_STATUS_UNSPECIFIED_FAILURE;
			goto fail;
		}
		sta->vlan_id = vlan_id;
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_RADIUS,
			       HOSTAPD_LEVEL_INFO, "VLAN ID %d", sta->vlan_id);
	}

	sta->flags &= ~WLAN_STA_PREAUTH;
	ieee802_1x_notify_pre_auth(sta->eapol_sm, 0);

	if (hapd->conf->acct_interim_interval == 0 && acct_interim_interval)
		sta->acct_interim_interval = acct_interim_interval;
	if (res == HOSTAPD_ACL_ACCEPT_TIMEOUT)
		ap_sta_session_timeout(hapd, sta, session_timeout);
	else
		ap_sta_no_session_timeout(hapd, sta);

	switch (auth_alg) {
	case WLAN_AUTH_OPEN:
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "authentication OK (open system)");
#ifdef IEEE80211_REQUIRE_AUTH_ACK
		/* Station will be marked authenticated if it ACKs the
		 * authentication reply. */
#else
		sta->flags |= WLAN_STA_AUTH;
		wpa_auth_sm_event(sta->wpa_sm, WPA_AUTH);
		sta->auth_alg = WLAN_AUTH_OPEN;
		mlme_authenticate_indication(hapd, sta);
#endif
		break;
	case WLAN_AUTH_SHARED_KEY:
		resp = auth_shared_key(hapd, sta, auth_transaction, challenge,
				       fc & WLAN_FC_ISWEP);
		sta->auth_alg = WLAN_AUTH_SHARED_KEY;
		mlme_authenticate_indication(hapd, sta);
		if (sta->challenge && auth_transaction == 1) {
			resp_ies[0] = WLAN_EID_CHALLENGE;
			resp_ies[1] = WLAN_AUTH_CHALLENGE_LEN;
			os_memcpy(resp_ies + 2, sta->challenge,
				  WLAN_AUTH_CHALLENGE_LEN);
			resp_ies_len = 2 + WLAN_AUTH_CHALLENGE_LEN;
		}
		break;
#ifdef CONFIG_IEEE80211R
	case WLAN_AUTH_FT:
		sta->auth_alg = WLAN_AUTH_FT;
		if (sta->wpa_sm == NULL)
			sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth,
							sta->addr);
		if (sta->wpa_sm == NULL) {
			wpa_printf(MSG_DEBUG, "FT: Failed to initialize WPA "
				   "state machine");
			resp = WLAN_STATUS_UNSPECIFIED_FAILURE;
			goto fail;
		}
		wpa_ft_process_auth(sta->wpa_sm, mgmt->bssid,
				    auth_transaction, mgmt->u.auth.variable,
				    len - IEEE80211_HDRLEN -
				    sizeof(mgmt->u.auth),
				    handle_auth_ft_finish, hapd);
		/* handle_auth_ft_finish() callback will complete auth. */
		return;
#endif /* CONFIG_IEEE80211R */
	}

 fail:
	send_auth_reply(hapd, mgmt->sa, mgmt->bssid, auth_alg,
			auth_transaction + 1, resp, resp_ies, resp_ies_len);
}

static int hostapd_get_aid(struct hostapd_data *hapd, struct sta_info *sta)
{
	int i, j = 32, aid;

	/* get a unique AID */
	if (sta->aid > 0) {
		wpa_printf(MSG_DEBUG, "  old AID %d", sta->aid);
		return 0;
	}

	for (i = 0; i < AID_WORDS; i++) {
		if (hapd->sta_aid[i] == (u32) -1)
			continue;
		for (j = 0; j < 32; j++) {
			if (!(hapd->sta_aid[i] & BIT(j)))
				break;
		}
		if (j < 32)
			break;
	}
	if (j == 32)
		return -1;
	aid = i * 32 + j + 1;
	if (aid > 2007)
		return -1;

	sta->aid = aid;
	hapd->sta_aid[i] |= BIT(j);
	wpa_printf(MSG_DEBUG, "  new AID %d", sta->aid);
	return 0;
}

static u16 check_ssid(struct hostapd_data *hapd, struct sta_info *sta,
		      const u8 *ssid_ie, size_t ssid_ie_len)
{
	if (ssid_ie == NULL)
		return WLAN_STATUS_UNSPECIFIED_FAILURE;

	if (ssid_ie_len != hapd->conf->ssid.ssid_len ||
	    os_memcmp(ssid_ie, hapd->conf->ssid.ssid, ssid_ie_len) != 0) {
		char ssid_txt[33];
		ieee802_11_print_ssid(ssid_txt, ssid_ie, ssid_ie_len);
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_INFO,
			       "Station tried to associate with unknown SSID "
			       "'%s'", ssid_txt);
		return WLAN_STATUS_UNSPECIFIED_FAILURE;
	}

	return WLAN_STATUS_SUCCESS;
}

static u16 check_wmm(struct hostapd_data *hapd, struct sta_info *sta,
		     const u8 *wmm_ie, size_t wmm_ie_len)
{
	sta->flags &= ~WLAN_STA_WMM;
	if (wmm_ie && hapd->conf->wmm_enabled) {
		if (hostapd_eid_wmm_valid(hapd, wmm_ie, wmm_ie_len))
			hostapd_logger(hapd, sta->addr,
				       HOSTAPD_MODULE_WPA,
				       HOSTAPD_LEVEL_DEBUG,
				       "invalid WMM element in association "
				       "request");
		else
			sta->flags |= WLAN_STA_WMM;
	}
	return WLAN_STATUS_SUCCESS;
}

static u16 copy_supp_rates(struct hostapd_data *hapd, struct sta_info *sta,
			   struct ieee802_11_elems *elems)
{
	if (!elems->supp_rates) {
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "No supported rates element in AssocReq");
		return WLAN_STATUS_UNSPECIFIED_FAILURE;
	}

	if (elems->supp_rates_len > sizeof(sta->supported_rates)) {
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "Invalid supported rates element length %d",
			       elems->supp_rates_len);
		return WLAN_STATUS_UNSPECIFIED_FAILURE;
	}

	os_memset(sta->supported_rates, 0, sizeof(sta->supported_rates));
	os_memcpy(sta->supported_rates, elems->supp_rates,
		  elems->supp_rates_len);
	sta->supported_rates_len = elems->supp_rates_len;

	if (elems->ext_supp_rates) {
		if (elems->supp_rates_len + elems->ext_supp_rates_len >
		    sizeof(sta->supported_rates)) {
			hostapd_logger(hapd, sta->addr,
				       HOSTAPD_MODULE_IEEE80211,
				       HOSTAPD_LEVEL_DEBUG,
				       "Invalid supported rates element length"
				       " %d+%d", elems->supp_rates_len,
				       elems->ext_supp_rates_len);
			return WLAN_STATUS_UNSPECIFIED_FAILURE;
		}

		os_memcpy(sta->supported_rates + elems->supp_rates_len,
			  elems->ext_supp_rates, elems->ext_supp_rates_len);
		sta->supported_rates_len += elems->ext_supp_rates_len;
	}

	return WLAN_STATUS_SUCCESS;
}

static u16 check_assoc_ies(struct hostapd_data *hapd, struct sta_info *sta,
			   const u8 *ies, size_t ies_len, int reassoc)
{
	struct ieee802_11_elems elems;
	u16 resp;
	const u8 *wpa_ie;
	size_t wpa_ie_len;

	if (ieee802_11_parse_elems(ies, ies_len, &elems, 1) == ParseFailed) {
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_INFO, "Station sent an invalid "
			       "association request");
		return WLAN_STATUS_UNSPECIFIED_FAILURE;
	}

	resp = check_ssid(hapd, sta, elems.ssid, elems.ssid_len);
	if (resp != WLAN_STATUS_SUCCESS)
		return resp;
	resp = check_wmm(hapd, sta, elems.wmm, elems.wmm_len);
	if (resp != WLAN_STATUS_SUCCESS)
		return resp;
	resp = copy_supp_rates(hapd, sta, &elems);
	if (resp != WLAN_STATUS_SUCCESS)
		return resp;
#ifdef CONFIG_IEEE80211N
	resp = copy_sta_ht_capab(sta, elems.ht_capabilities,
				 elems.ht_capabilities_len);
	if (resp != WLAN_STATUS_SUCCESS)
		return resp;
#endif /* CONFIG_IEEE80211N */

	if ((hapd->conf->wpa & WPA_PROTO_RSN) && elems.rsn_ie) {
		wpa_ie = elems.rsn_ie;
		wpa_ie_len = elems.rsn_ie_len;
	} else if ((hapd->conf->wpa & WPA_PROTO_WPA) &&
		   elems.wpa_ie) {
		wpa_ie = elems.wpa_ie;
		wpa_ie_len = elems.wpa_ie_len;
	} else {
		wpa_ie = NULL;
		wpa_ie_len = 0;
	}

#ifdef CONFIG_WPS
	sta->flags &= ~(WLAN_STA_WPS | WLAN_STA_MAYBE_WPS);
	if (hapd->conf->wps_state && elems.wps_ie) {
		wpa_printf(MSG_DEBUG, "STA included WPS IE in (Re)Association "
			   "Request - assume WPS is used");
		sta->flags |= WLAN_STA_WPS;
		wpabuf_free(sta->wps_ie);
		sta->wps_ie = ieee802_11_vendor_ie_concat(ies, ies_len,
							  WPS_IE_VENDOR_TYPE);
		wpa_ie = NULL;
		wpa_ie_len = 0;
	} else if (hapd->conf->wps_state && wpa_ie == NULL) {
		wpa_printf(MSG_DEBUG, "STA did not include WPA/RSN IE in "
			   "(Re)Association Request - possible WPS use");
		sta->flags |= WLAN_STA_MAYBE_WPS;
	} else
#endif /* CONFIG_WPS */
	if (hapd->conf->wpa && wpa_ie == NULL) {
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_INFO,
			       "No WPA/RSN IE in association request");
		return WLAN_STATUS_INVALID_IE;
	}

	if (hapd->conf->wpa && wpa_ie) {
		int res;
		wpa_ie -= 2;
		wpa_ie_len += 2;
		if (sta->wpa_sm == NULL)
			sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth,
							sta->addr);
		if (sta->wpa_sm == NULL) {
			wpa_printf(MSG_WARNING, "Failed to initialize WPA "
				   "state machine");
			return WLAN_STATUS_UNSPECIFIED_FAILURE;
		}
		res = wpa_validate_wpa_ie(hapd->wpa_auth, sta->wpa_sm,
					  wpa_ie, wpa_ie_len,
					  elems.mdie, elems.mdie_len);
		if (res == WPA_INVALID_GROUP)
			resp = WLAN_STATUS_GROUP_CIPHER_NOT_VALID;
		else if (res == WPA_INVALID_PAIRWISE)
			resp = WLAN_STATUS_PAIRWISE_CIPHER_NOT_VALID;
		else if (res == WPA_INVALID_AKMP)
			resp = WLAN_STATUS_AKMP_NOT_VALID;
		else if (res == WPA_ALLOC_FAIL)
			resp = WLAN_STATUS_UNSPECIFIED_FAILURE;
#ifdef CONFIG_IEEE80211W
		else if (res == WPA_MGMT_FRAME_PROTECTION_VIOLATION)
			resp = WLAN_STATUS_ROBUST_MGMT_FRAME_POLICY_VIOLATION;
		else if (res == WPA_INVALID_MGMT_GROUP_CIPHER)
			resp = WLAN_STATUS_ROBUST_MGMT_FRAME_POLICY_VIOLATION;
#endif /* CONFIG_IEEE80211W */
		else if (res == WPA_INVALID_MDIE)
			resp = WLAN_STATUS_INVALID_MDIE;
		else if (res != WPA_IE_OK)
			resp = WLAN_STATUS_INVALID_IE;
		if (resp != WLAN_STATUS_SUCCESS)
			return resp;
#ifdef CONFIG_IEEE80211W
		if ((sta->flags & WLAN_STA_MFP) && !sta->sa_query_timed_out &&
		    sta->sa_query_count > 0)
			ap_check_sa_query_timeout(hapd, sta);
		if ((sta->flags & WLAN_STA_MFP) && !sta->sa_query_timed_out &&
		    (!reassoc || sta->auth_alg != WLAN_AUTH_FT)) {
			/*
			 * STA has already been associated with MFP and SA
			 * Query timeout has not been reached. Reject the
			 * association attempt temporarily and start SA Query,
			 * if one is not pending.
			 */

			if (sta->sa_query_count == 0)
				ap_sta_start_sa_query(hapd, sta);

			return WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY;
		}

		if (wpa_auth_uses_mfp(sta->wpa_sm))
			sta->flags |= WLAN_STA_MFP;
		else
			sta->flags &= ~WLAN_STA_MFP;
#endif /* CONFIG_IEEE80211W */

#ifdef CONFIG_IEEE80211R
		if (sta->auth_alg == WLAN_AUTH_FT) {
			if (!reassoc) {
				wpa_printf(MSG_DEBUG, "FT: " MACSTR " tried "
					   "to use association (not "
					   "re-association) with FT auth_alg",
					   MAC2STR(sta->addr));
				return WLAN_STATUS_UNSPECIFIED_FAILURE;
			}

			resp = wpa_ft_validate_reassoc(sta->wpa_sm, ies,
						       ies_len);
			if (resp != WLAN_STATUS_SUCCESS)
				return resp;
		}
#endif /* CONFIG_IEEE80211R */

#ifdef CONFIG_IEEE80211N
		if ((sta->flags & WLAN_STA_HT) &&
		    wpa_auth_get_pairwise(sta->wpa_sm) == WPA_CIPHER_TKIP) {
			hostapd_logger(hapd, sta->addr,
				       HOSTAPD_MODULE_IEEE80211,
				       HOSTAPD_LEVEL_INFO,
				       "Station tried to use TKIP with HT "
				       "association");
			return WLAN_STATUS_CIPHER_REJECTED_PER_POLICY;
		}
#endif /* CONFIG_IEEE80211N */
	} else
		wpa_auth_sta_no_wpa(sta->wpa_sm);

	return WLAN_STATUS_SUCCESS;
}

static void send_deauth(struct hostapd_data *hapd, const u8 *addr,
			u16 reason_code)
{
	int send_len;
	struct ieee80211_mgmt reply;

	os_memset(&reply, 0, sizeof(reply));
	reply.frame_control =
		IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_DEAUTH);
	os_memcpy(reply.da, addr, ETH_ALEN);
	os_memcpy(reply.sa, hapd->own_addr, ETH_ALEN);
	os_memcpy(reply.bssid, hapd->own_addr, ETH_ALEN);

	send_len = IEEE80211_HDRLEN + sizeof(reply.u.deauth);
	reply.u.deauth.reason_code = host_to_le16(reason_code);

	if (hapd->drv.send_mgmt_frame(hapd, &reply, send_len) < 0)
		wpa_printf(MSG_INFO, "Failed to send deauth: %s",
			   strerror(errno));
}

static void send_assoc_resp(struct hostapd_data *hapd, struct sta_info *sta,
			    u16 status_code, int reassoc, const u8 *ies,
			    size_t ies_len)
{
	int send_len;
	u8 buf[sizeof(struct ieee80211_mgmt) + 1024];
	struct ieee80211_mgmt *reply;
	u8 *p;

	os_memset(buf, 0, sizeof(buf));
	reply = (struct ieee80211_mgmt *) buf;
	reply->frame_control =
		IEEE80211_FC(WLAN_FC_TYPE_MGMT,
			     (reassoc ? WLAN_FC_STYPE_REASSOC_RESP :
			      WLAN_FC_STYPE_ASSOC_RESP));
	os_memcpy(reply->da, sta->addr, ETH_ALEN);
	os_memcpy(reply->sa, hapd->own_addr, ETH_ALEN);
	os_memcpy(reply->bssid, hapd->own_addr, ETH_ALEN);

	send_len = IEEE80211_HDRLEN;
	send_len += sizeof(reply->u.assoc_resp);
	reply->u.assoc_resp.capab_info =
		host_to_le16(hostapd_own_capab_info(hapd, sta, 0));
	reply->u.assoc_resp.status_code = host_to_le16(status_code);
	reply->u.assoc_resp.aid = host_to_le16((sta ? sta->aid : 0)
					       | BIT(14) | BIT(15));
	/* Supported rates */
	p = hostapd_eid_supp_rates(hapd, reply->u.assoc_resp.variable);
	/* Extended supported rates */
	p = hostapd_eid_ext_supp_rates(hapd, p);

#ifdef CONFIG_IEEE80211R
	if (status_code == WLAN_STATUS_SUCCESS) {
		/* IEEE 802.11r: Mobility Domain Information, Fast BSS
		 * Transition Information, RSN, [RIC Response] */
		p = wpa_sm_write_assoc_resp_ies(sta->wpa_sm, p,
						buf + sizeof(buf) - p,
						sta->auth_alg, ies, ies_len);
	}
#endif /* CONFIG_IEEE80211R */

#ifdef CONFIG_IEEE80211W
	if (status_code == WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY)
		p = hostapd_eid_assoc_comeback_time(hapd, sta, p);
#endif /* CONFIG_IEEE80211W */

#ifdef CONFIG_IEEE80211N
	p = hostapd_eid_ht_capabilities(hapd, p);
	p = hostapd_eid_ht_operation(hapd, p);
#endif /* CONFIG_IEEE80211N */

	if (sta->flags & WLAN_STA_WMM)
		p = hostapd_eid_wmm(hapd, p);

#ifdef CONFIG_WPS
	if (sta->flags & WLAN_STA_WPS) {
		struct wpabuf *wps = wps_build_assoc_resp_ie();
		if (wps) {
			os_memcpy(p, wpabuf_head(wps), wpabuf_len(wps));
			p += wpabuf_len(wps);
			wpabuf_free(wps);
		}
	}
#endif /* CONFIG_WPS */

	send_len += p - reply->u.assoc_resp.variable;

	if (hapd->drv.send_mgmt_frame(hapd, reply, send_len) < 0)
		wpa_printf(MSG_INFO, "Failed to send assoc resp: %s",
			   strerror(errno));
}

static void handle_assoc(struct hostapd_data *hapd,
			 const struct ieee80211_mgmt *mgmt, size_t len,
			 int reassoc)
{
	u16 capab_info, listen_interval;
	u16 resp = WLAN_STATUS_SUCCESS;
	const u8 *pos;
	int left, i;
	struct sta_info *sta;

	if (len < IEEE80211_HDRLEN + (reassoc ? sizeof(mgmt->u.reassoc_req) :
				      sizeof(mgmt->u.assoc_req))) {
		printf("handle_assoc(reassoc=%d) - too short payload (len=%lu)"
		       "\n", reassoc, (unsigned long) len);
		return;
	}

	if (reassoc) {
		capab_info = le_to_host16(mgmt->u.reassoc_req.capab_info);
		listen_interval = le_to_host16(
			mgmt->u.reassoc_req.listen_interval);
		wpa_printf(MSG_DEBUG, "reassociation request: STA=" MACSTR
			   " capab_info=0x%02x listen_interval=%d current_ap="
			   MACSTR,
			   MAC2STR(mgmt->sa), capab_info, listen_interval,
			   MAC2STR(mgmt->u.reassoc_req.current_ap));
		left = len - (IEEE80211_HDRLEN + sizeof(mgmt->u.reassoc_req));
		pos = mgmt->u.reassoc_req.variable;
	} else {
		capab_info = le_to_host16(mgmt->u.assoc_req.capab_info);
		listen_interval = le_to_host16(
			mgmt->u.assoc_req.listen_interval);
		wpa_printf(MSG_DEBUG, "association request: STA=" MACSTR
			   " capab_info=0x%02x listen_interval=%d",
			   MAC2STR(mgmt->sa), capab_info, listen_interval);
		left = len - (IEEE80211_HDRLEN + sizeof(mgmt->u.assoc_req));
		pos = mgmt->u.assoc_req.variable;
	}

	sta = ap_get_sta(hapd, mgmt->sa);
#ifdef CONFIG_IEEE80211R
	if (sta && sta->auth_alg == WLAN_AUTH_FT &&
	    (sta->flags & WLAN_STA_AUTH) == 0) {
		wpa_printf(MSG_DEBUG, "FT: Allow STA " MACSTR " to associate "
			   "prior to authentication since it is using "
			   "over-the-DS FT", MAC2STR(mgmt->sa));
	} else
#endif /* CONFIG_IEEE80211R */
	if (sta == NULL || (sta->flags & WLAN_STA_AUTH) == 0) {
		hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_INFO, "Station tried to "
			       "associate before authentication "
			       "(aid=%d flags=0x%x)",
			       sta ? sta->aid : -1,
			       sta ? sta->flags : 0);
		send_deauth(hapd, mgmt->sa,
			    WLAN_REASON_CLASS2_FRAME_FROM_NONAUTH_STA);
		return;
	}

	if (hapd->tkip_countermeasures) {
		resp = WLAN_REASON_MICHAEL_MIC_FAILURE;
		goto fail;
	}

	if (listen_interval > hapd->conf->max_listen_interval) {
		hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "Too large Listen Interval (%d)",
			       listen_interval);
		resp = WLAN_STATUS_ASSOC_DENIED_LISTEN_INT_TOO_LARGE;
		goto fail;
	}

	/* followed by SSID and Supported rates; and HT capabilities if 802.11n
	 * is used */
	resp = check_assoc_ies(hapd, sta, pos, left, reassoc);
	if (resp != WLAN_STATUS_SUCCESS)
		goto fail;

	if (hostapd_get_aid(hapd, sta) < 0) {
		hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_INFO, "No room for more AIDs");
		resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA;
		goto fail;
	}

	sta->capability = capab_info;
	sta->listen_interval = listen_interval;

	if (hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211G)
		sta->flags |= WLAN_STA_NONERP;
	for (i = 0; i < sta->supported_rates_len; i++) {
		if ((sta->supported_rates[i] & 0x7f) > 22) {
			sta->flags &= ~WLAN_STA_NONERP;
			break;
		}
	}
	if (sta->flags & WLAN_STA_NONERP && !sta->nonerp_set) {
		sta->nonerp_set = 1;
		hapd->iface->num_sta_non_erp++;
		if (hapd->iface->num_sta_non_erp == 1)
			ieee802_11_set_beacons(hapd->iface);
	}

	if (!(sta->capability & WLAN_CAPABILITY_SHORT_SLOT_TIME) &&
	    !sta->no_short_slot_time_set) {
		sta->no_short_slot_time_set = 1;
		hapd->iface->num_sta_no_short_slot_time++;
		if (hapd->iface->current_mode->mode ==
		    HOSTAPD_MODE_IEEE80211G &&
		    hapd->iface->num_sta_no_short_slot_time == 1)
			ieee802_11_set_beacons(hapd->iface);
	}

	if (sta->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
		sta->flags |= WLAN_STA_SHORT_PREAMBLE;
	else
		sta->flags &= ~WLAN_STA_SHORT_PREAMBLE;

	if (!(sta->capability & WLAN_CAPABILITY_SHORT_PREAMBLE) &&
	    !sta->no_short_preamble_set) {
		sta->no_short_preamble_set = 1;
		hapd->iface->num_sta_no_short_preamble++;
		if (hapd->iface->current_mode->mode == HOSTAPD_MODE_IEEE80211G
		    && hapd->iface->num_sta_no_short_preamble == 1)
			ieee802_11_set_beacons(hapd->iface);
	}

#ifdef CONFIG_IEEE80211N
	update_ht_state(hapd, sta);
#endif /* CONFIG_IEEE80211N */

	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_DEBUG,
		       "association OK (aid %d)", sta->aid);
	/* Station will be marked associated, after it acknowledges AssocResp
	 */

#ifdef CONFIG_IEEE80211W
	if ((sta->flags & WLAN_STA_MFP) && sta->sa_query_timed_out) {
		wpa_printf(MSG_DEBUG, "Allowing %sassociation after timed out "
			   "SA Query procedure", reassoc ? "re" : "");
		/* TODO: Send a protected Disassociate frame to the STA using
		 * the old key and Reason Code "Previous Authentication no
		 * longer valid". Make sure this is only sent protected since
		 * unprotected frame would be received by the STA that is now
		 * trying to associate.
		 */
	}
#endif /* CONFIG_IEEE80211W */

	if (reassoc) {
		os_memcpy(sta->previous_ap, mgmt->u.reassoc_req.current_ap,
			  ETH_ALEN);
	}

	if (sta->last_assoc_req)
		os_free(sta->last_assoc_req);
	sta->last_assoc_req = os_malloc(len);
	if (sta->last_assoc_req)
		os_memcpy(sta->last_assoc_req, mgmt, len);

	/* Make sure that the previously registered inactivity timer will not
	 * remove the STA immediately. */
	sta->timeout_next = STA_NULLFUNC;

 fail:
	send_assoc_resp(hapd, sta, resp, reassoc, pos, left);
}

static void handle_disassoc(struct hostapd_data *hapd,
			    const struct ieee80211_mgmt *mgmt, size_t len)
{
	struct sta_info *sta;

	if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.disassoc)) {
		printf("handle_disassoc - too short payload (len=%lu)\n",
		       (unsigned long) len);
		return;
	}

	wpa_printf(MSG_DEBUG, "disassocation: STA=" MACSTR " reason_code=%d",
		   MAC2STR(mgmt->sa),
		   le_to_host16(mgmt->u.disassoc.reason_code));

	sta = ap_get_sta(hapd, mgmt->sa);
	if (sta == NULL) {
		printf("Station " MACSTR " trying to disassociate, but it "
		       "is not associated.\n", MAC2STR(mgmt->sa));
		return;
	}

	sta->flags &= ~WLAN_STA_ASSOC;
	wpa_msg(hapd->msg_ctx, MSG_INFO, AP_STA_DISCONNECTED MACSTR,
		MAC2STR(sta->addr));
	wpa_auth_sm_event(sta->wpa_sm, WPA_DISASSOC);
	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_INFO, "disassociated");
	sta->acct_terminate_cause = RADIUS_ACCT_TERMINATE_CAUSE_USER_REQUEST;
	ieee802_1x_notify_port_enabled(sta->eapol_sm, 0);
	/* Stop Accounting and IEEE 802.1X sessions, but leave the STA
	 * authenticated. */
	accounting_sta_stop(hapd, sta);
	ieee802_1x_free_station(sta);
	hapd->drv.sta_remove(hapd, sta->addr);

	if (sta->timeout_next == STA_NULLFUNC ||
	    sta->timeout_next == STA_DISASSOC) {
		sta->timeout_next = STA_DEAUTH;
		eloop_cancel_timeout(ap_handle_timer, hapd, sta);
		eloop_register_timeout(AP_DEAUTH_DELAY, 0, ap_handle_timer,
				       hapd, sta);
	}

	mlme_disassociate_indication(
		hapd, sta, le_to_host16(mgmt->u.disassoc.reason_code));
}

static void handle_deauth(struct hostapd_data *hapd,
			  const struct ieee80211_mgmt *mgmt, size_t len)
{
	struct sta_info *sta;

	if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.deauth)) {
		printf("handle_deauth - too short payload (len=%lu)\n",
		       (unsigned long) len);
		return;
	}

	wpa_printf(MSG_DEBUG, "deauthentication: STA=" MACSTR
		   " reason_code=%d",
		   MAC2STR(mgmt->sa),
		   le_to_host16(mgmt->u.deauth.reason_code));

	sta = ap_get_sta(hapd, mgmt->sa);
	if (sta == NULL) {
		printf("Station " MACSTR " trying to deauthenticate, but it "
		       "is not authenticated.\n", MAC2STR(mgmt->sa));
		return;
	}

	sta->flags &= ~(WLAN_STA_AUTH | WLAN_STA_ASSOC);
	wpa_msg(hapd->msg_ctx, MSG_INFO, AP_STA_DISCONNECTED MACSTR,
		MAC2STR(sta->addr));
	wpa_auth_sm_event(sta->wpa_sm, WPA_DEAUTH);
	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_DEBUG, "deauthenticated");
	mlme_deauthenticate_indication(
		hapd, sta, le_to_host16(mgmt->u.deauth.reason_code));
	sta->acct_terminate_cause = RADIUS_ACCT_TERMINATE_CAUSE_USER_REQUEST;
	ieee802_1x_notify_port_enabled(sta->eapol_sm, 0);
	ap_free_sta(hapd, sta);
}

static void handle_beacon(struct hostapd_data *hapd,
			  const struct ieee80211_mgmt *mgmt, size_t len,
			  struct hostapd_frame_info *fi)
{
	struct ieee802_11_elems elems;

	if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.beacon)) {
		printf("handle_beacon - too short payload (len=%lu)\n",
		       (unsigned long) len);
		return;
	}

	(void) ieee802_11_parse_elems(mgmt->u.beacon.variable,
				      len - (IEEE80211_HDRLEN +
					     sizeof(mgmt->u.beacon)), &elems,
				      0);

	ap_list_process_beacon(hapd->iface, mgmt, &elems, fi);
}

#ifdef CONFIG_IEEE80211W

/* MLME-SAQuery.request */
void ieee802_11_send_sa_query_req(struct hostapd_data *hapd,
				  const u8 *addr, const u8 *trans_id)
{
	struct ieee80211_mgmt mgmt;
	u8 *end;

	wpa_printf(MSG_DEBUG, "IEEE 802.11: Sending SA Query Request to "
		   MACSTR, MAC2STR(addr));
	wpa_hexdump(MSG_DEBUG, "IEEE 802.11: SA Query Transaction ID",
		    trans_id, WLAN_SA_QUERY_TR_ID_LEN);

	os_memset(&mgmt, 0, sizeof(mgmt));
	mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
					  WLAN_FC_STYPE_ACTION);
	os_memcpy(mgmt.da, addr, ETH_ALEN);
	os_memcpy(mgmt.sa, hapd->own_addr, ETH_ALEN);
	os_memcpy(mgmt.bssid, hapd->own_addr, ETH_ALEN);
	mgmt.u.action.category = WLAN_ACTION_SA_QUERY;
	mgmt.u.action.u.sa_query_req.action = WLAN_SA_QUERY_REQUEST;
	os_memcpy(mgmt.u.action.u.sa_query_req.trans_id, trans_id,
		  WLAN_SA_QUERY_TR_ID_LEN);
	end = mgmt.u.action.u.sa_query_req.trans_id + WLAN_SA_QUERY_TR_ID_LEN;
	if (hapd->drv.send_mgmt_frame(hapd, &mgmt, end - (u8 *) &mgmt) < 0)
		perror("ieee802_11_send_sa_query_req: send");
}

static void hostapd_sa_query_request(struct hostapd_data *hapd,
				     const struct ieee80211_mgmt *mgmt)
{
	struct sta_info *sta;
	struct ieee80211_mgmt resp;
	u8 *end;

	wpa_printf(MSG_DEBUG, "IEEE 802.11: Received SA Query Request from "
		   MACSTR, MAC2STR(mgmt->sa));
	wpa_hexdump(MSG_DEBUG, "IEEE 802.11: SA Query Transaction ID",
		    mgmt->u.action.u.sa_query_resp.trans_id,
		    WLAN_SA_QUERY_TR_ID_LEN);

	sta = ap_get_sta(hapd, mgmt->sa);
	if (sta == NULL || !(sta->flags & WLAN_STA_ASSOC)) {
		wpa_printf(MSG_DEBUG, "IEEE 802.11: Ignore SA Query Request "
			   "from unassociated STA " MACSTR, MAC2STR(mgmt->sa));
		return;
	}

	wpa_printf(MSG_DEBUG, "IEEE 802.11: Sending SA Query Response to "
		   MACSTR, MAC2STR(mgmt->sa));

	os_memset(&resp, 0, sizeof(resp));
	resp.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
					  WLAN_FC_STYPE_ACTION);
	os_memcpy(resp.da, mgmt->sa, ETH_ALEN);
	os_memcpy(resp.sa, hapd->own_addr, ETH_ALEN);
	os_memcpy(resp.bssid, hapd->own_addr, ETH_ALEN);
	resp.u.action.category = WLAN_ACTION_SA_QUERY;
	resp.u.action.u.sa_query_req.action = WLAN_SA_QUERY_RESPONSE;
	os_memcpy(resp.u.action.u.sa_query_req.trans_id,
		  mgmt->u.action.u.sa_query_req.trans_id,
		  WLAN_SA_QUERY_TR_ID_LEN);
	end = resp.u.action.u.sa_query_req.trans_id + WLAN_SA_QUERY_TR_ID_LEN;
	if (hapd->drv.send_mgmt_frame(hapd, &resp, end - (u8 *) &resp) < 0)
		perror("hostapd_sa_query_request: send");
}

static void hostapd_sa_query_action(struct hostapd_data *hapd,
				    const struct ieee80211_mgmt *mgmt,
				    size_t len)
{
	struct sta_info *sta;
	const u8 *end;
	int i;

	end = mgmt->u.action.u.sa_query_resp.trans_id +
		WLAN_SA_QUERY_TR_ID_LEN;
	if (((u8 *) mgmt) + len < end) {
		wpa_printf(MSG_DEBUG, "IEEE 802.11: Too short SA Query Action "
			   "frame (len=%lu)", (unsigned long) len);
		return;
	}

	if (mgmt->u.action.u.sa_query_resp.action == WLAN_SA_QUERY_REQUEST) {
		hostapd_sa_query_request(hapd, mgmt);
		return;
	}

	if (mgmt->u.action.u.sa_query_resp.action != WLAN_SA_QUERY_RESPONSE) {
		wpa_printf(MSG_DEBUG, "IEEE 802.11: Unexpected SA Query "
			   "Action %d", mgmt->u.action.u.sa_query_resp.action);
		return;
	}

	wpa_printf(MSG_DEBUG, "IEEE 802.11: Received SA Query Response from "
		   MACSTR, MAC2STR(mgmt->sa));
	wpa_hexdump(MSG_DEBUG, "IEEE 802.11: SA Query Transaction ID",
		    mgmt->u.action.u.sa_query_resp.trans_id,
		    WLAN_SA_QUERY_TR_ID_LEN);

	/* MLME-SAQuery.confirm */

	sta = ap_get_sta(hapd, mgmt->sa);
	if (sta == NULL || sta->sa_query_trans_id == NULL) {
		wpa_printf(MSG_DEBUG, "IEEE 802.11: No matching STA with "
			   "pending SA Query request found");
		return;
	}

	for (i = 0; i < sta->sa_query_count; i++) {
		if (os_memcmp(sta->sa_query_trans_id +
			      i * WLAN_SA_QUERY_TR_ID_LEN,
			      mgmt->u.action.u.sa_query_resp.trans_id,
			      WLAN_SA_QUERY_TR_ID_LEN) == 0)
			break;
	}

	if (i >= sta->sa_query_count) {
		wpa_printf(MSG_DEBUG, "IEEE 802.11: No matching SA Query "
			   "transaction identifier found");
		return;
	}

	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_DEBUG,
		       "Reply to pending SA Query received");
	ap_sta_stop_sa_query(hapd, sta);
}

static int robust_action_frame(u8 category)
{
	return category != WLAN_ACTION_PUBLIC &&
		category != WLAN_ACTION_HT;
}
#endif /* CONFIG_IEEE80211W */

static void handle_action(struct hostapd_data *hapd,
			  const struct ieee80211_mgmt *mgmt, size_t len)
{
	struct sta_info *sta;

	if (len < IEEE80211_HDRLEN + 1) {
		hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "handle_action - too short payload (len=%lu)",
			       (unsigned long) len);
		return;
	}

	sta = ap_get_sta(hapd, mgmt->sa);
#ifdef CONFIG_IEEE80211W
	if (sta && (sta->flags & WLAN_STA_MFP) &&
	    !(mgmt->frame_control & host_to_le16(WLAN_FC_ISWEP) &&
	      robust_action_frame(mgmt->u.action.category))) {
		hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "Dropped unprotected Robust Action frame from "
			       "an MFP STA");
		return;
	}
#endif /* CONFIG_IEEE80211W */

	switch (mgmt->u.action.category) {
#ifdef CONFIG_IEEE80211R
	case WLAN_ACTION_FT:
	{
		if (sta == NULL || !(sta->flags & WLAN_STA_ASSOC)) {
			wpa_printf(MSG_DEBUG, "IEEE 802.11: Ignored FT Action "
				   "frame from unassociated STA " MACSTR,
				   MAC2STR(mgmt->sa));
			return;
		}

		if (wpa_ft_action_rx(sta->wpa_sm, (u8 *) &mgmt->u.action,
				     len - IEEE80211_HDRLEN))
			break;

		return;
	}
#endif /* CONFIG_IEEE80211R */
	case WLAN_ACTION_WMM:
		hostapd_wmm_action(hapd, mgmt, len);
		return;
#ifdef CONFIG_IEEE80211W
	case WLAN_ACTION_SA_QUERY:
		hostapd_sa_query_action(hapd, mgmt, len);
		return;
#endif /* CONFIG_IEEE80211W */
	case WLAN_ACTION_PUBLIC:
		if (hapd->public_action_cb) {
			hapd->public_action_cb(hapd->public_action_cb_ctx,
					       (u8 *) mgmt, len,
					       hapd->iface->freq);
			return;
		}
		break;
	}

	hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_DEBUG,
		       "handle_action - unknown action category %d or invalid "
		       "frame",
		       mgmt->u.action.category);
	if (!(mgmt->da[0] & 0x01) && !(mgmt->u.action.category & 0x80) &&
	    !(mgmt->sa[0] & 0x01)) {
		struct ieee80211_mgmt *resp;

		/*
		 * IEEE 802.11-REVma/D9.0 - 7.3.1.11
		 * Return the Action frame to the source without change
		 * except that MSB of the Category set to 1.
		 */
		wpa_printf(MSG_DEBUG, "IEEE 802.11: Return unknown Action "
			   "frame back to sender");
		resp = os_malloc(len);
		if (resp == NULL)
			return;
		os_memcpy(resp, mgmt, len);
		os_memcpy(resp->da, resp->sa, ETH_ALEN);
		os_memcpy(resp->sa, hapd->own_addr, ETH_ALEN);
		os_memcpy(resp->bssid, hapd->own_addr, ETH_ALEN);
		resp->u.action.category |= 0x80;

		hapd->drv.send_mgmt_frame(hapd, resp, len);
		os_free(resp);
	}
}

/**
 * ieee802_11_mgmt - process incoming IEEE 802.11 management frames
 * @hapd: hostapd BSS data structure (the BSS to which the management frame was
 * sent to)
 * @buf: management frame data (starting from IEEE 802.11 header)
 * @len: length of frame data in octets
 * @fi: meta data about received frame (signal level, etc.)
 *
 * Process all incoming IEEE 802.11 management frames. This will be called for
 * each frame received from the kernel driver through wlan#ap interface. In
 * addition, it can be called to re-inserted pending frames (e.g., when using
 * external RADIUS server as an MAC ACL).
 */
void ieee802_11_mgmt(struct hostapd_data *hapd, const u8 *buf, size_t len,
		     struct hostapd_frame_info *fi)
{
	struct ieee80211_mgmt *mgmt;
	int broadcast;
	u16 fc, stype;

	mgmt = (struct ieee80211_mgmt *) buf;
	fc = le_to_host16(mgmt->frame_control);
	stype = WLAN_FC_GET_STYPE(fc);

	if (stype == WLAN_FC_STYPE_BEACON) {
		handle_beacon(hapd, mgmt, len, fi);
		return;
	}

	broadcast = mgmt->bssid[0] == 0xff && mgmt->bssid[1] == 0xff &&
		mgmt->bssid[2] == 0xff && mgmt->bssid[3] == 0xff &&
		mgmt->bssid[4] == 0xff && mgmt->bssid[5] == 0xff;

	if (!broadcast &&
	    os_memcmp(mgmt->bssid, hapd->own_addr, ETH_ALEN) != 0) {
		printf("MGMT: BSSID=" MACSTR " not our address\n",
		       MAC2STR(mgmt->bssid));
		return;
	}

	if (stype == WLAN_FC_STYPE_PROBE_REQ) {
		handle_probe_req(hapd, mgmt, len);
		return;
	}

	if (os_memcmp(mgmt->da, hapd->own_addr, ETH_ALEN) != 0) {
		hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "MGMT: DA=" MACSTR " not our address",
			       MAC2STR(mgmt->da));
		return;
	}

	switch (stype) {
	case WLAN_FC_STYPE_AUTH:
		wpa_printf(MSG_DEBUG, "mgmt::auth");
		handle_auth(hapd, mgmt, len);
		break;
	case WLAN_FC_STYPE_ASSOC_REQ:
		wpa_printf(MSG_DEBUG, "mgmt::assoc_req");
		handle_assoc(hapd, mgmt, len, 0);
		break;
	case WLAN_FC_STYPE_REASSOC_REQ:
		wpa_printf(MSG_DEBUG, "mgmt::reassoc_req");
		handle_assoc(hapd, mgmt, len, 1);
		break;
	case WLAN_FC_STYPE_DISASSOC:
		wpa_printf(MSG_DEBUG, "mgmt::disassoc");
		handle_disassoc(hapd, mgmt, len);
		break;
	case WLAN_FC_STYPE_DEAUTH:
		wpa_printf(MSG_DEBUG, "mgmt::deauth");
		handle_deauth(hapd, mgmt, len);
		break;
	case WLAN_FC_STYPE_ACTION:
		wpa_printf(MSG_DEBUG, "mgmt::action");
		handle_action(hapd, mgmt, len);
		break;
	default:
		hostapd_logger(hapd, mgmt->sa, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "unknown mgmt frame subtype %d", stype);
		break;
	}
}

static void handle_auth_cb(struct hostapd_data *hapd,
			   const struct ieee80211_mgmt *mgmt,
			   size_t len, int ok)
{
	u16 auth_alg, auth_transaction, status_code;
	struct sta_info *sta;

	if (!ok) {
		hostapd_logger(hapd, mgmt->da, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_NOTICE,
			       "did not acknowledge authentication response");
		return;
	}

	if (len < IEEE80211_HDRLEN + sizeof(mgmt->u.auth)) {
		printf("handle_auth_cb - too short payload (len=%lu)\n",
		       (unsigned long) len);
		return;
	}

	auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
	auth_transaction = le_to_host16(mgmt->u.auth.auth_transaction);
	status_code = le_to_host16(mgmt->u.auth.status_code);

	sta = ap_get_sta(hapd, mgmt->da);
	if (!sta) {
		printf("handle_auth_cb: STA " MACSTR " not found\n",
		       MAC2STR(mgmt->da));
		return;
	}

	if (status_code == WLAN_STATUS_SUCCESS &&
	    ((auth_alg == WLAN_AUTH_OPEN && auth_transaction == 2) ||
	     (auth_alg == WLAN_AUTH_SHARED_KEY && auth_transaction == 4))) {
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_INFO, "authenticated");
		sta->flags |= WLAN_STA_AUTH;
	}
}

static void handle_assoc_cb(struct hostapd_data *hapd,
			    const struct ieee80211_mgmt *mgmt,
			    size_t len, int reassoc, int ok)
{
	u16 status;
	struct sta_info *sta;
	int new_assoc = 1;
	struct ieee80211_ht_capabilities ht_cap;

	if (!ok) {
		hostapd_logger(hapd, mgmt->da, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_DEBUG,
			       "did not acknowledge association response");
		return;
	}

	if (len < IEEE80211_HDRLEN + (reassoc ? sizeof(mgmt->u.reassoc_resp) :
				      sizeof(mgmt->u.assoc_resp))) {
		printf("handle_assoc_cb(reassoc=%d) - too short payload "
		       "(len=%lu)\n", reassoc, (unsigned long) len);
		return;
	}

	if (reassoc)
		status = le_to_host16(mgmt->u.reassoc_resp.status_code);
	else
		status = le_to_host16(mgmt->u.assoc_resp.status_code);

	sta = ap_get_sta(hapd, mgmt->da);
	if (!sta) {
		printf("handle_assoc_cb: STA " MACSTR " not found\n",
		       MAC2STR(mgmt->da));
		return;
	}

	if (status != WLAN_STATUS_SUCCESS)
		goto fail;

	/* Stop previous accounting session, if one is started, and allocate
	 * new session id for the new session. */
	accounting_sta_stop(hapd, sta);

	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
		       HOSTAPD_LEVEL_INFO,
		       "associated (aid %d)",
		       sta->aid);

	if (sta->flags & WLAN_STA_ASSOC)
		new_assoc = 0;
	sta->flags |= WLAN_STA_ASSOC;
	if ((!hapd->conf->ieee802_1x && !hapd->conf->wpa) ||
	    sta->auth_alg == WLAN_AUTH_FT) {
		/*
		 * Open, static WEP, or FT protocol; no separate authorization
		 * step.
		 */
		sta->flags |= WLAN_STA_AUTHORIZED;
		wpa_msg(hapd->msg_ctx, MSG_INFO,
			AP_STA_CONNECTED MACSTR, MAC2STR(sta->addr));
	}

	if (reassoc)
		mlme_reassociate_indication(hapd, sta);
	else
		mlme_associate_indication(hapd, sta);

#ifdef CONFIG_IEEE80211W
	sta->sa_query_timed_out = 0;
#endif /* CONFIG_IEEE80211W */

	/*
	 * Remove the STA entry in order to make sure the STA PS state gets
	 * cleared and configuration gets updated in case of reassociation back
	 * to the same AP.
	 */
	hapd->drv.sta_remove(hapd, sta->addr);

#ifdef CONFIG_IEEE80211N
	if (sta->flags & WLAN_STA_HT)
		hostapd_get_ht_capab(hapd, sta->ht_capabilities, &ht_cap);
#endif /* CONFIG_IEEE80211N */

	if (hapd->drv.sta_add(hapd, sta->addr, sta->aid, sta->capability,
			      sta->supported_rates, sta->supported_rates_len,
			      sta->listen_interval,
			      sta->flags & WLAN_STA_HT ? &ht_cap : NULL)) {
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE80211,
			       HOSTAPD_LEVEL_NOTICE,
			       "Could not add STA to kernel driver");
	}

	if (sta->eapol_sm == NULL) {
		/*
		 * This STA does not use RADIUS server for EAP authentication,
		 * so bind it to the selected VLAN interface now, since the
		 * interface selection is not going to change anymore.
		 */
		if (ap_sta_bind_vlan(hapd, sta, 0) < 0)
			goto fail;
	} else if (sta->vlan_id) {
		/* VLAN ID already set (e.g., by PMKSA caching), so bind STA */
		if (ap_sta_bind_vlan(hapd, sta, 0) < 0)
			goto fail;
	}

	hapd->drv.set_sta_flags(hapd, sta);

	if (sta->auth_alg == WLAN_AUTH_FT)
		wpa_auth_sm_event(sta->wpa_sm, WPA_ASSOC_FT);
	else
		wpa_auth_sm_event(sta->wpa_sm, WPA_ASSOC);
	hapd->new_assoc_sta_cb(hapd, sta, !new_assoc);

	ieee802_1x_notify_port_enabled(sta->eapol_sm, 1);

 fail:
	/* Copy of the association request is not needed anymore */
	if (sta->last_assoc_req) {
		os_free(sta->last_assoc_req);
		sta->last_assoc_req = NULL;
	}
}

/**
 * ieee802_11_mgmt_cb - Process management frame TX status callback
 * @hapd: hostapd BSS data structure (the BSS from which the management frame
 * was sent from)
 * @buf: management frame data (starting from IEEE 802.11 header)
 * @len: length of frame data in octets
 * @stype: management frame subtype from frame control field
 * @ok: Whether the frame was ACK'ed
 */
void ieee802_11_mgmt_cb(struct hostapd_data *hapd, const u8 *buf, size_t len,
			u16 stype, int ok)
{
	const struct ieee80211_mgmt *mgmt;
	mgmt = (const struct ieee80211_mgmt *) buf;

	switch (stype) {
	case WLAN_FC_STYPE_AUTH:
		wpa_printf(MSG_DEBUG, "mgmt::auth cb");
		handle_auth_cb(hapd, mgmt, len, ok);
		break;
	case WLAN_FC_STYPE_ASSOC_RESP:
		wpa_printf(MSG_DEBUG, "mgmt::assoc_resp cb");
		handle_assoc_cb(hapd, mgmt, len, 0, ok);
		break;
	case WLAN_FC_STYPE_REASSOC_RESP:
		wpa_printf(MSG_DEBUG, "mgmt::reassoc_resp cb");
		handle_assoc_cb(hapd, mgmt, len, 1, ok);
		break;
	case WLAN_FC_STYPE_PROBE_RESP:
		wpa_printf(MSG_DEBUG, "mgmt::proberesp cb");
		break;
	case WLAN_FC_STYPE_DEAUTH:
		/* ignore */
		break;
	case WLAN_FC_STYPE_ACTION:
		wpa_printf(MSG_DEBUG, "mgmt::action cb");
		break;
	default:
		printf("unknown mgmt cb frame subtype %d\n", stype);
		break;
	}
}

int ieee802_11_get_mib(struct hostapd_data *hapd, char *buf, size_t buflen)
{
	/* TODO */
	return 0;
}

int ieee802_11_get_mib_sta(struct hostapd_data *hapd, struct sta_info *sta,
			   char *buf, size_t buflen)
{
	/* TODO */
	return 0;
}

void hostapd_tx_status(struct hostapd_data *hapd, const u8 *addr,
		       const u8 *buf, size_t len, int ack)
{
	struct sta_info *sta;
	struct hostapd_iface *iface = hapd->iface;

	sta = ap_get_sta(hapd, addr);
	if (sta == NULL && iface->num_bss > 1) {
		size_t j;
		for (j = 0; j < iface->num_bss; j++) {
			hapd = iface->bss[j];
			sta = ap_get_sta(hapd, addr);
			if (sta)
				break;
		}
	}
	if (sta == NULL)
		return;
	if (sta->flags & WLAN_STA_PENDING_POLL) {
		wpa_printf(MSG_DEBUG, "STA " MACSTR " %s pending "
			   "activity poll", MAC2STR(sta->addr),
			   ack ? "ACKed" : "did not ACK");
		if (ack)
			sta->flags &= ~WLAN_STA_PENDING_POLL;
	}

	ieee802_1x_tx_status(hapd, sta, buf, len, ack);
}

void ieee802_11_rx_from_unknown(struct hostapd_data *hapd, const u8 *src,
				int wds)
{
	struct sta_info *sta;

	sta = ap_get_sta(hapd, src);
	if (sta && (sta->flags & WLAN_STA_ASSOC)) {
		if (wds && !(sta->flags & WLAN_STA_WDS)) {
			wpa_printf(MSG_DEBUG, "Enable 4-address WDS mode for "
				   "STA " MACSTR " (aid %u)",
				   MAC2STR(sta->addr), sta->aid);
			sta->flags |= WLAN_STA_WDS;
			hapd->drv.set_wds_sta(hapd, sta->addr, sta->aid, 1);
		}
		return;
	}

	wpa_printf(MSG_DEBUG, "Data/PS-poll frame from not associated STA "
		   MACSTR, MAC2STR(src));
	if (sta && (sta->flags & WLAN_STA_AUTH))
		hapd->drv.sta_disassoc(
			hapd, src,
			WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA);
	else
		hapd->drv.sta_deauth(
			hapd, src,
			WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA);
}

#endif /* CONFIG_NATIVE_WINDOWS */


text:
class Author < ActiveRecord::Base
  attr_accessible :name
  has_many :posts
  has_many :comments
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Core Plot (iOS): Source/CPTAnnotationHostLayer.m File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="customdoxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>

Core Plot (iOS)

Cocoa plotting framework for Mac OS X and iOS

Main Page

Animation & Constants

Classes

Files

File List

File Members

CPTAnnotationHostLayer.m File Reference

#import "CPTAnnotationHostLayer.h"

#import "CPTAnnotation.h"

#import "CPTExceptions.h"

   Include dependency graph for CPTAnnotationHostLayer.m:

<map name="_source_2_c_p_t_annotation_host_layer_8m" id="_source_2_c_p_t_annotation_host_layer_8m">
<area shape="rect" id="node3" href="_c_p_t_annotation_host_layer_8h.html" title="CPTAnnotationHostLayer.h" alt="" coords="318,105,511,135"/><area shape="rect" id="node28" href="_c_p_t_annotation_8h.html" title="CPTAnnotation.h" alt="" coords="494,185,623,215"/><area shape="rect" id="node33" href="_c_p_t_exceptions_8h.html" title="CPTExceptions.h" alt="" coords="740,105,869,135"/><area shape="rect" id="node5" href="_c_p_t_layer_8h.html" title="CPTLayer.h" alt="" coords="361,185,453,215"/><area shape="rect" id="node7" href="_c_p_t_responder_8h.html" title="CPTResponder.h" alt="" coords="231,265,358,295"/><area shape="rect" id="node20" href="_c_p_t_definitions_8h.html" title="CPTDefinitions.h" alt="" coords="495,265,623,295"/><area shape="rect" id="node11" href="_c_p_t_platform_specific_defines_8h.html" title="CPTPlatformSpecificDefines.h" alt="" coords="36,345,247,375"/></map>

Generated by


text:
import d3 from 'd3';
import fc from 'd3fc';
import event from '../../event';

export default function() {
    var dispatch = d3.dispatch(event.indicatorChange);

    function editIndicatorGroup(selection) {
        selection.each(function(model) {
            var sel = d3.select(this);

            var div = sel.selectAll('div')
                .data(model.selectedIndicators, function(d) {
                    return d.valueString;
                });

            var containersEnter = div.enter()
                .append('div')
                .attr('class', 'edit-indicator');

            containersEnter.append('span')
                .attr('class', 'icon bf-icon-delete')
                .on('click', dispatch.indicatorChange);

            containersEnter.append('span')
                .attr('class', 'indicator-label')
                .text(function(d) {
                    return d.displayString;
                });

            div.exit()
                .remove();
        });
    }

    d3.rebind(editIndicatorGroup, dispatch, 'on');

    return editIndicatorGroup;

}


text:
package org.hl7.v3;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for MCCI_MT000100UV01.Sender complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="MCCI_MT000100UV01.Sender">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <group ref="{urn:hl7-org:v3}InfrastructureRootElements"/>
 *         <element name="telecom" type="{urn:hl7-org:v3}TEL" minOccurs="0"/>
 *         <element name="device" type="{urn:hl7-org:v3}MCCI_MT000100UV01.Device"/>
 *       </sequence>
 *       <attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/>
 *       <attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" />
 *       <attribute name="typeCode" use="required" type="{urn:hl7-org:v3}CommunicationFunctionType" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MCCI_MT000100UV01.Sender", propOrder = {
    "realmCode",
    "typeId",
    "templateId",
    "telecom",
    "device"
})
public class MCCIMT000100UV01Sender {

    protected List<CS> realmCode;
    protected II typeId;
    protected List<II> templateId;
    protected TEL telecom;
    @XmlElement(required = true)
    protected MCCIMT000100UV01Device device;
    @XmlAttribute(name = "nullFlavor")
    protected List<String> nullFlavor;
    @XmlAttribute(name = "typeCode", required = true)
    protected CommunicationFunctionType typeCode;

    /**
     * Gets the value of the realmCode property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the realmCode property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getRealmCode().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CS }
     *
     *
     */
    public List<CS> getRealmCode() {
        if (realmCode == null) {
            realmCode = new ArrayList<CS>();
        }
        return this.realmCode;
    }

    /**
     * Gets the value of the typeId property.
     *
     * @return
     *     possible object is
     *     {@link II }
     *
     */
    public II getTypeId() {
        return typeId;
    }

    /**
     * Sets the value of the typeId property.
     *
     * @param value
     *     allowed object is
     *     {@link II }
     *
     */
    public void setTypeId(II value) {
        this.typeId = value;
    }

    /**
     * Gets the value of the templateId property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the templateId property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getTemplateId().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link II }
     *
     *
     */
    public List<II> getTemplateId() {
        if (templateId == null) {
            templateId = new ArrayList<II>();
        }
        return this.templateId;
    }

    /**
     * Gets the value of the telecom property.
     *
     * @return
     *     possible object is
     *     {@link TEL }
     *
     */
    public TEL getTelecom() {
        return telecom;
    }

    /**
     * Sets the value of the telecom property.
     *
     * @param value
     *     allowed object is
     *     {@link TEL }
     *
     */
    public void setTelecom(TEL value) {
        this.telecom = value;
    }

    /**
     * Gets the value of the device property.
     *
     * @return
     *     possible object is
     *     {@link MCCIMT000100UV01Device }
     *
     */
    public MCCIMT000100UV01Device getDevice() {
        return device;
    }

    /**
     * Sets the value of the device property.
     *
     * @param value
     *     allowed object is
     *     {@link MCCIMT000100UV01Device }
     *
     */
    public void setDevice(MCCIMT000100UV01Device value) {
        this.device = value;
    }

    /**
     * Gets the value of the nullFlavor property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the nullFlavor property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getNullFlavor().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link String }
     *
     *
     */
    public List<String> getNullFlavor() {
        if (nullFlavor == null) {
            nullFlavor = new ArrayList<String>();
        }
        return this.nullFlavor;
    }

    /**
     * Gets the value of the typeCode property.
     *
     * @return
     *     possible object is
     *     {@link CommunicationFunctionType }
     *
     */
    public CommunicationFunctionType getTypeCode() {
        return typeCode;
    }

    /**
     * Sets the value of the typeCode property.
     *
     * @param value
     *     allowed object is
     *     {@link CommunicationFunctionType }
     *
     */
    public void setTypeCode(CommunicationFunctionType value) {
        this.typeCode = value;
    }

}


text:
class WelcomeController < ApplicationController
  skip_before_action :authenticate_user!
  def index
  end
end


text:
package griffon.plugins.hibernate3;

/**
 * @author Andres Almiray
 */
public interface Hibernate3Mapping {
}


text:
package com.orionplatform.math.polynomial.tasks.calculation;

import java.util.ArrayList;
import java.util.List;
import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.math.number.ANumber;
import com.orionplatform.math.polynomial.Polynomial;

public class GetLegendrePolynomialTask extends Orion
{
    public static synchronized Polynomial run(int degree)
    {
        List<ANumber> legendreCoefficients = new ArrayList<ANumber>();
        legendreCoefficients.add(ANumber.of(1));
        legendreCoefficients.add(ANumber.of(0));
        legendreCoefficients.add(ANumber.of(1));
        int maxDegree = (int) Math.floor(Math.sqrt(2.0 * legendreCoefficients.size())) - 1;

        if(degree > maxDegree)
        {
            legendreCoefficients = computeUpToDegree(degree, maxDegree, legendreCoefficients);
        }

        int start = degree * (degree + 1) / 2;
        ANumber[] a = new ANumber[degree + 1];

        for(int i = 0; i <= degree; i++)
        {
            a[i] = legendreCoefficients.get(start + i);
        }

        return Polynomial.of(a);
    }

    private static synchronized List<ANumber> computeUpToDegree(int degree, int maxDegree, List<ANumber> legendreCoefficients)
    {
        int startK = (maxDegree - 1) * maxDegree / 2;

        for(int k = maxDegree; k < degree; k++)
        {
            int startKm1 = startK;
            startK += k;
            ANumber[] coefficients = new ANumber[3];
            coefficients[0] = ANumber.of(0);
            coefficients[1] = ANumber.of(2 * k + 1).divideGET(k + 1);
            coefficients[2] = ANumber.of(k).divideGET(k + 1);
            ANumber ck = legendreCoefficients.get(startK);
            ANumber ckm1 = legendreCoefficients.get(startKm1);
            legendreCoefficients.add(ck.multiplyGET(coefficients[0]).subtractGET(ckm1.multiplyGET(coefficients[2])));

            for(int i = 1; i < k; ++i)
            {
                ANumber ckPrev = ck.getCopy();
                ck = legendreCoefficients.get(startK + i).getCopy();
                ckm1 = legendreCoefficients.get(startKm1 + i).getCopy();
                legendreCoefficients.add(ck.multiplyGET(coefficients[0]).addGET(ckPrev.multiplyGET(coefficients[1])).subtractGET(ckm1.multiplyGET(coefficients[2])));
            }

            ANumber ckPrev = ck.getCopy();
            ck = legendreCoefficients.get(startK + k).getCopy();
            legendreCoefficients.add(ck.multiplyGET(coefficients[0]).addGET(ckPrev.multiplyGET(coefficients[1])));
            legendreCoefficients.add(ck.multiplyGET(coefficients[1]));
        }

        return legendreCoefficients;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.deliveredtechnologies.rulebook.model.runner Class Hierarchy (rulebook API)</title>
<meta name="date" content="2020-10-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.deliveredtechnologies.rulebook.model.runner

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.deliveredtechnologies.rulebook.model.Auditor

com.deliveredtechnologies.rulebook.model.runner.AbstractRuleBookRunner (implements com.deliveredtechnologies.rulebook.model.RuleBook<T>)

com.deliveredtechnologies.rulebook.model.runner.RuleBookRunner

com.deliveredtechnologies.rulebook.model.runner.RuleBookRunner4PojoClasses

com.deliveredtechnologies.rulebook.model.runner.RuleAdapter (implements com.deliveredtechnologies.rulebook.model.Rule<T,U>)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
class Parameters;
class ExodusModel;

class Volumetric3D {
public:
    // reference type of material properties
    enum MaterialRefType {Absolute, Reference1D, Reference3D, ReferencePerturb};
    const std::vector<std::string> MaterialRefTypeString = {"Absolute",
        "Reference1D", "Reference3D", "ReferencePerturb"};
    const std::vector<std::string> MaterialRefTypeStringShort = {"Abs",
        "Ref1D", "Ref3D", "RefPtb"};

    // allowed keys for material properties
    enum MaterialProperty {VPV, VPH, VSV, VSH, RHO, ANIS_ETA, QKAPPA, QMU, VP, VS,
        C11, C12, C13, C14, C15, C16,
        C22, C23, C24, C25, C26,
        C33, C34, C35, C36,
        C44, C45, C46,
        C55, C56,
        C66
    };
    const std::vector<std::string> MaterialPropertyString = {"VPV", "VPH", "VSV", "VSH",
        "RHO", "ANIS_ETA", "QKAPPA", "QMU", "VP", "VS",
        "C11", "C12", "C13", "C14", "C15", "C16",
        "C22", "C23", "C24", "C25", "C26",
        "C33", "C34", "C35", "C36",
        "C44", "C45", "C46",
        "C55", "C56",
        "C66"
    };
    const std::vector<double> MaterialPropertyAbsSI = {1e3, 1e3, 1e3, 1e3,
        1e3, 1., 1., 1., 1e3, 1e3,
        // Cijkl should be given in GPa
        1e9, 1e9, 1e9, 1e9, 1e9, 1e9,
        1e9, 1e9, 1e9, 1e9, 1e9,
        1e9, 1e9, 1e9, 1e9,
        1e9, 1e9, 1e9,
        1e9, 1e9,
        1e9
    };

    virtual ~Volumetric3D() {finalize();};

    // initialize internal variables if needed
    virtual void initialize() {};
    virtual void initialize(const std::vector<std::string> &params) {initialize();};

    // finalize internal variables if needed
    virtual void finalize() {};

    // get perturbations or absolute values at location r/theta/phi
    // IMPORTANT NOTES:
    // a) This function should be realized such that r/theta/phi are the geocentric
    //    coordinates, without rotating the source to the north pole.
    //    For models given in geographic coordinates, geocentric-to-geographic
    //    conversions from (theta, phi) to (lat, lon) has to be performed internally.
    // b) rElemCenter: radius of the element center, used to decide whether the given
    //    location is within the model range. We use rElemCenter instead of r itself
    //    to honour vertical discontinuities.
    // c) output: properties, refTypes, values
    // d) return: a "false" return means the outputs are all ignored,
    //    e.g., the input location is out of the model range
    virtual bool get3dProperties(double r, double theta, double phi, double rElemCenter,
        std::vector<MaterialProperty> &properties,
        std::vector<MaterialRefType> &refTypes,
        std::vector<double> &values) const = 0;

    // verbose
    virtual std::string verbose() const = 0;

    // set source location, if needed
    virtual void setSourceLocation(double srcLat, double srcLon, double srcDep) {};

    // obtain additional mesh information from ExodusModel, if needed
    virtual void setupExodusModel(const ExodusModel *exModel) {};

    // build from input parameters
    static void buildInparam(std::vector<Volumetric3D *> &models,
        const Parameters &par, const ExodusModel *exModel,
        double srcLat, double srcLon, double srcDep, int verbose);

    // some models may extent into the fluid core
    // but may not create 3D fluid actually
    virtual bool makeFluid3D() const {return false;};

};


text:
// This file contains the constant definitions as well as the required
// data structures to work with on the ECAN module
#ifndef _ECAN_DEFINITIONS_H_
#define _ECAN_DEFINITIONS_H_

#ifdef __cplusplus
	extern "C"{
#endif

#include "stdint.h"

// Message Types either a data message or a remote transmit request
enum can_msg_type {
	CAN_MSG_DATA = 0,
	CAN_MSG_RTR
};

// CAN frame type: either extended (29-bit header) or standard (11-bit header)
enum can_frame_type {
	CAN_FRAME_EXT = 0,
	CAN_FRAME_STD
};

// Data structures
typedef struct {
	uint32_t id;           // The 11-bit or 29-bit message ID
	uint8_t  buffer;       // An internal-use variable referring to buffer this message was received into/sent from.
	uint8_t  message_type; // The message type. See can_msg_type.
	uint8_t  frame_type;   // The frame type. See can_frame_type.
	uint8_t  payload[8];   // The message payload. Stores between 0 and 8 bytes of data.
	uint8_t  validBytes;   // Indicates how many bytes are valid within payload.
} tCanMessage;

typedef union {
	tCanMessage message;
	uint8_t     bytes[sizeof(tCanMessage)];
} CanUnion;

#ifdef __cplusplus
	}
#endif

#endif /* _ECAN_DEFINITIONS_H_ */


text:
package org.apache.aries.jmx.test.bundleb.impl;

import java.util.Dictionary;

import org.apache.aries.jmx.test.bundleb.api.InterfaceB;

/**
 *
 *
 * @version $Rev$ $Date$
 */
@SuppressWarnings("unchecked")
public class B implements InterfaceB {

    private Dictionary<String, Object> conf;

    public boolean invoke() {
       return (conf == null);
    }

    public void configure(Dictionary<String, Object> props) {
        this.conf = props;
    }

    // test cback
    public Dictionary getConfig() {
        return this.conf;
    }
}


text:
#region License

#endregion

namespace OpenCL
{
    using System;
    using System.Diagnostics;

    /// <summary>
    /// Represents an OpenCL context property.
    /// </summary>
    /// <remarks> An OpenCL context property is a (name, value) data pair. </remarks>
    public class OpenCLContextProperty
    {
        #region Fields

        private readonly OpenCLContextProperties name;

        private readonly IntPtr value;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the <see cref="OpenCLContextPropertyName"/> of the <see cref="OpenCLContextProperty"/>.
        /// </summary>
        /// <value> The <see cref="OpenCLContextPropertyName"/> of the <see cref="OpenCLContextProperty"/>. </value>
        public OpenCLContextProperties Name { get { return name; } }

        /// <summary>
        /// Gets the value of the <see cref="OpenCLContextProperty"/>.
        /// </summary>
        /// <value> The value of the <see cref="OpenCLContextProperty"/>. </value>
        public IntPtr Value { get { return value; } }

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a new <see cref="OpenCLContextProperty"/>.
        /// </summary>
        /// <param name="name"> The name of the <see cref="OpenCLContextProperty"/>. </param>
        /// <param name="value"> The value of the created <see cref="OpenCLContextProperty"/>. </param>
        public OpenCLContextProperty(OpenCLContextProperties name, IntPtr value)
        {
            this.name = name;
            this.value = value;
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Gets the string representation of the <see cref="OpenCLContextProperty"/>.
        /// </summary>
        /// <returns> The string representation of the <see cref="OpenCLContextProperty"/>. </returns>
        public override string ToString()
        {
            return GetType().Name + "(" + name + ", " + value + ")";
        }

        #endregion
    }
}


text:
<?php

namespace Foodex\RecipesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Facebook\FacebookSession;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookHttpable;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Foodex\BaseBundle\Entity\User;

class AccountController extends Controller
{
    public function loginAction(Request $request)
    {
        FacebookSession::setDefaultApplication('397176000420165', 'bc416b39fbd5a22ca57eb27cad0f9d25');
        $session = $request->getSession();
        $em = $this->getDoctrine()->getManager();
        //ini_set( 'display_errors', 1 );
        //error_reporting( E_ALL );

        $helper = new FacebookJavaScriptLoginHelper();
        $FB_session = "";
        try {
            $FB_session = $helper->getSession();
        } catch(FacebookRequestException $ex) {
            // When Facebook returns an error
        } catch(\Exception $ex) {
            // When validation fails or other local issues
        }

        if ($FB_session != "") {
            $exists = $session->get('user_ID');
            if(!isset($exists)){
                $user_data = (new FacebookRequest(
                    $FB_session, 'GET', '/me'
                ))->execute()->getGraphObject(GraphUser::className());

                $FB_user_ID = $user_data->getId();
                $name = $user_data->getName();
                $name_data = explode(' ', $name);
                $name = $name_data[0];
                $surname = $name_data[1];
                $photo = "http://graph.facebook.com/".$FB_user_ID."/picture";

                $users_existence = $em->getRepository("FoodexBaseBundle:User")->findOneBy(array("facebookId" => $FB_user_ID));
                if(count($users_existence) == 1){
                    //if user exists
                    $user_ID = $users_existence->getId();
                }else{
                    //if user do not exists
                    $new_user = new User();

                    $new_user->setName($name);
                    $new_user->setSurname($surname);
                    $new_user->setUsername('empty_username');
                    $new_user->setPassword('empty_password');
                    $new_user->setEmail('empty_password');
                    $new_user->setPhoto($photo);
                    $new_user->setCover('/images/food (4).jpg');
                    $new_user->setFacebookId($FB_user_ID);
                    $new_user->setRole("user");
                    $em->persist($new_user);
                    $em->flush();
                    $user_ID = $new_user->getId();
                }

                //set session
                $session->set('user_name', $name);
                $session->set('user_photo', $photo);
                $session->set('user_ID', $user_ID);
            }
        }else{
            $session->remove('user_name');
            $session->remove('user_photo');
            $session->remove('user_ID');
        }

        return "labas";
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Development workflow — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="up" title="Git for development" href="git_development.html" />
    <link rel="next" title="git resources" href="git_resources.html" />
    <link rel="prev" title="Git configuration" href="configure_git.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          next |

          previous |

NumPy v1.8 Manual »

Contributing to Numpy »

Working with NumPy source code »

Git for development »

Development workflow¶

You already have your own forked copy of the NumPy repository, by
following Making your own copy (fork) of NumPy, Set up your fork, you have configured git
by following Git configuration, and have linked the upstream
repository as explained in Linking your repository to the upstream repo.

What is described below is a recommended workflow with Git.

Basic workflow¶

In short:

Update your <tt class="docutils literal">master</tt> branch if it’s not up to date.
Then start a new feature branch for each set of edits that you do.
See below.

Avoid putting new commits in your <tt class="docutils literal">master</tt> branch.

Hack away! See below

Avoid merging other branches into your feature branch while you are
working.

You can optionally rebase if really needed,
see below.

When finished:

Contributors: push your feature branch to your own Github repo, and
ask for code review or make a pull request.

Core developers (if you want to push changes without
further review):

# First, either (i) rebase on upstream -- if you have only few commits
git fetch upstream
git rebase upstream/master

# or, (ii) merge to upstream -- if you have many related commits
git fetch upstream
git merge --no-ff upstream/master

# Recheck that what is there is sensible
git log --oneline --graph
git log -p upstream/master..

# Finally, push branch to upstream master
git push upstream my-new-feature:master

See below.

Note

It’s usually a good idea to use the <tt class="docutils literal">-n</tt> flag to <tt class="docutils literal">git push</tt>
to check first that you’re about to push the changes you want to
the place you want.

This way of working helps to keep work well organized and the history
as clear as possible.

Note

Do not use <tt class="docutils literal">git pull</tt> — this avoids common mistakes if you are
new to Git. Instead, always do <tt class="docutils literal">git fetch</tt> followed by <tt class="docutils literal">git
rebase</tt>, <tt class="docutils literal">git merge --ff-only</tt> or <tt class="docutils literal">git merge --no-ff</tt>,
depending on what you intend.

See also

See discussions on linux git workflow,
and ipython git workflow.

Making a new feature branch¶

To update your master branch, use:

git fetch upstream
git merge upstream/master --ff-only

To create a new branch and check it out, use:

git checkout -b my-new-feature upstream/master

Generally, you will want to keep this branch also on your public github fork
of NumPy.  To do this, you git push this new branch up to your github
repo.  Generally (if you followed the instructions in these pages, and
by default), git will have a link to your github repo, called
<tt class="docutils literal">origin</tt>.  You push up to your own repo on github with:

git push origin my-new-feature

In git >= 1.7 you can ensure that the link is correctly set by using the
<tt class="docutils literal">--set-upstream</tt> option:

git push --set-upstream origin my-new-feature

From now on git will know that <tt class="docutils literal">my-new-feature</tt> is related to the
<tt class="docutils literal">my-new-feature</tt> branch in your own github repo.

The editing workflow¶

Overview¶

# hack hack
git add my_new_file
git commit -am 'ENH: some message'

# push the branch to your own Github repo
git push

In more detail¶

Make some changes

See which files have changed with <tt class="docutils literal">git status</tt> (see git status).
You’ll see a listing like this one:

# On branch my-new-feature
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#  modified:   README
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#  INSTALL
no changes added to commit (use "git add" and/or "git commit -a")

Check what the actual changes are with <tt class="docutils literal">git diff</tt> (git diff).

Add any new files to version control <tt class="docutils literal">git add new_file_name</tt> (see
git add).

To commit all modified files into the local copy of your repo,, do
<tt class="docutils literal">git commit -am 'A commit message'</tt>.  Note the <tt class="docutils literal">-am</tt> options to
<tt class="docutils literal">commit</tt>. The <tt class="docutils literal">m</tt> flag just signals that you’re going to type a
message on the command line.   If you leave it out, an editor will open in
which you can compose your commit message.  For non-trivial commits this is
often the better choice.  The <tt class="docutils literal">a</tt> flag - you can just take on faith - or
see why the -a flag? - and the helpful use-case description in the
tangled working copy problem. The section on
commit messages below might also be useful.

To push the changes up to your forked repo on github, do a <tt class="docutils literal">git
push</tt> (see git push).

Writing the commit message¶

Commit messages should be clear and follow a few basic rules.  Example:

ENH: add functionality X to numpy.<submodule>.

The first line of the commit message starts with a capitalized acronym
(options listed below) indicating what type of commit this is.  Then a blank
line, then more text if needed.  Lines shouldn't be longer than 80
characters.  If the commit is related to a ticket, indicate that with
"See #3456", "See ticket 3456", "Closes #3456" or similar.

Describing the motivation for a change, the nature of a bug for bug fixes or
some details on what an enhancement does are also good to include in a commit
message.  Messages should be understandable without looking at the code
changes.  A commit message like <tt class="docutils literal">MAINT: fixed another one</tt> is an example of
what not to do; the reader has to go look for context elsewhere.

Standard acronyms to start the commit message with are:

API: an (incompatible) API change
BLD: change related to building numpy
BUG: bug fix
DEP: deprecate something, or remove a deprecated object
DEV: development tool or utility
DOC: documentation
ENH: enhancement
MAINT: maintenance commit (refactoring, typos, etc.)
REV: revert an earlier commit
STY: style fix (whitespace, PEP8)
TST: addition or modification of tests
REL: related to releasing numpy

Rebasing on master¶

This updates your feature branch with changes from the upstream NumPy
github repo. If you do not absolutely need to do this, try to avoid
doing it, except perhaps when you are finished.

First, it can be useful to update your master branch:

# go to the master branch
git checkout master
# pull changes from github
git fetch upstream
# update the master branch
git rebase upstream/master
# push it to your Github repo
git push

Then, the feature branch:

# go to the feature branch
git checkout my-new-feature
# make a backup in case you mess up
git branch tmp my-new-feature
# rebase on master
git rebase master

If you have made changes to files that have changed also upstream,
this may generate merge conflicts that you need to resolve.
Finally, remove the backup branch once the rebase succeeded:

git branch -D tmp

Recovering from mess-ups¶

Sometimes, you mess up merges or rebases. Luckily, in Git it is
relatively straightforward to recover from such mistakes.

If you mess up during a rebase:

git rebase --abort

If you notice you messed up after the rebase:

# reset branch back to the saved point
git reset --hard tmp

If you forgot to make a backup branch:

# look at the reflog of the branch
git reflog show my-feature-branch

8630830 my-feature-branch@{0}: commit: BUG: io: close file handles immediately
278dd2a my-feature-branch@{1}: rebase finished: refs/heads/my-feature-branch onto 11ee694744f2552d
26aa21a my-feature-branch@{2}: commit: BUG: lib: make seek_gzip_factory not leak gzip obj
...

# reset the branch to where it was before the botched rebase
git reset --hard my-feature-branch@{2}

If you didn’t actually mess up but there are merge conflicts, you need to
resolve those.  This can be one of the trickier things to get right.  For a
good description of how to do this, see
http://git-scm.com/book/en/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts

Asking for your changes to be merged with the main repo¶

When you feel your work is finished, you can ask for code review, or
directly file a pull request.

Asking for code review¶

Go to your repo URL - e.g. <tt class="docutils literal">http://github.com/your-user-name/numpy</tt>.

Click on the Branch list button:

Click on the Compare button for your feature branch - here <tt class="docutils literal">my-new-feature</tt>:

If asked, select the base and comparison branch names you want to
compare.  Usually these will be <tt class="docutils literal">master</tt> and <tt class="docutils literal">my-new-feature</tt>
(where that is your feature branch name).

At this point you should get a nice summary of the changes.  Copy the
URL for this, and post it to the NumPy mailing list, asking for
review.  The URL will look something like:
<tt class="docutils literal">http://github.com/your-user-name/numpy/compare/master...my-new-feature</tt>.
There’s an example at
http://github.com/matthew-brett/nipy/compare/master...find-install-data
See: http://github.com/blog/612-introducing-github-compare-view for
more detail.

The generated comparison, is between your feature branch
<tt class="docutils literal">my-new-feature</tt>, and the place in <tt class="docutils literal">master</tt> from which you branched
<tt class="docutils literal">my-new-feature</tt>.  In other words, you can keep updating <tt class="docutils literal">master</tt>
without interfering with the output from the comparison.  More detail?
Note the three dots in the URL above (<tt class="docutils literal">master...my-new-feature</tt>) and
see Two and three dots in difference specs.

Filing a pull request¶

When you are ready to ask for the merge of your code:

Go to the URL of your forked repo, say
<tt class="docutils literal">http://github.com/your-user-name/numpy.git</tt>.

Click on the ‘Pull request’ button:

Enter a message; we suggest you select only <tt class="docutils literal">NumPy</tt> as the
recipient.  The message will go to the NumPy core developers.  Please
feel free to add others from the list as you like.

Pushing changes to the main repo¶

When you have a set of “ready” changes in a feature branch ready for
Numpy’s <tt class="docutils literal">master</tt> or <tt class="docutils literal">maintenance/1.5.x</tt> branches, you can push
them to <tt class="docutils literal">upstream</tt> as follows:

First, merge or rebase on the target branch.

Only a few commits: prefer rebasing:

git fetch upstream
git rebase upstream/master

See above.

Many related commits: consider creating a merge commit:

git fetch upstream
git merge --no-ff upstream/master

Check that what you are going to push looks sensible:

git log -p upstream/master..
git log --oneline --graph

Push to upstream:

git push upstream my-feature-branch:master

Note

Avoid using <tt class="docutils literal">git pull</tt> here.

Additional things you might want to do¶

Rewriting commit history¶

Note

Do this only for your own feature branches.

There’s an embarassing typo in a commit you made? Or perhaps the you
made several false starts you would like the posterity not to see.

This can be done via interactive rebasing.

Suppose that the commit history looks like this:

git log --oneline
eadc391 Fix some remaining bugs
a815645 Modify it so that it works
2dec1ac Fix a few bugs + disable
13d7934 First implementation
6ad92e5 * masked is now an instance of a new object, MaskedConstant
29001ed Add pre-nep for a copule of structured_array_extensions.
...

and <tt class="docutils literal">6ad92e5</tt> is the last commit in the <tt class="docutils literal">master</tt> branch. Suppose we
want to make the following changes:

Rewrite the commit message for <tt class="docutils literal">13d7934</tt> to something more sensible.

Combine the commits <tt class="docutils literal">2dec1ac</tt>, <tt class="docutils literal">a815645</tt>, <tt class="docutils literal">eadc391</tt> into a single one.

We do as follows:

# make a backup of the current state
git branch tmp HEAD
# interactive rebase
git rebase -i 6ad92e5

This will open an editor with the following text in it:

pick 13d7934 First implementation
pick 2dec1ac Fix a few bugs + disable
pick a815645 Modify it so that it works
pick eadc391 Fix some remaining bugs

# Rebase 6ad92e5..eadc391 onto 6ad92e5
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

To achieve what we want, we will make the following changes to it:

r 13d7934 First implementation
pick 2dec1ac Fix a few bugs + disable
f a815645 Modify it so that it works
f eadc391 Fix some remaining bugs

This means that (i) we want to edit the commit message for
<tt class="docutils literal">13d7934</tt>, and (ii) collapse the last three commits into one. Now we
save and quit the editor.

Git will then immediately bring up an editor for editing the commit
message. After revising it, we get the output:

[detached HEAD 721fc64] FOO: First implementation
 2 files changed, 199 insertions(+), 66 deletions(-)
[detached HEAD 0f22701] Fix a few bugs + disable
 1 files changed, 79 insertions(+), 61 deletions(-)
Successfully rebased and updated refs/heads/my-feature-branch.

and the history looks now like this:

0f22701 Fix a few bugs + disable
721fc64 ENH: Sophisticated feature
6ad92e5 * masked is now an instance of a new object, MaskedConstant

If it went wrong, recovery is again possible as explained above.

Deleting a branch on github¶

git checkout master
# delete branch locally
git branch -D my-unwanted-branch
# delete branch on github
git push origin :my-unwanted-branch

(Note the colon <tt class="docutils literal">:</tt> before <tt class="docutils literal">test-branch</tt>.  See also:
http://github.com/guides/remove-a-remote-branch

Several people sharing a single repository¶

If you want to work on some stuff with other people, where you are all
committing into the same repository, or even the same branch, then just
share it via github.

First fork NumPy into your account, as from Making your own copy (fork) of NumPy.

Then, go to your forked repository github page, say
<tt class="docutils literal">http://github.com/your-user-name/numpy</tt>

Click on the ‘Admin’ button, and add anyone else to the repo as a
collaborator:

Now all those people can do:

git clone git@githhub.com:your-user-name/numpy.git

Remember that links starting with <tt class="docutils literal">git@</tt> use the ssh protocol and are
read-write; links starting with <tt class="docutils literal">git://</tt> are read-only.

Your collaborators can then commit directly into that repo with the
usual:

git commit -am 'ENH - much better code'
git push origin master # pushes directly into your repo

Exploring your repository¶

To see a graphical representation of the repository branches and
commits:

gitk --all

To see a linear list of commits for this branch:

git log

You can also look at the network graph visualizer for your github
repo.

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime/pprof"

	lr "github.com/pattyshack/abc/src/lr/internal"
	"github.com/pattyshack/abc/src/lr/internal/code_gen"
	"github.com/pattyshack/abc/src/lr/internal/parser"
	"github.com/pattyshack/abc/src/lr/internal/parser/yacc"
)

func main() {
	cpuProfile := flag.String("cpu-profile", "", "write cpu profile to file")

	useYacc := flag.Bool(
		"use-yacc",
		false,
		"Use yacc generated parser instead of bootstrap parser")

	shouldPrintTokens := flag.Bool("print-tokens", false, "For testing only")
	shouldPrintParsed := flag.Bool("print-parsed", false, "For testing only")
	shouldPrintLRStates := flag.Bool("print-lr-states", false, "For testing only")
	shouldPrintGenerated := flag.Bool("print-generated", false, "For testing only")

	language := flag.String("language", "go", "output/target language")
	output := flag.String("o", "", "parser output")
	flag.Parse()

	if *cpuProfile != "" {
		profile, err := os.Create(*cpuProfile)
		if err != nil {
			panic(err)
		}
		defer profile.Close()

		pprof.StartCPUProfile(profile)
		defer pprof.StopCPUProfile()
	}

	if len(flag.Args()) != 1 {
		fmt.Printf("Usage of %s:\n", filepath.Base(os.Args[0]))
		flag.PrintDefaults()
		return
	}

	filename := flag.Args()[0]

	if *shouldPrintTokens {
		printTokens(filename)
	}

	if *shouldPrintParsed {
		printParsed(filename)
	}

	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	var parsed *parser.Grammar
	if *useYacc {
		fmt.Println("Using yacc generated parser")
		parsed, err = yacc.Parse(filename, file)
		if err != nil {
			panic(err)
		}
	} else {
		parsed, err = parser.Parse(filename, file)
		if err != nil {
			panic(err)
		}

	}

	grammar, err := lr.NewGrammar(filename, parsed)
	if err != nil {
		panic(err)
	}

	parsed = nil

	lrStates := lr.NewLRStates(grammar)

	if *shouldPrintLRStates {
		printLRStates(lrStates)
	}

	if *shouldPrintGenerated || *output != "" {
		builder, err := code_gen.GenerateLRCode(grammar, lrStates, *language)
		if err != nil {
			panic(err)
		}

		buffer := bytes.NewBuffer(nil)
		_, err = builder.WriteTo(buffer)

		if err != nil {
			panic(err)
		}

		bytes := buffer.Bytes()

		if *shouldPrintGenerated {
			fmt.Println("File (Generated): ", filename)
			fmt.Println("==================================")

			fmt.Println(string(bytes))
		}

		if *output != "" {
			err = ioutil.WriteFile(*output, bytes, 0664)
			if err != nil {
				panic(err)
			}
		}
	}

	if lrStates.ShiftReduceConflictsCount > 0 ||
		lrStates.ReduceReduceConflictsCount > 0 {

		fmt.Print("conflicts:")

		if lrStates.ShiftReduceConflictsCount > 0 {
			fmt.Print(" ", lrStates.ShiftReduceConflictsCount, " shift/reduce")
		}

		if lrStates.ReduceReduceConflictsCount > 0 {
			fmt.Print(" ", lrStates.ReduceReduceConflictsCount, " reduce/reduce")
		}

		fmt.Print("\n")
	}
}

func printTokens(filename string) {
	fmt.Println("File (Tokens): ", filename)
	fmt.Println("==================================")

	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	lexer := parser.NewLexer(filename, file)

	for {
		token, err := lexer.Next()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}

		fmt.Println(token)
	}
}

func printParsed(filename string) {
	fmt.Println("File (Parsed Definitions): ", filename)
	fmt.Println("==================================")

	yacc.LrErrorVerbose = true

	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	parsed, err := yacc.Parse(filename, file)
	if err != nil {
		panic(err)
	}

	for _, def := range parsed.Definitions {
		fmt.Println(def.Loc())
		fmt.Println(def)
		fmt.Println()
	}

	for _, section := range parsed.AdditionalSections {
		fmt.Println("--------------------------")
		fmt.Println(section.Name.Loc())
		fmt.Println("Additional Section: ", section.Name.Value)
		fmt.Println(section.Content.Value)
	}
}

func printLRStates(states *lr.LRStates) {
	fmt.Println("File (LR States): ", states.Source)
	fmt.Println("==================================")

	symbols := []string{"$", "*"}
	for _, terms := range [][]*lr.Term{states.Terminals, states.NonTerminals} {
		for _, term := range terms {
			symbols = append(symbols, term.Name)
		}
	}

	gotoCount := 0
	reduceCount := 0

	fmt.Println("States:")
	for _, state := range states.OrderedStates {
		reduce := map[string][]string{}
		fmt.Println("    State", state.StateNum, ":")
		fmt.Println("      Kernel Items:")
		firstNonKernel := true
		for _, item := range state.Items {
			if !item.IsKernel && firstNonKernel {
				firstNonKernel = false
				fmt.Println("      Non-kernel Items:")
			}

			if item.IsReduce {
				reduceCount += 1
				reduce[item.LookAhead] = append(
					reduce[item.LookAhead],
					item.Name)
			}
			fmt.Println("       ", item)
		}
		fmt.Println("      Reduce:")
		if len(reduce) == 0 {
			fmt.Println("        (nil)")
		}
		for _, symbol := range symbols {
			list := reduce[symbol]
			if len(list) > 0 {
				fmt.Printf("        %s -> %v\n", symbol, list)
			}
		}
		fmt.Println("      Goto:")
		gotoCount += len(state.Goto)
		for _, symbol := range symbols {
			child, ok := state.Goto[symbol]
			if ok {
				fmt.Printf("        %s -> State %d\n", symbol, child.StateNum)
			}
		}

		fmt.Println()
	}

	fmt.Println("Number of shift actions:", gotoCount)
	fmt.Println("Number of reduce actions:", reduceCount)
}


text:
using System;
using De.Osthus.Ambeth.Log;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using De.Osthus.Ambeth.Xml.Pending;

namespace De.Osthus.Ambeth.Xml.Typehandler
{
    public class ObjectTypeHandler : AbstractHandler, ITypeBasedHandler
    {
        [LogInstance]
        public new ILogger Log { private get; set; }

        public virtual ICommandBuilder CommandBuilder { protected get; set; }

        public override void AfterPropertiesSet()
        {
            base.AfterPropertiesSet();

            ParamChecker.AssertNotNull(CommandBuilder, "CommandBuilder");
        }

        public virtual void WriteObject(Object obj, Type type, IWriter writer)
        {
            writer.WriteStartElementEnd();
            ITypeInfoItem[] members = writer.GetMembersOfType(type);

            String valueAttribute = XmlDictionary.ValueAttribute;
            String primitiveElement = XmlDictionary.PrimitiveElement;
            for (int a = 0, size = members.Length; a < size; a++)
            {
                ITypeInfoItem field = members[a];

                Object fieldValue = field.GetValue(obj, false);
                if (field.RealType.IsPrimitive)
                {
                    writer.WriteStartElement(primitiveElement);
                    String convertedValue = ConversionHelper.ConvertValueToType<String>(fieldValue);
                    writer.WriteAttribute(valueAttribute, convertedValue);
                    writer.WriteEndElement();
                    continue;
                }
                writer.WriteObject(fieldValue);
            }
        }

        public virtual Object ReadObject(Type returnType, Type objType, int id, IReader reader)
        {
            Object obj = Activator.CreateInstance(objType);
            if (id > 0)
            {
                reader.PutObjectWithId(obj, id);
            }
            reader.NextTag();
            ITypeInfoItem[] members = reader.GetMembersOfType(objType);

            int index = 0;
            String valueAttribute = XmlDictionary.ValueAttribute;
            String primitiveElement = XmlDictionary.PrimitiveElement;
            ICommandBuilder commandBuilder = CommandBuilder;
            ICommandTypeRegistry commandTypeRegistry = reader.CommandTypeRegistry;
            IConversionHelper conversionHelper = ConversionHelper;
            while (reader.IsStartTag())
            {
                ITypeInfoItem member = members[index++];
                Object memberValue;
                if (primitiveElement.Equals(reader.GetElementName()))
                {
                    String value = reader.GetAttributeValue(valueAttribute);
                    memberValue = conversionHelper.ConvertValueToType(member.RealType, value);
                    reader.MoveOverElementEnd();
                }
                else
                {
                    memberValue = reader.ReadObject(member.RealType);
                }
                if (memberValue is IObjectFuture)
                {
                    IObjectFuture objectFuture = (IObjectFuture)memberValue;
                    IObjectCommand command = commandBuilder.Build(commandTypeRegistry, objectFuture, obj, member);
                    reader.AddObjectCommand(command);
                }
                else
                {
                    member.SetValue(obj, memberValue);
                }
            }
            return obj;
        }
    }
}