text:
unsigned int create_chrAncestries(const char*, FILE*, FILE*);
unsigned int create_chrAttributes(const char*, FILE*, FILE*);
unsigned int create_chrBloodlines(const char*, FILE*, FILE*);
unsigned int create_chrFactions(const char*, FILE*, FILE*);
unsigned int create_chrRaces(const char*, FILE*, FILE*);
unsigned int create_chrCertificates(const char*, FILE*, FILE*, const char*);
unsigned int create_eveUnits(const char*, FILE*, FILE*);
unsigned int create_dgmAttributeCategories(const char*, FILE*, FILE*);
unsigned int create_dgmAttributeTypes(const char*, FILE*, FILE*);
unsigned int create_dgmEffects(const char*, FILE*, FILE*);
unsigned int create_dgmTypes(const char*, FILE*, FILE*);

unsigned int create_dgm(FILE *mf, const char *certs_yaml) {
	int rc;
	char *src;
	FILE *f = NULL;
	char jsonfile[BUFLEN] = NULLSTR;

	// dgmData
	src = "dgmMeta";
	if (!(f = open_datafile(src))) return 1;
	rc = create_chrAncestries(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_chrAttributes(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_chrBloodlines(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_chrFactions(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_chrRaces(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_chrCertificates(src, mf, f, certs_yaml); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_eveUnits(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_dgmAttributeCategories(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_dgmAttributeTypes(src, mf, f); if (0 != rc) return rc;
	TBLSEP(f, mf); rc = create_dgmEffects(src, mf, f); if (0 != rc) return rc;
	if (close_datafile(src, f)) return 1;

	// dgmTypes
	src = "dgmTypes";
	if (!(f = open_datafile(src))) return 1;
	fprintf(mf, ",\n"); rc = create_dgmTypes(src, mf, f); if (0 != rc) return rc;
	if (close_datafile(src, f)) return 1;

	return 0;
}

unsigned int create_chrAncestries(const char *j, FILE *mf, FILE *f) {
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[1001];
	const char *tbl = "chrAncestries";

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"ancestryName\",\"bloodlineID\",\"description\",\"perception\",\"willpower\",\"charisma\",\"memory\",\"intelligence\",\"iconID\",\"shortDescription\"],\n");
	fprintf(mf, "\"k\":\"ancestryID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM chrAncestries ORDER BY ancestryID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 101);
		fprintf(f, "\"%s\",", txtbuf); // ancestryName
		fprintf(f, "%ld,", sql_column_long(stmt, 2)); // bloodlineID
		sql_column_text(txtbuf, stmt, 3, 1001);
		fprintf(f, "\"%s\",", txtbuf); // description
		fprintf(f, "%ld,", sql_column_long(stmt, 4)); // perception
		fprintf(f, "%ld,", sql_column_long(stmt, 5)); // willpower
		fprintf(f, "%ld,", sql_column_long(stmt, 6)); // charisma
		fprintf(f, "%ld,", sql_column_long(stmt, 7)); // memory
		fprintf(f, "%ld,", sql_column_long(stmt, 8)); // intelligence
		fprintf(f, "%ld,", sql_column_long(stmt, 9)); // iconID
		sql_column_text(txtbuf, stmt, 10, 501);
		fprintf(f, "\"%s\"", txtbuf); // shortDescription
		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_chrAttributes(const char *j, FILE *mf, FILE *f) {
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[1001];
	const char *tbl = "chrAttributes";

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"attributeName\",\"description\",\"iconID\",\"shortDescription\",\"notes\"],\n");
	fprintf(mf, "\"k\":\"attributeID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM chrAttributes ORDER BY attributeID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 101);
		fprintf(f, "\"%s\",", txtbuf); // attributeName
		sql_column_text(txtbuf, stmt, 2, 1001);
		fprintf(f, "\"%s\",", txtbuf); // description
		fprintf(f, "%ld,", sql_column_long(stmt, 3)); // iconID
		sql_column_text(txtbuf, stmt, 4, 501);
		fprintf(f, "\"%s\",", txtbuf); // shortDescription
		sql_column_text(txtbuf, stmt, 5, 501);
		fprintf(f, "\"%s\"", txtbuf); // notes
		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_chrBloodlines(const char *j, FILE *mf, FILE *f) {
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[1001];
	const char *tbl = "chrBloodlines";

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"bloodlineName\",\"raceID\",\"description\",\"maleDescription\",\"femaleDescription\",\"shipTypeID\",\"corporationID\",\"perception\",\"willpower\",\"charisma\",\"memory\",\"intelligence\",\"iconID\",\"shortDescription\",\"shortMaleDescription\",\"shortFemaleDescription\"],\n");
	fprintf(mf, "\"k\":\"bloodlineID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM chrBloodlines ORDER BY bloodlineID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 101);
		fprintf(f, "\"%s\",", txtbuf); // bloodlineName
		fprintf(f, "%ld,", sql_column_long(stmt, 2)); // raceID
		sql_column_text(txtbuf, stmt, 3, 1001);
		fprintf(f, "\"%s\",", txtbuf); // description
		sql_column_text(txtbuf, stmt, 4, 1001);
		fprintf(f, "\"%s\",", txtbuf); // maleDescription
		sql_column_text(txtbuf, stmt, 5, 1001);
		fprintf(f, "\"%s\",", txtbuf); // femaleDescription
		fprintf(f, "%ld,", sql_column_long(stmt, 6)); // shipTypeID
		fprintf(f, "%ld,", sql_column_long(stmt, 7)); // corporationID
		fprintf(f, "%ld,", sql_column_long(stmt, 8)); // perception
		fprintf(f, "%ld,", sql_column_long(stmt, 9)); // willpower
		fprintf(f, "%ld,", sql_column_long(stmt, 10)); // charisma
		fprintf(f, "%ld,", sql_column_long(stmt, 11)); // memory
		fprintf(f, "%ld,", sql_column_long(stmt, 12)); // intelligence
		fprintf(f, "%ld,", sql_column_long(stmt, 13)); // iconID
		sql_column_text(txtbuf, stmt, 14, 501);
		fprintf(f, "\"%s\",", txtbuf); // shortDescription
		sql_column_text(txtbuf, stmt, 15, 501);
		fprintf(f, "\"%s\",", txtbuf); // shortMaleDescription
		sql_column_text(txtbuf, stmt, 16, 501);
		fprintf(f, "\"%s\"", txtbuf); // shortFemaleDescription
		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_chrFactions(const char *j, FILE *mf, FILE *f) {
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[1001];
	const char *tbl = "chrFactions";

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"factionName\",\"description\",\"raceIDs\",\"solarSystemID\",\"corporationID\",\"sizeFactor\",\"stationCount\",\"stationSystemCount\",\"militiaCorporationID\",\"iconID\"],\n");
	fprintf(mf, "\"k\":\"factionID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM chrFactions ORDER BY factionID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 101);
		fprintf(f, "\"%s\",", txtbuf); // factionName
		sql_column_text(txtbuf, stmt, 2, 1001);
		fprintf(f, "\"%s\",", txtbuf); // description
		fprintf(f, "%ld,", sql_column_long(stmt, 3)); // raceIDs
		fprintf(f, "%ld,", sql_column_long(stmt, 4)); // solarSystemID
		fprintf(f, "%ld,", sql_column_long(stmt, 5)); // corporationID
		fprintf(f, "%g,", sql_column_float(stmt, 6)); // sizeFactor
		fprintf(f, "%ld,", sql_column_long(stmt, 7)); // stationCount
		fprintf(f, "%ld,", sql_column_long(stmt, 8)); // stationSystemCount
		fprintf(f, "%ld,", sql_column_long(stmt, 9)); // militiaCorporationID
		fprintf(f, "%ld", sql_column_long(stmt, 10)); // iconID
		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_chrRaces(const char *j, FILE *mf, FILE *f) {
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[1001];
	const char *tbl = "chrRaces";

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"raceName\",\"description\",\"iconID\",\"shortDescription\"],\n");
	fprintf(mf, "\"k\":\"raceID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM chrRaces ORDER BY raceID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 101);
		fprintf(f, "\"%s\",", txtbuf); // raceName
		sql_column_text(txtbuf, stmt, 2, 1001);
		fprintf(f, "\"%s\",", txtbuf); // description
		fprintf(f, "%ld,", sql_column_long(stmt, 3)); // iconID
		sql_column_text(txtbuf, stmt, 4, 501);
		fprintf(f, "\"%s\"", txtbuf); // shortDescription
		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_chrCertificates(const char *j, FILE *mf, FILE *f, const char *certs_yaml) {
	const char *tbl = "chrCertificates";
	FILE *f_yaml = NULL;
	unsigned int count = 0;
	int yret;
	yaml_node_t *node;
	yaml_node_t *bufnode;
	yaml_node_t *valnode;
	yaml_node_pair_t *pair;
	yaml_node_pair_t *bufpair;
	int certID = 0;
	int groupID = 0;
	char *description = NULL;
	char *name = NULL;
	int recommended_idx = 0;
	int skilltypes_idx = 0;
	int first = 0;
	yaml_parser_t parser;
	yaml_document_t ydoc;

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"name\",\"description\",\"groupID\",\"recommendedFor\",\"skillTypes\"],\n");
	fprintf(mf, "\"m\":{\"recommendedFor\":\"[ typeID, ... ]\",\"skillTypes\":\"{ skillID: { certLevel: skillLevel, ... }, ... }\"},\n");
	fprintf(mf, "\"k\":\"raceID\",\n");
	fprintf(mf, "\"t\":\"yaml\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	f_yaml = fopen(certs_yaml, "rb");
	if (f_yaml == NULL) {
		printf("err\n");
		fprintf(stderr, "error opening certs file\n");
		return 1;
	}
	yaml_parser_initialize(&parser);
	yaml_parser_set_input_file(&parser, f_yaml);
	yret = yaml_parser_load(&parser, &ydoc);
	if (!yret) {
		printf("err\n");
		fprintf(stderr, "error parsing certs file\n");
		yaml_parser_delete(&parser);
		return 1;
	}
	// expect first node to be a mapping node for the whole document (certIDs to mappings)
	node = yaml_document_get_root_node(&ydoc);
	if (!node || node->type != YAML_MAPPING_NODE) {
		printf("err\n");
		fprintf(stderr, "error parsing certs file - unexpected root node type\n");
		yaml_parser_delete(&parser);
		return 1;
	}
	first = 1;
	for (pair = node->data.mapping.pairs.start; pair < node->data.mapping.pairs.top; pair++) {
		// get the key node for this mapping; should be the certID
		bufnode = yaml_document_get_node(&ydoc, pair->key);
		if (bufnode->type != YAML_SCALAR_NODE) continue;
		certID = atoi(bufnode->data.scalar.value);

		// get the value node for this mapping; should be another mapping
		bufnode = yaml_document_get_node(&ydoc, pair->value);
		if (bufnode->type != YAML_MAPPING_NODE) continue;
		groupID = 0;
		description = NULL;
		name = NULL;
		recommended_idx = 0;
		skilltypes_idx = 0;
		for (bufpair = bufnode->data.mapping.pairs.start; bufpair < bufnode->data.mapping.pairs.top; bufpair++) {
			// get the key node for this mapping; test for a few things to handle
			valnode = yaml_document_get_node(&ydoc, bufpair->key);
			if (valnode->type != YAML_SCALAR_NODE) continue;
			if (strncmp(valnode->data.scalar.value, "recommendedFor", 14) == 0) recommended_idx = bufpair->value;
			if (strncmp(valnode->data.scalar.value, "skillTypes", 10) == 0) skilltypes_idx = bufpair->value;
			else if (strncmp(valnode->data.scalar.value, "groupID", 7) == 0) {
				valnode = yaml_document_get_node(&ydoc, bufpair->value);
				if (!valnode || valnode->type != YAML_SCALAR_NODE) continue;
				groupID = atoi(valnode->data.scalar.value);
			}
			else if (strncmp(valnode->data.scalar.value, "name", 4) == 0) {
				valnode = yaml_document_get_node(&ydoc, bufpair->value);
				if (!valnode || valnode->type != YAML_SCALAR_NODE) continue;
				name = calloc(valnode->data.scalar.length + 1, sizeof(char));
				memcpy(name, valnode->data.scalar.value, valnode->data.scalar.length);
			}
			else if (strncmp(valnode->data.scalar.value, "description", 4) == 0) {
				valnode = yaml_document_get_node(&ydoc, bufpair->value);
				if (!valnode || valnode->type != YAML_SCALAR_NODE) continue;
				description = calloc(valnode->data.scalar.length + 1, sizeof(char));
				memcpy(description, valnode->data.scalar.value, valnode->data.scalar.length);
			}
		}

		if (!first) fprintf(f, ",\n");
		first = 0;
		fprintf(f, "\"%d\":[\"%s\",\"%s\",\"%d\",", certID, name, description, groupID);
		if (recommended_idx) yaml_json_sequence(f, &ydoc, yaml_document_get_node(&ydoc, recommended_idx));
		else fprintf(f, "null");
		fprintf(f, ",");
		if (skilltypes_idx) yaml_json_mapping(f, &ydoc, yaml_document_get_node(&ydoc, skilltypes_idx));
		else fprintf(f, "null");
		fprintf(f, "]");
		count++;
	}
	yaml_document_delete(&ydoc);
	yaml_parser_delete(&parser);
	fclose(f_yaml);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_eveUnits(const char *j, FILE *mf, FILE *f) {
	const char *tbl = "eveUnits";
	unsigned int count = 0;
	SQLRETURN rc;
	SQLHSTMT stmt;
	char txtbuf[1001];

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"unitName\",\"displayName\",\"description\"],\n");
	fprintf(mf, "\"k\":\"unitID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM eveUnits ORDER BY unitID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 101);
		fprintf(f, "\"%s\",", txtbuf); // unitName
		sql_column_text(txtbuf, stmt, 2, 51);
		fprintf(f, "\"%s\",", txtbuf); // displayName
		sql_column_text(txtbuf, stmt, 3, 1001);
		fprintf(f, "\"%s\"", txtbuf); // description
		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_dgmAttributeCategories(const char *j, FILE *mf, FILE *f) {
	const char *tbl = "dgmAttributeCategories";
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[201];

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"categoryName\",\"categoryDescription\"],\n");
	fprintf(mf, "\"k\":\"categoryID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM dgmAttributeCategories ORDER BY categoryID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 51);
		fprintf(f, "\"%s\",", txtbuf); // categoryName
		sql_column_text(txtbuf, stmt, 2, 201);
		fprintf(f, "\"%s\"", txtbuf); // categoryDescription
		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_dgmAttributeTypes(const char *j, FILE *mf, FILE *f) {
	const char *tbl = "dgmAttributeTypes";
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[1001];

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"attributeName\",\"description\",\"iconID\",\"defaultValue\",\"published\",\"displayName\",\"unitID\",\"stackable\",\"highIsGood\",\"categoryID\"],\n");
	fprintf(mf, "\"k\":\"attributeID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM dgmAttributeTypes ORDER BY attributeID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 101);
		fprintf(f, "\"%s\",", txtbuf); // attributeName
		sql_column_text(txtbuf, stmt, 2, 1001);
		fprintf(f, "\"%s\",", txtbuf); // description
		fprintf(f, "%ld,", sql_column_long(stmt, 3)); // iconID
		fprintf(f, "%g,", sql_column_float(stmt, 4)); // defaultValue
		fprintf(f, "%s,", sql_column_long(stmt, 5) == 0 ? "false" : "true"); // published
		sql_column_text(txtbuf, stmt, 6, 101);
		fprintf(f, "\"%s\",", txtbuf); // // displayName
		fprintf(f, "%ld,", sql_column_long(stmt, 7)); // unitID
		fprintf(f, "%s,", sql_column_long(stmt, 8) == 0 ? "false" : "true"); // stackable
		fprintf(f, "%s,", sql_column_long(stmt, 9) == 0 ? "false" : "true"); // highIsGood
		fprintf(f, "%ld", sql_column_long(stmt, 10)); // categoryID

		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_dgmEffects(const char *j, FILE *mf, FILE *f) {
	const char *tbl = "dgmEffects";
	SQLRETURN rc;
	SQLHSTMT stmt;
	unsigned int count = 0;
	char txtbuf[1001];

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"effectName\",\"effectCategory\",\"preExpression\",\"postExpression\",\"description\",\"guid\",\"iconID\",\"isOffensive\",\"isAssistance\",\"durationAttributeID\",\"trackingSpeedAttributeID\",\"dischargeAttributeID\",\"rangeAttributeID\",\"falloffAttributeID\",\"disallowAutoRepeat\",\"published\",\"displayName\",\"isWarpSafe\",\"rangeChance\",\"electronicChance\",\"propulsionChance\",\"distribution\",\"sfxName\",\"npcUsageChanceAttributeID\",\"npcActivationChanceAttributeID\",\"fittingUsageChanceAttributeID\"],\n");
	fprintf(mf, "\"k\":\"attributeID\",\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT * FROM dgmEffects ORDER BY effectID", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		fprintf(f, "\"%ld\":[", sql_column_long(stmt, 0));
		sql_column_text(txtbuf, stmt, 1, 401);
		fprintf(f, "\"%s\",", txtbuf); // effectName
		fprintf(f, "%ld,", sql_column_long(stmt, 2)); // effectCategory
		fprintf(f, "%ld,", sql_column_long(stmt, 3)); // preExpression
		fprintf(f, "%ld,", sql_column_long(stmt, 4)); // postExpression
		sql_column_text(txtbuf, stmt, 5, 1001);
		fprintf(f, "\"%s\",", txtbuf); // description
		sql_column_text(txtbuf, stmt, 6, 61);
		fprintf(f, "\"%s\",", txtbuf); // guid
		fprintf(f, "%ld,", sql_column_long(stmt, 7)); // iconID
		fprintf(f, "%s,", sql_column_long(stmt, 8) == 0 ? "false" : "true"); // isOffensive
		fprintf(f, "%s,", sql_column_long(stmt, 9) == 0 ? "false" : "true"); // isAssistance
		fprintf(f, "%ld,", sql_column_long(stmt, 10)); // durationAttributeID
		fprintf(f, "%ld,", sql_column_long(stmt, 11)); // trackingSpeedAttributeID
		fprintf(f, "%ld,", sql_column_long(stmt, 12)); // dischargeAttributeID
		fprintf(f, "%ld,", sql_column_long(stmt, 13)); // rangeAttributeID
		fprintf(f, "%ld,", sql_column_long(stmt, 14)); // falloffAttributeID
		fprintf(f, "%s,", sql_column_long(stmt, 15) == 0 ? "false" : "true"); // disallowAutoRepeat
		fprintf(f, "%s,", sql_column_long(stmt, 16) == 0 ? "false" : "true"); // published
		sql_column_text(txtbuf, stmt, 17, 101);
		fprintf(f, "\"%s\",", txtbuf); // // displayName
		fprintf(f, "%s,", sql_column_long(stmt, 18) == 0 ? "false" : "true"); // isWarpSafe
		fprintf(f, "%s,", sql_column_long(stmt, 19) == 0 ? "false" : "true"); // rangeChance
		fprintf(f, "%s,", sql_column_long(stmt, 20) == 0 ? "false" : "true"); // electronicChance
		fprintf(f, "%s,", sql_column_long(stmt, 21) == 0 ? "false" : "true"); // propulsionChance
		fprintf(f, "%ld,", sql_column_long(stmt, 22)); // distribution
		sql_column_text(txtbuf, stmt, 23, 21);
		fprintf(f, "\"%s\",", txtbuf); // sfxName
		fprintf(f, "%ld,", sql_column_long(stmt, 24)); // npcUsageChanceAttributeID
		fprintf(f, "%ld,", sql_column_long(stmt, 25)); // npcActivationChanceAttributeID
		fprintf(f, "%ld", sql_column_long(stmt, 26)); // fittingUsageChanceAttributeID

		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}

unsigned int create_dgmTypes(const char *j, FILE *mf, FILE *f) {
	const char *tbl = "dgmTypes";
	SQLRETURN rc;
	SQLHSTMT stmt;
	SQLHSTMT substmt;
	SQLINTEGER typeID;
	SQLINTEGER valueInt;
	SQLFLOAT valueFloat;
	unsigned int count = 0;
	char sql[BUFLEN] = NULLSTR;

	// meta
	fprintf(mf, "\"%s\":{\n", tbl);
	fprintf(mf, "\"j\":\"%s\",\n", j);
	fprintf(mf, "\"c\":[\"attributes\",\"effects\"],\n");
	fprintf(mf, "\"k\":\"typeID\",\n");
	fprintf(mf, "\"m\":{\"attributes\":\"{ attributeID: value, ... }\",\"effects\":\"{ effectID: isDefault, ... }\"},\n");
	fprintf(mf, "\"t\":\"sql\",\n");

	// data
	fprintf(f, "\"%s\":{\n", tbl);
	fprintf(f, "\"d\":{\n");
	rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC, &stmt);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC, 1);
	rc = SQLExecDirect(stmt, "SELECT typeID FROM dgmTypeEffects UNION SELECT typeID FROM dgmTypeAttributes ORDER BY 1", SQL_NTS);
	if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, stmt, 1);
	rc = SQLFetch(stmt);
	while (SQL_SUCCEEDED(rc)) {
		typeID = sql_column_long(stmt, 0);
		fprintf(f, "\"%ld\":[", typeID);

		// attributes
		fprintf(f, "{");
		rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC2, &substmt);
		if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC2, 1);
		SNPRINTF(sql, BUFLEN, "SELECT * FROM dgmTypeAttributes WHERE typeID = %ld ORDER BY attributeID\0", typeID);
		rc = SQLExecDirect(substmt, sql, SQL_NTS);
		if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, substmt, 1);
		rc = SQLFetch(substmt);
		while (SQL_SUCCEEDED(rc)) {
			fprintf(f, "\"%ld\":", sql_column_long(substmt, 1));
			valueInt = sql_column_long(substmt, 2);
			valueFloat = sql_column_float(substmt, 3);
			if (valueFloat != 0) fprintf(f, "%g", valueFloat);
			else fprintf(f, "%ld", valueInt);
			rc = SQLFetch(substmt);
			if (SQL_SUCCEEDED(rc)) fprintf(f, ",");
		}
		fprintf(f, "},");
		SQLFreeHandle(SQL_HANDLE_STMT, substmt);

		// effects
		fprintf(f, "{");
		rc = SQLAllocHandle(SQL_HANDLE_STMT, H_DBC2, &substmt);
		if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_DBC, H_DBC2, 1);
		SNPRINTF(sql, BUFLEN, "SELECT * FROM dgmTypeEffects WHERE typeID = %ld ORDER BY effectID\0", typeID);
		rc = SQLExecDirect(substmt, sql, SQL_NTS);
		if (!SQL_SUCCEEDED(rc)) return dump_sql_error(rc, SQL_HANDLE_STMT, substmt, 1);
		rc = SQLFetch(substmt);
		while (SQL_SUCCEEDED(rc)) {
			fprintf(f, "\"%ld\":", sql_column_long(substmt, 1));
			fprintf(f, "%s", sql_column_long(substmt, 2) == 0 ? "false" : "true"); // isDefault
			rc = SQLFetch(substmt);
			if (SQL_SUCCEEDED(rc)) fprintf(f, ",");
		}
		fprintf(f, "}");
		SQLFreeHandle(SQL_HANDLE_STMT, substmt);

		rc = SQLFetch(stmt);
		if (SQL_SUCCEEDED(rc)) fprintf(f, "],\n");
		else fprintf(f, "]\n");
		count++;
	}
	SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	fprintf(f, "}\n}");

	fprintf(mf, "\"l\":%u\n}", count);

	return 0;
}


text:
using namespace std;

bool QueenProblem::isInserted(int queen_row, int queen_col) {

    // Check the
    // current row
    for (int j = 0; j < queen_col; ++j) {
        if(board[queen_row][j] == 1) {
            // The queen can't be
            // placed in this cell
            return false;
        }
    }

    for (int j = queen_col+1; j <size; ++j) {
        if(board[queen_row][j] == 1) {
            // The queen can't be
            // placed in this cell
            return false;
        }
    }

    // Check the upper
    // left diagonal
    for (int i = queen_row, j = queen_col; i > -1 && j > -1; --i, --j) {
        if(board[i][j] == 1) {
            // The queen can't be
            // placed in this cell
            return false;
        }
    }

    // Check the lower
    // left diagonal
    for (int i = queen_row, j = queen_col; i < size && j > -1; ++i, --j) {
        if(board[i][j] == 1) {
            // The queen can't be
            // placed in this cell
            return false;
        }
    }

    // Check the upper
    // right diagonal
    for (int i = queen_row, j = queen_col; i > -1 && j < size; --i, ++j) {
        if(board[i][j] == 1) {
            // The queen can't be
            // placed in this cell
            return false;
        }
    }

    // Check the upper
    // right diagonal
    for (int i = queen_row, j = queen_col; i < size && j < size; ++i, ++j) {
        if(board[i][j] == 1) {
            // The queen can't be
            // placed in this cell
            return false;
        }
    }

    // The queen can be
    // placed in this cell
    return true;
}

void QueenProblem::initialize(const int size) {

    if(isInitialized()) {
        // Clear memory
        for (int i = 0; i < size; ++i) {
            delete[] board[i];
        }
        delete[] board;
    }

    numberOfSolutions = 0;
    this->size = size;

    // Initialize the
    // two-dimensional array
    board = new int*[size];
    for(int i = 0; i < size; ++i)
        board[i] = new int[size];

    // Fill in the array
    for (int i = 0; i < size; ++i) {
        for (int j = 0; j < size; ++j) {
            board[i][j] = 42; // The meaning of life
        }
    }

    // Mark the array as initialized
    initialized = true;
}

bool QueenProblem::isInitialized() {
    return initialized;
}

bool QueenProblem::isSolved() {
    return solved;
}

long QueenProblem::getNumberOfSolutions(){

    if(!isSolved()) {
        throw std::logic_error("Error!");
    }
    return numberOfSolutions;
}

void QueenProblem::backtracking(int queen) {

    // Check if the method was
    // called after initialization
    if (isInitialized() && (size > 0)) {

        if (size == 1){
            // There is only one
            // solution to the problem
            numberOfSolutions = 1;
            solved = true;
            return;
        }
        // Check if the task has
        // a solution
        if (size > 1 && size < 4) {
            solved = true;
            return;
        } else {
            if (queen == size) {
                // Increment the number
                // of solutions
                ++numberOfSolutions;

                // Mark the task
                // as solved
                solved = true;

                return;
            }

            for (int currentRow = 0; currentRow < size; ++currentRow) {

                // Check if placing a
                // queen here is safe
                if (isInserted(currentRow, queen)) {

                    // Mark the current
                    // cell as reserved
                    board[currentRow][queen] = 1;

                    // Find a proper cell
                    // for the next queen
                    backtracking(queen + 1);

                    // Mark the cell as free
                    // because the solution
                    // didn't work if this code
                    // is reached
                    board[currentRow][queen] = 42;
                }
            }
            return;
        }
    } else {
        throw std::logic_error("Error!");
    }
}

QueenProblem::~QueenProblem() {

    // Clear memory
    for (int i = 0; i < size; ++i) {
        delete[] board[i];
    }
    delete[] board;
}

redpajama_set_name: RedPajamaGithub


text:
const initialState = {
  offices: [
    {abbreviation: 'JC3W', name: 'Some Office 1', id: 1},
    {abbreviation: 'DC3W', name: 'Some Office 2', id: 2},
    {abbreviation: 'J22W', name: 'Some Office 3', id: 3},
    {abbreviation: 'Rw3W', name: 'Some Office 4', id: 4}
  ]
};

export function officeState(state = initialState, action) {
    const {type} = action;

    switch (type) {
        default:
            return state;
    }
}


text:
package xworker.app.monitor.res;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import org.xmeta.World;
import org.xmeta.util.ExceptionUtil;
import org.xmeta.util.UtilMap;

import xworker.app.monitor.db.DbTask;
import xworker.dataObject.DataObject;

public class ResourceTask extends MonitableTask implements Runnable{
	private static Logger logger = LoggerFactory.getLogger(DbTask.class);

	public List<DataObject> resources;

	public ResourceTask(MonitorContext message, ActionContext actionContext, DataObject monitor, DataObject monitorTask, DataObject task, List<DataObject> resources){
		super(message, monitorTask, task, resources, actionContext);

		this.resources = resources;
	}

	public void doTask(){
		try{
			Thing taskThing = World.getInstance().getThing(monitorTaskTask.getString("taskPath"));
			if(taskThing == null){
				monitorContext.appendContent(monitorTask, null, null, "TaskThing not exists");
			}else{
				String result = (String) taskThing.doAction("run", actionContext, UtilMap.toMap("monitor", monitor, "monitorTaskTask", monitorTaskTask, "resources", resources,
						"monitorTask", monitorTask, "monitorContext", monitorContext, "taskThing", taskThing,
						"paramBindings", paramBindings));

				if(result != null){
					monitorContext.appendContent(monitorTask, null, null, result);
				}
			}
		}catch(Exception e){
			logger.error("Execute dbmonitor dbtask error," +
					"monitorid=" + monitor.getString("id") + ", monitorname=" + monitor.getString("monitor") +
					",taskid=" + monitorTaskTask.get("id") + ",taskname=" + monitorTaskTask.getString("name"), e);
			monitorContext.appendContent(monitorTask, null, null, ExceptionUtil.getRootMessage(e));
		}
	}

}


text:
"""Base class for tests in this module."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import imp

from tensorflow.contrib.py2tf.pyct import context
from tensorflow.contrib.py2tf.pyct import parser
from tensorflow.contrib.py2tf.pyct import qual_names
from tensorflow.contrib.py2tf.pyct.static_analysis import activity
from tensorflow.contrib.py2tf.pyct.static_analysis import live_values
from tensorflow.contrib.py2tf.pyct.static_analysis import type_info
from tensorflow.python.platform import test

class TestCase(test.TestCase):
  """Base class for unit tests in this module. Contains relevant utilities."""

  def make_fake_tf(self, *symbols):
    fake_tf = imp.new_module('fake_tf')
    for s in symbols:
      setattr(fake_tf, s.__name__, s)
    return fake_tf

  def attach_namespace(self, module, **ns):
    for k, v in ns.items():
      setattr(module, k, v)

  def parse_and_analyze(self,
                        test_fn,
                        namespace,
                        namer=None,
                        arg_types=None,
                        include_type_analysis=True,
                        recursive=True):
    node, source = parser.parse_entity(test_fn)
    ctx = context.EntityContext(
        namer=namer,
        source_code=source,
        source_file=None,
        namespace=namespace,
        arg_values=None,
        arg_types=arg_types,
        recursive=recursive)
    node = qual_names.resolve(node)
    node = activity.resolve(node, ctx)
    node = live_values.resolve(node, ctx, {})
    if include_type_analysis:
      node = type_info.resolve(node, ctx)
      node = live_values.resolve(node, ctx, {})
    self.ctx = ctx
    return node


text:
@class NWPDFPage, NWPDFAnnotation, NWPDFSinglePageView;

@protocol NWPDFAnnotationView <NSObject>
@property (nonatomic, strong) NWPDFAnnotation *annotation;
@optional
- (BOOL)shouldReceiveTouchForLocation:(CGPoint)location;
@end

@interface NWPDFPageView : UIView
- (id)initWithFrame:(CGRect)frame page:(NWPDFPage *)page;
@end

@protocol NWPDFSinglePageViewDelegate <NSObject>
@optional
- (UIView <NWPDFAnnotationView>*)pageView:(NWPDFSinglePageView *)pageView viewForAnnotation:(NWPDFAnnotation *)annotation;
@end

@interface NWPDFSinglePageView : UIView

@property (nonatomic, readonly) NWPDFPage *page;
@property (nonatomic, readonly) NWPDFPageView *pdfView;
@property (nonatomic, readonly) id<NWPDFSinglePageViewDelegate>annotationDelegate;
@property (nonatomic, readonly) NSMutableArray *annotationViews;

- (id)initWithPage:(NWPDFPage *)page annotationDelegate:(id<NWPDFSinglePageViewDelegate>)annotationDelegate;
- (void)setImage:(UIImage *)image;

@end

@interface NWPDFSinglePageZoomView : UIScrollView <NWPDFSinglePageViewDelegate, UIScrollViewDelegate>

@property (nonatomic, readonly) NWPDFPage *page;
@property (nonatomic, readonly) id<NWPDFSinglePageViewDelegate>annotationDelegate;
@property (nonatomic, readonly) NSMutableArray *annotationViews;
@property (nonatomic, readonly) NWPDFPageView *pdfView;

- (id)initWithPage:(NWPDFPage *)page annotationDelegate:(id<NWPDFSinglePageViewDelegate>)annotationDelegate;
- (void)setImage:(UIImage *)image;

@end


text:
layout: example
categories: example/v1.0.0
version: v1.0.0
title: Places from Foursquare
description: Use Foursquare's API to request points of interest on a map like Cafes.
tags:
  - markers
---


text:
package pastis

import (
	"fmt"
	"io"
	"log"
	"os"
)

//An API Logger whose level is configurable
type Logger struct {
	level int
	info  *log.Logger
	debug *log.Logger
	fatal *log.Logger
	warn  *log.Logger
	err   *log.Logger
}

const (
	DEBUG = 1
	INFO  = 2
	WARN  = 3
	ERROR = 4
	FATAL = 5
	OFF   = 6
)

//Level converts a strong value of a level into into its integer value
func LevelInt(level string) int {
	switch {
	case "INFO" == level:
		return INFO
	case "DEBUG" == level:
		return DEBUG
	case "WARN" == level:
		return WARN
	case "ERROR" == level:
		return ERROR
	case "FATAL" == level:
		return FATAL
	}
	return OFF  //default level
}

// GetLogger retrieves a logger having the given level.
// The level defines the minimum set of levels recognized by the system, that is OFF, FATAL, ERROR, WARN, INFO, DEBUG and ALL.
func GetLogger(level string) *Logger {
	levelInt := LevelInt(level)
	pastisLogger := &Logger{level: levelInt}
	pastisLogger.info = nativeLogger(os.Stdout, "INFO", log.Ldate|log.Ltime)
	pastisLogger.debug = nativeLogger(os.Stdout, "DEBUG", log.Ldate|log.Ltime)
	pastisLogger.warn = nativeLogger(os.Stdout, "WARN", log.Ldate|log.Ltime)
	pastisLogger.err = nativeLogger(os.Stdout, "ERROR", log.Ldate|log.Ltime)
	pastisLogger.fatal = nativeLogger(os.Stdout, "FATAL", log.Ldate|log.Ltime)
	return pastisLogger
}

func nativeLogger(w io.Writer, prefix string, flag int) *log.Logger {
	return log.New(w, fmt.Sprintf("%s: ", prefix), flag)
}

// Set the minimum set of levels recognized by the system, that is OFF, FATAL, ERROR, WARN, INFO, DEBUG and ALL.
func (logger *Logger) SetLevel(level string) {
	logger.level = LevelInt(level)
}

//SetOutput sets the output destination for the logger having the given level.
func (logger *Logger) SetOutputs(w io.Writer, flag int, levels ...string) {
	for _, l := range levels {
		logger.SetOutput(l, w, flag)
	}
}

//SetOutput sets the output destination for the logger having the given level.
func (logger *Logger) SetOutput(level string, w io.Writer, flag int) {
	levelNum := LevelInt(level)
	switch {
	case INFO == levelNum:
		logger.info = nativeLogger(w, level, flag)
	case DEBUG == levelNum:
		logger.debug = nativeLogger(w, level, flag)
	case WARN == levelNum:
		logger.warn = nativeLogger(w, level, flag)
	case ERROR == levelNum:
		logger.err = nativeLogger(w, level, flag)
	case FATAL == levelNum:
		logger.fatal = nativeLogger(w, level, flag)
	default:
	}
}

//Log a message object with the INFO level. Arguments are handled in the manner of fmt.Print.
func (logger *Logger) Info(s string) {
	if INFO >= logger.level {
		logger.info.Print(s)
	}
}

//Log a message object with the DEBUG level. Arguments are handled in the manner of fmt.Print.
func (logger *Logger) Debug(s string) {
	if DEBUG >= logger.level {
		logger.debug.Print(s)
	}
}

//Log a message object with the ERROR level. Arguments are handled in the manner of fmt.Print.
func (logger *Logger) Error(s string) {
	if ERROR >= logger.level {
		logger.err.Print(s)
	}
}

//Log a message object with the FATAL level. Arguments are handled in the manner of fmt.Print.
func (logger *Logger) Fatal(s string) {
	if FATAL >= logger.level {
		logger.fatal.Print(s)
	}
}

//Log a message object with the WARN level. Arguments are handled in the manner of fmt.Print.
func (logger *Logger) Warn(s string) {
	if WARN >= logger.level {
		logger.warn.Print(s)
	}
}

//Log a message object with the INFO level. Arguments are handled in the manner of fmt.Printf.
func (logger *Logger) Infof(format string, v ...interface{}) {
	if INFO >= logger.level {
		logger.info.Printf(format, v...)
	}
}

//Log a message object with the DEBUG level. Arguments are handled in the manner of fmt.Printf.
func (logger *Logger) Debugf(format string, v ...interface{}) {
	if DEBUG >= logger.level {
		logger.debug.Printf(format, v...)
	}
}

//Log a message object with the ERROR level. Arguments are handled in the manner of fmt.Printf.
func (logger *Logger) Errorf(format string, v ...interface{}) {
	if ERROR >= logger.level {
		logger.err.Printf(format, v...)
	}
}

//Log a message object with the FATAL level. Arguments are handled in the manner of fmt.Printf.
func (logger *Logger) Fatalf(format string, v ...interface{}) {
	if FATAL >= logger.level {
		logger.fatal.Printf(format, v...)
	}
}

//Log a message object with the WARN level. Arguments are handled in the manner of fmt.Printf.
func (logger *Logger) Warnf(format string, v ...interface{}) {
	if WARN >= logger.level {
		logger.warn.Printf(format, v...)
	}
}


text:
UNFINISHED_TEMPLATE //delete me

var MemoryGame = (function() { //begin game IIFE

var MemoryCardModel = Backbone.Model.extend({
    defaults: {status:'facedown'}
});

var MemoryCollection = Backbone.Collection.extend({
  model: MemoryCardModel,
});

// Ctor:
function MemoryGame(cardset) {
  //...

  this.cards = new MemoryCollection();

  this.length //= something;

  this.reset = function() {
        //...
  }

  this.lift=function(here) { //here should be a number
    // lift will include these somewhere:
    if (this.gui)
        this.gui.removeSoon([here,there]);
    //...
    if (this.gui)
        this.gui.hideSoon([here,there]);
    //...
    if (this.gui)
        this.gui.show(here,faceVal);
    //...
  };

}; // end ctor

return MemoryGame;
})(); //end game IIFE

var cards = null, gui = null, game = null;  //global for debugging
$(function() {
    cards = new MemoryCards();
    game = new MemoryGame(cards);

	gui = new MemoryGUI(game); //make a gui
    game.gui = gui; //attach gui to game/collection
});


text:
@interface STQRCodeMainVC : STMainBaseVC

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Curso Online Abierto [Seguridad-2016 Hacking ético (2ª ed.)] El Reto - Codernewbie</title>

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Curso Online Abierto [Seguridad-2016 Hacking ético (2ª ed.)] El Reto">
    <meta name="twitter:description" content="">

    <meta property="og:type" content="article">
    <meta property="og:title" content="Curso Online Abierto [Seguridad-2016 Hacking ético (2ª ed.)] El Reto">
    <meta property="og:description" content="">

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

    <link rel="stylesheet" type="text/css" href="//neocarvajal.github.io/themes/uno/assets/css/uno.css?v=1476461059390" />

    <link rel="canonical" href="https://neocarvajal.github.io/2016/10/14/Curso-Online-Abierto-Seguridad-2016-Hacking-etico-2-ed-El-Reto.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Codernewbie" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Curso Online Abierto [Seguridad-2016 Hacking ético (2ª ed.)] El Reto" />
    <meta property="og:description" content="Llegamos al final del Curso abierto de Hacking Ético junto al equipo de Mondragon Unibersitatea, en esta ocasión hablaré un poco sobre la experiencia en el curso y hacer memoria de lo que fue el reto final para conseguir las insignias. El Enigma Para muchos todo el rollo del reto" />
    <meta property="og:url" content="https://neocarvajal.github.io/2016/10/14/Curso-Online-Abierto-Seguridad-2016-Hacking-etico-2-ed-El-Reto.html" />
    <meta property="article:tag" content="mooc" />
    <meta property="article:tag" content="hacking ético" />
    <meta property="article:tag" content=" moocHackingMU" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Curso Online Abierto [Seguridad-2016 Hacking ético (2ª ed.)] El Reto" />
    <meta name="twitter:description" content="Llegamos al final del Curso abierto de Hacking Ético junto al equipo de Mondragon Unibersitatea, en esta ocasión hablaré un poco sobre la experiencia en el curso y hacer memoria de lo que fue el reto final para conseguir las insignias. El Enigma Para muchos todo el rollo del reto" />
    <meta name="twitter:url" content="https://neocarvajal.github.io/2016/10/14/Curso-Online-Abierto-Seguridad-2016-Hacking-etico-2-ed-El-Reto.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Codernewbie" href="https://neocarvajal.github.io/rss/" />

Codernewbie

Blog personal donde encontraras información acerca de lo ultimo que he estado haciendo en mis ratos libres

Blog

                      Facebook

                      Twitter

                      Github

                      Instagram

                      Email

        <time datetime="14 Oct 2016" class="post-meta__date date">14 Oct 2016</time> • on mooc, hacking ético,  moocHackingMU
         by Erick Carvajal R

Curso Online Abierto [Seguridad-2016 Hacking ético (2ª ed.)] El Reto

Llegamos al final del Curso abierto de Hacking Ético junto al equipo de Mondragon Unibersitatea, en esta ocasión hablaré un poco sobre la experiencia en el curso y hacer memoria de lo que fue el reto final para conseguir las insignias.

El Enigma

Para muchos todo el rollo del reto comenzó al momento de conseguir la solución al enigma planteado en el moocHackingMU o por lo menos ese fue mi caso, donde después de seguir cada paso en la plataforma controlada "pruebas.euskalert.net", seguir el consejo de Yoda y usar un poco de la fuerza ("use the force") pude descifrar el archivo con el mensaje del consejo y de esa forma unirme al grupo secreto antes de que publicaran en la web.

Antes del Reto

Luego de ver que necesitaba un grupo para entrar en el reto, un compañero de mi país (Venezuela) me contacto para ser parte del "Quigon Hacking Team". El consejo nos dio el server del team 0004 (45.55.68.249) para realizar todas las configuraciones que el equipo considerada de manera que al empezar el reto nuestro server soportara los ataques y a la vez como grupo plantearnos una estrategia de ataque.

Dentro del equipo me dedique a hacer pruebas contra el servidor con algunos script que explotaban vulnerabilidades de gitlist y cacti que para el momento de hacerlas no tenían éxito por el trabajo que el grupo venia realizando en el sever, por lo que tome la decisión de tratar proteger los servicios en vista de que todos se preocuparon lo suficiente por las aplicaciones disponibles.

Note que muchas personas dentro del curso trabajaban con Kali Linux y al saber de las herramientas que tienen a disposición sabia que intentarían ataques de fuerza bruta, DoS, DDoS, así que investigando un poco conseguí un modulo de apache que no viene por defecto pero puede ser instalado y configurado sin problemas:

Instalando modulo evasion:

apt-get -y install libapache2-mod-evasive

Creando directorios para log:

mkdir -p /var/log/apache2/evasive

Asignando permisos:

chown -R www-data:root /var/log/apache2/evasive

Una vez instalado el modulo tocaba hacer algunos cambios en el archivo de configuración

DOSHashTableSize

DOSPageCount  # máximo número de peticiones a la misma página

DOSSiteCount   # número total de peticiones para cualquier objeto por el mismo cliente IP en el mismo listener

DOSPageInterval # intervalo para la página

DOSSiteInterval  # intervalo para el sitio

DOSBlockingPeriod # tiempo en que estará bloqueado un cliente

DOSLogDir # directorio de log

DOSEmailNotify # email de notificación

Luego dentro del archivo compartido del grupo cada persona fue escribiendo los cambios importantes que hacían dentro del server. Otro punto era la personalización de nuestro server y para cuando yo estaba haciendo algunas pruebas ya un compañero había realizado un index dentro del server que se veía de esta forma:

Así que trabaje un poco con Yeoman.io para generar un index que a final de cuentas quedo como un index secundario dentro del server:

Lo pueden ver mejor en la siguiente dirección 45.55.68.249

El Reto

El reto comenzó y la verdad es que no estaba preparado como atacante (sin herramientas efectivas como metasploit entre otros), me toco hacer varios ataques manuales, pero en ese tiempo perdí comunicación con el equipo y para cuando pude obtener un archivo cifrado (nivel 1) de otro equipo ya era tarde porque mi equipo había conseguido atacar varios niveles del mismo con éxito, dejando como rastro un pequeño mensaje en cada index.

Tareas

Cuando empece en este curso no sabia si podría finalizarlo con éxito con las características del equipo que tenia en frente:

Igual seguí adelante hasta que llego el punto de la instalación de una maquina virtual para la tarea de SQL Inyection donde la poca memoria de mi pc (unos 700mb) se quedaba corta a la hora de correr la maquina virtual. De resto pude realizar cada tarea que dejo a continuación en estos post:

Unidad I.

Unidad 2 Parte I

Unidad 2 Parte 2

Unidad 2 Parte 3

Luego hare un post en caso de obtener alguna insignia !

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus

                © 2016. All rights reserved.
                Uno theme by Dale-Anthony
                Proudly published with Hubpress


text:
package persistent.prestige.modules.eshop.model;

import java.io.Serializable;
import java.util.List;

public class OrderVo implements Serializable {

	private Integer orderId;

	private String orderNo;

	private String buyUid;

	private String sellerUid;

	private Long totalPrice;

	private Integer status;

	private String buyName;

	private String sellerName;

	private List<OrderItemVo> items;

	public Integer getOrderId() {
		return orderId;
	}

	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}

	public String getOrderNo() {
		return orderNo;
	}

	public void setOrderNo(String orderNo) {
		this.orderNo = orderNo;
	}

	public String getBuyUid() {
		return buyUid;
	}

	public void setBuyUid(String buyUid) {
		this.buyUid = buyUid;
	}

	public String getSellerUid() {
		return sellerUid;
	}

	public void setSellerUid(String sellerUid) {
		this.sellerUid = sellerUid;
	}

	public Long getTotalPrice() {
		return totalPrice;
	}

	public void setTotalPrice(Long totalPrice) {
		this.totalPrice = totalPrice;
	}

	public Integer getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}

	public String getBuyName() {
		return buyName;
	}

	public void setBuyName(String buyName) {
		this.buyName = buyName;
	}

	public String getSellerName() {
		return sellerName;
	}

	public void setSellerName(String sellerName) {
		this.sellerName = sellerName;
	}

	public List<OrderItemVo> getItems() {
		return items;
	}

	public void setItems(List<OrderItemVo> items) {
		this.items = items;
	}

}


text:
A small program to move around the filesystem.

Inspired by [teleport](https://github.com/bollu/teleport)

## Install

Install this by `cargo install` in the project directory. You'll need rust nightly installed to compile this. If you're on MacOS, then you can download the binaries from the releases page.

Once you've installed the binaries on your $PATH, you'll want to add the following function to your `bash_alias` or profile.

```bash
function j() {
  OUTPUT=`jump $@`
  if [ $? -eq 0 ]
    then cd "$OUTPUT"
    else echo "$OUTPUT"
  fi
}
```

You can then use the `jump-cfg` binary to set your workspace and jump markers, then the `j` function to go to those markers or directories in your workspace.


text:
package de.herm_detlef.java.application.di.guice;

import com.google.inject.AbstractModule;
import javafx.stage.Stage;

import java.lang.annotation.Annotation;

public class StageModule extends AbstractModule {
    private final Stage stage;
    private final Class< ? extends Annotation > annotation;

    public StageModule( Stage stage, Class< ? extends Annotation > annotation ) {
        this.stage = stage;
        this.annotation = annotation;
    }

    public StageModule( Class< ? extends Annotation > annotation ) {
        this.stage = new Stage();
        this.annotation = annotation;
    }

    @Override
    public void configure() {
        bind( Stage.class )
                .annotatedWith( annotation )
                .toProvider( () -> stage )
                .asEagerSingleton();
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>amp-truncate-text truncated link</title>
  <link rel="canonical" href="amps.html">
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

Inline text, with a link that is truncated

  <amp-truncate-text layout="container" class="text">
    Some text with a long link that should ellipsize and show a see more span afterwards.
     See more
  </amp-truncate-text>


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <link href="http://gmpg.org/xfn/11" rel="profile">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>

      Archive · Brian Leung

  </title>

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

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/B.png">
  <link rel="shortcut icon" href="/public/B.png">

  <link rel="alternate" type="application/atom+xml" title="Brian Leung" href="/atom.xml">

          Brian Leung

                About

                Archive

Archive

Blog Posts

20 Oct 2015 »  Increase test modularity by using SinonJS

25 Sep 2015 »  Increase Our Productivity with Task Runners

30 Aug 2015 »  Visualizing JavaScript Classical Inheritance

23 Aug 2015 »  Javascript Hoisting

          © <time datetime="2015-10-25T21:23:49-07:00">2015</time>. All rights reserved.


text:
package com.focusti.cervejaria.repository;

import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.focusti.cervejaria.model.Cidade;
import com.focusti.cervejaria.model.Estado;
import com.focusti.cervejaria.repository.helper.cidade.CidadesQueries;

@Repository
public interface Cidades extends JpaRepository<Cidade, Long>, CidadesQueries {

	public List<Cidade> findByEstadoCodigo(Long codigoEstado);

	public Optional<Cidade> findByNomeAndEstado(String nome, Estado estado);

}


text:
Capistrano::Configuration.instance.load do
  _cset(:eye_default_hooks) { true }
  _cset(:eye_config) { "config/eye.yml" }
  _cset(:eye_bin) { "bundle exec eye-patch" }
  _cset(:eye_roles) { :app }

  if fetch(:eye_default_hooks)
    after  "deploy:stop",    "eye:stop"
    after  "deploy:start",   "eye:load_config"
    before "deploy:restart", "eye:restart"
  end

  namespace :eye do
    desc "Start eye with the desired configuration file"
    task :load_config, roles: -> { fetch(:eye_roles) } do
      run "cd #{current_path} && #{fetch(:eye_bin)} quit"
      run "cd #{current_path} && #{fetch(:eye_bin)} load #{fetch(:eye_config)}"
    end

    desc "Stop eye and all of its monitored tasks"
    task :stop, roles: -> { fetch(:eye_roles) } do
      run "cd #{current_path} && #{fetch(:eye_bin)} stop all"
      run "cd #{current_path} && #{fetch(:eye_bin)} quit"
    end

    desc "Restart all tasks monitored by eye"
    task :restart, roles: -> { fetch(:eye_roles) } do
      run "cd #{current_path} && #{fetch(:eye_bin)} restart all"
    end
  end

  before "eye:restart", "eye:load_config"
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/ll_retry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@mipmap/loadpage_top" />

        <TextView
            android:id="@+id/retry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:text="获取数据失败"
            android:textColor="@color/black"
            android:textSize="16sp" />
    </LinearLayout>

</RelativeLayout>


text:
set -e

# CHECK TOOLS

# Checks for missing system compilers and tools

TOOLS=( ant autoconf make javac mpicc swig zsh )
declare -a MISSING

for T in ${TOOLS[@]}
do
  if ! which ${T} 2>&1 > /dev/null
  then
    MISSING+=( ${T} )
  fi
done

if (( ${#MISSING} ))
then
  echo "This system is missing the following required tools:"
  for T in ${MISSING[@]}
  do
    echo ${T}
  done
  exit 1
fi

exit