code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package com.weixin.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.util.Hash;
import com.weixin.vo.AccessToken;
import com.weixin.vo.NewsVo;
import com.weixin.vo.Oauth2Token;
import com.weixin.vo.UserInfo;
import com.weixin.vo.WxMediaVo;
import net.sf.json.JSONObject;
/**
* @author Jay
*/
@Component
public class WeixinUtil {
private static final Logger log = LoggerFactory.getLogger(WeixinUtil.class);
private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static final String GET_USERS_URL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";
private static final String GET_USER_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
private static final String GET_Oauth2AccessToken_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
private static final String GET_MATERIAL_URL = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN";
private static final String GET_JSPAI_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
private static final String MEDIA_UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
private static final String GET_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
private static final String MESSAGE_PREVIEW_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN";
/**
* 添加永久素材
*/
private static final String METERIAL_ADD_NEWS = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN";
/**
* 上传图片
*/
private static final String UPLOAD_IMG = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";
/**
* 上传永久素材
*/
private static final String MATERIAL_ADD_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN";
/**
* 获取素材总数
*/
private static final String GET_METERIALCOUNT_URL = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=ACCESS_TOKEN";
/**
* 获取素材列表
*/
private static final String GET_METERIALLIST_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
/**
* 群发
*/
private static final String SEND_ALL_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";
@Autowired
private RestTemplate restTemplate;
/**
* get请求
*
* @param url
* @return
*/
public static JSONObject doGetStr(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
public static String doGetStr2(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
String result = "";
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* post请求
*
* @param url
* @param outStr
* @return
*/
public static JSONObject doPostStr(String url, String outStr) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
try {
httpost.setEntity(new StringEntity(outStr, "UTF-8"));
HttpResponse response = httpClient.execute(httpost);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
jsonObject = JSONObject.fromObject(result);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* get access_token
*
* @return
*/
public static AccessToken getAccessToken() {
AccessToken token = new AccessToken();
String url = GET_ACCESS_TOKEN_URL.replace("APPID", TokenThread.APPID).replace("APPSECRET",
TokenThread.APPSECRET);
JSONObject jsonObject = doGetStr(url);
System.out.println(jsonObject.toString());
if (jsonObject != null) {
try {
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (Exception e) {
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
System.out.println(errorCode + " | " + errorMsg);
}
}
return token;
}
public static AccessToken getAccessToken(String appId, String appSecret) {
AccessToken token = new AccessToken();
String url = GET_ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", appSecret);
JSONObject jsonObject = doGetStr(url);
System.out.println(jsonObject.toString());
if (jsonObject != null) {
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
}
return token;
}
/*
* Get user list
*/
public static List<UserInfo> getUsers(String token) throws ParseException, IOException {
String url = GET_USERS_URL.replace("ACCESS_TOKEN", token);
JSONObject jsonObject = doGetStr(url);
Object obj = jsonObject.get("data");
Map<String, List<String>> map = (Map<String, List<String>>) obj;
List<String> list = map.get("openid");
List<UserInfo> userList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
UserInfo userInfo = WeixinUtil.getUser(token, list.get(i));
userList.add(userInfo);
}
return userList;
}
/*
* Get user info
*/
public static UserInfo getUser(String token, String openId) throws ParseException, IOException {
String url = GET_USER_URL.replace("ACCESS_TOKEN", token).replace("OPENID", openId);
JSONObject jsonObject = doGetStr(url);
System.out.println("hack");
System.out.println(jsonObject.toString());
UserInfo userInfo = new UserInfo();
if (null != jsonObject) {
try {
userInfo = new UserInfo();
// openId
userInfo.setOpenId(jsonObject.getString("openid"));
// 昵称
userInfo.setNickname(jsonObject.getString("nickname"));
// 性别
userInfo.setSex(jsonObject.getInt("sex"));
// 国家
userInfo.setCountry(jsonObject.getString("country"));
// 省
userInfo.setProvince(jsonObject.getString("province"));
// 城市
userInfo.setCity(jsonObject.getString("city"));
// 图片url
userInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
// privilege
// userInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"),
// List.class));
} catch (Exception e) {
userInfo = null;
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
System.out.println(errorCode + " | " + errorMsg);
}
}
return userInfo;
}
/**
* Get OAuth Access Token
*/
public static Oauth2Token getOauth2AccessToken(String appid, String appsecret, String code) {
String url = GET_Oauth2AccessToken_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE",
code);
JSONObject jsonObject = doGetStr(url);
Oauth2Token oauth2Token = new Oauth2Token();
if (jsonObject != null) {
try {
oauth2Token.setAccessToken(jsonObject.getString("access_token"));
oauth2Token.setExpiresIn(jsonObject.getInt("expires_in"));
oauth2Token.setRefreshToken(jsonObject.getString("refresh_token"));
oauth2Token.setOpenId(jsonObject.getString("openid"));
oauth2Token.setScope(jsonObject.getString("scope"));
} catch (Exception e) {
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
System.out.println(errorCode + " :" + errorMsg);
}
}
return oauth2Token;
}
/**
* get OAuth access token
*/
public static Oauth2Token getOauth2AccessToken(String code) {
return getOauth2AccessToken(TokenThread.APPID, TokenThread.APPSECRET, code);
}
/**
* Get material
*/
public void getMaterial(String token,String mediaId) {
String url = GET_MATERIAL_URL.replace("ACCESS_TOKEN", token);
// JSONObject jsonObject = doPostStr(url,
// "{'media_id': 'X-fJF8E32mDZQnq6XgyDBTI7iriawzkKNQv2QzrzrYg");
Map<String, Object> params = new HashMap<>();
params.put("media_id", mediaId);
String result = restTemplate.postForObject(url, params, String.class);
log.info(result.toString());
// System.out.println(jsonObject.toString());
}
/**
* Get JSPAI Token
*/
public static String getJsapiToken(String token) {
String url = GET_JSPAI_URL.replace("ACCESS_TOKEN", token);
JSONObject jsonObject = doGetStr(url);
System.out.println(jsonObject.toString());
return jsonObject.getString("ticket");
}
/**
* media upload
*
* @param token
* @param file
* @param type
* @return
*/
public WxMediaVo mediaUpload(String token, File file, String type) {
String url = MEDIA_UPLOAD_URL.replace("ACCESS_TOKEN", token).replace("TYPE", type);
// JSONObject jsonObject = doPostStr(url, "{'media': file}");
// System.out.println(jsonObject.toString());
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("jarFile", resource);
// WxMediaVo vo = restTemplate.postForObject(url, param,
// WxMediaVo.class);
String str = restTemplate.postForObject(url, param, String.class);
WxMediaVo vo = null;
try {
vo = new ObjectMapper().readValue(str, WxMediaVo.class);
} catch (Exception e) {
e.printStackTrace();
}
log.info(vo.toString());
return vo;
}
/**
* get media
* @param token
* @param mediaId
*/
public void getMedia(String token,String mediaId){
String url = GET_MEDIA_URL.replace("ACCESS_TOKEN", token).replace("MEDIA_ID", mediaId);
HttpHeaders result = restTemplate.headForHeaders(url);
log.info(result.toString());
}
/**
* 添加图文
* @param token
* @param newsVo
*/
public void meterialAddNews(String token,NewsVo newsVo){
String url = METERIAL_ADD_NEWS.replace("ACCESS_TOKEN", token);
String result = restTemplate.postForObject(url, newsVo, String.class);
log.info(result.toString());
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
// X-fJF8E32mDZQnq6XgyDBTI7iriawzkKNQv2QzrzrYg
// 这里的media_id 保存到本地数据库
}
/**
* 获取素材总数
* @param token
* @param newsVo
*/
public void getMeteialCount(String token){
String url = GET_METERIALCOUNT_URL.replace("ACCESS_TOKEN", token);
String result = restTemplate.getForObject(url, String.class);
log.info(result.toString());
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* 获取素材总数
* @param token
* @param newsVo
*/
public String getMeteialList(String token){
String url = GET_METERIALLIST_URL.replace("ACCESS_TOKEN", token);
Map<String, Object> param = new HashMap<>();
param.put("type", "image");
param.put("offset", 0);
param.put("count", 10);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result.toString());
return result;
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* 群发
* user not agree mass-send protocol 没有权限
* @param token
*/
public void sendALL(String token){
String url = SEND_ALL_URL.replace("ACCESS_TOKEN", token);
Map<String, Object> param = new HashMap<>();
Map<String, Object> mpnews = new HashMap<>();
mpnews.put("media_id", "X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"); //test
param.put("mpnews", mpnews);
param.put("msgtype", "mpnews");
Map<String, Object> filter = new HashMap<>();
filter.put("is_to_all", true);
param.put("filter", filter);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result.toString());
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* 预览
* user not agree mass-send protocol 没有权限
* @param token
*/
public String messagePreview(String token,String touser){
String url = MESSAGE_PREVIEW_URL.replace("ACCESS_TOKEN", token);
Map<String, Object> param = new HashMap<>();
Map<String, Object> mpnews = new HashMap<>();
mpnews.put("media_id", "X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"); //test
param.put("mpnews", mpnews);
param.put("msgtype", "mpnews");
param.put("touser", touser);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result.toString());
return result;
// {"media_id":"X-fJF8E32mDZQnq6XgyDBaBEx3KMckF_oePNQfBjt4I"}
/**
* {"voice_count":0,"video_count":0,"image_count":2,"news_count":1}
*/
// 这里的media_id 保存到本地数据库
}
/**
* Upload image
* @param token
* @param file
*/
public void uploadImg(String token,File file){
String url = UPLOAD_IMG.replace("ACCESS_TOKEN", token);
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("jarFile", resource);
String imgUrl = restTemplate.postForObject(url, param, String.class);
log.info(imgUrl);
// http://mmbiz.qpic.cn/mmbiz/NlnaapibtH6EVOVBmPlf1TQI6Mwt6DLO79rhQNHZYE4Q12NN88coMAWcMAibeRaeMqRnQDAR90ibJk4sNqNm2EWkQ/0
// 保存到本地数据库
}
/**
* access_token 是 调用接口凭证
* type 是 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
* media 是 form-data中媒体文件标识,有filename、filelength、content-type等信息
*{"media_id":"X-fJF8E32mDZQnq6XgyDBRGqKvuTPm9YJqFPk7dqcUY","url":"https:\/\/mmbiz.qlogo.cn\/mmbiz\/NlnaapibtH6EVOVBmPlf1TQI6Mwt6DLO79rhQNHZYE4Q12NN88coMAWcMAibeRaeMqRnQDAR90ibJk4sNqNm2EWkQ\/0?wx_fmt=jpeg"}
* @param token
* @param file
* @param type
*/
public void materialAdd(String token,File file,String type){
String url = MATERIAL_ADD_URL.replace("ACCESS_TOKEN", token);
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("media", resource);
param.add("type", type);
String result = restTemplate.postForObject(url, param, String.class);
log.info(result);
JSONObject obj = JSONObject.fromObject(result);
String mediaId = obj.getString("media_id");
log.info(mediaId);
if(type.equals("image")){
String imgUrl = obj.getString("url");
log.info(imgUrl);
}
// 本地是否需要保存
}
}
| ScorpionJay/wechat | src/main/java/com/weixin/util/WeixinUtil.java | Java | mit | 17,181 |
'use strict';
const Perceptron = require('./perceptron');
const PerceptronTrainer = require('./perceptron.trainer');
const trainer = new PerceptronTrainer();
trainer.setLearningRate(2.0);
// and-perceptron: weights: [1,4], bias: -5
const perceptron = new Perceptron();
perceptron.setWeights([-20,-30]);
perceptron.setBias(1);
trainer.train(perceptron, [
{ inputs: [0 ,0], ideal: 0 },
{ inputs: [1 ,0], ideal: 0 },
{ inputs: [0 ,1], ideal: 0 },
{ inputs: [1 ,1], ideal: 1 },
]);
console.log({
perceptron: perceptron.getConnections(),
inputs: [1, 0],
output: perceptron.output()
});
// or-perceptron: weights: [1,2], bias: -1
perceptron.setWeights([-20,-30]);
perceptron.setBias(1);
trainer.train(perceptron, [
{ inputs: [0 ,0], ideal: 0 },
{ inputs: [1 ,0], ideal: 1 },
{ inputs: [0 ,1], ideal: 1 },
{ inputs: [1 ,1], ideal: 1 },
]);
console.log({
perceptron: perceptron.getConnections(),
inputs: [1, 0],
output: perceptron.output()
}); | pascalvree/example-perceptron-implementation | src/example.js | JavaScript | mit | 998 |
require 'rails_helper'
RSpec.describe ComponentsController, type: :controller do
describe "GET a_z" do
before(:each) do
get :a_z
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/a-z")
end
end
describe "GET alert" do
before(:each) do
get :alert
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/alert")
end
end
describe "GET badges" do
before(:each) do
get :badges
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/badges")
end
end
describe "GET banners" do
before(:each) do
get :banners
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/banners")
end
end
describe "GET breadcrumb" do
before(:each) do
get :breadcrumb
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/breadcrumb")
end
end
describe "GET footer" do
before(:each) do
get :footer
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/footer")
end
end
describe "GET header" do
before(:each) do
get :header
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/header")
end
end
describe "GET pagination" do
before(:each) do
get :pagination
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "rendered using the correct template" do
expect(response).to render_template("styleguide/components/pagination")
end
end
end
| naseberry/styleguide | spec/controllers/components_controller_spec.rb | Ruby | mit | 2,542 |
import { getElementIfNotEmpty } from './getElementIfNotEmpty.js';
export function getStackDataIfNotEmpty(viewportIndex) {
const element = getElementIfNotEmpty(viewportIndex);
if (!element) {
return;
}
const stackToolData = cornerstoneTools.getToolState(element, 'stack');
if (!stackToolData ||
!stackToolData.data ||
!stackToolData.data.length) {
return;
}
const stack = stackToolData.data[0];
if (!stack) {
return;
}
return stack;
}
| NucleusIo/HealthGenesis | viewerApp/Packages/ohif-viewerbase/client/lib/getStackDataIfNotEmpty.js | JavaScript | mit | 518 |
class AddTeamIdToUsersAndBuckets < ActiveRecord::Migration
def change
add_column :users, :team_id, :integer
add_column :buckets, :team_id, :integer
end
end
| jonmagic/i-got-issues | db/migrate/20140608063204_add_team_id_to_users_and_buckets.rb | Ruby | mit | 170 |
<?php
/**
* A simple component which returns a list of controllers plus the corresponding action names.
*
* See also: http://cakebaker.42dh.com/2006/07/21/how-to-list-all-controllers
*
* This code is in the public domain, use it in any way you like ;-)
*/
class ControllerListComponent extends Object {
public function get() {
$controllerClasses = App::objects('controller');
foreach($controllerClasses as $controller) {
if ($controller != 'App') {
App::import('Controller', $controller);
$className = $controller . 'Controller';
$actions = get_class_methods($className);
foreach($actions as $k => $v) {
if ($v{0} == '_') {
unset($actions[$k]);
}
}
$parentActions = get_class_methods('AppController');
$controllers[$controller] = array_diff($actions, $parentActions);
}
}
return $controllers;
}
}
| ambagasdowa/kml | app/controllers/components/controller_list.php | PHP | mit | 1,033 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Wpf.Controls.Demo
{
public class DelegateCommand : ICommand
{
private Action<object> _executeMethod;
private Func<object, bool> _canExecuteMethod;
public DelegateCommand(Action<object> executeMethod, Func<object, bool> canExecuteMethod)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
if (_canExecuteMethod == null)
return true;
return _canExecuteMethod(parameter);
}
public void Execute(object parameter)
{
if (_executeMethod != null)
_executeMethod(parameter);
}
public void RaiseCanExecute()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, null);
}
}
}
| fengdingfeilong/FssControls | Wpf.Controls.Demo/DelegateCommand.cs | C# | mit | 1,265 |
// Markup.cpp: implementation of the CMarkup class.
//
// Markup Release 11.2
// Copyright (C) 2009 First Objective Software, Inc. All rights reserved
// Go to www.firstobject.com for the latest CMarkup and EDOM documentation
// Use in commercial applications requires written permission
// This software is provided "as is", with no warranty.
//
#include <stdio.h>
#include "Markup.h"
#if defined(MCD_STRERROR) // C error routine
#include <errno.h>
#endif // C error routine
#if defined (MARKUP_ICONV)
#include <iconv.h>
#endif
#if defined(MARKUP_STL) && ( defined(MARKUP_WINCONV) || (! defined(MCD_STRERROR)))
#include <windows.h> // for MultiByteToWideChar, WideCharToMultiByte, FormatMessage
#endif // need windows.h when STL and (not setlocale or not strerror), MFC afx.h includes it already
#if defined(MARKUP_MBCS) // MBCS/double byte
#pragma message( "Note: MBCS build (not UTF-8)" )
// For UTF-8, remove MBCS from project settings C/C++ preprocessor definitions
#if defined (MARKUP_WINCONV)
#include <mbstring.h> // for VC++ _mbclen
#endif // WINCONV
#endif // MBCS/double byte
#if defined(_DEBUG) && _MSC_VER > 1000 // VC++ DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#if defined(DEBUG_NEW)
#define new DEBUG_NEW
#endif // DEBUG_NEW
#endif // VC++ DEBUG
// Customization
#define x_EOL MCD_T("\r\n") // can be \r\n or \n or empty
#define x_EOLLEN (sizeof(x_EOL)/sizeof(MCD_CHAR)-1) // string length of x_EOL
#define x_ATTRIBQUOTE '\"' // can be double or single quote
// Disable "while ( 1 )" warning in VC++ 2002
#if _MSC_VER >= 1300 // VC++ 2002 (7.0)
#pragma warning(disable:4127)
#endif // VC++ 2002 (7.0)
//////////////////////////////////////////////////////////////////////
// Internal static utility functions
//
void x_StrInsertReplace( MCD_STR& str, int nLeft, int nReplace, const MCD_STR& strInsert )
{
// Insert strInsert into str at nLeft replacing nReplace chars
// Reduce reallocs on growing string by reserving string space
// If realloc needed, allow for 1.5 times the new length
//
int nStrLength = MCD_STRLENGTH(str);
int nInsLength = MCD_STRLENGTH(strInsert);
int nNewLength = nInsLength + nStrLength - nReplace;
int nAllocLen = MCD_STRCAPACITY(str);
#if defined(MCD_STRINSERTREPLACE) // STL, replace method
if ( nNewLength > nAllocLen )
MCD_BLDRESERVE( str, (nNewLength + nNewLength/2 + 128) );
MCD_STRINSERTREPLACE( str, nLeft, nReplace, strInsert );
#else // MFC, no replace method
int nBufferLen = nNewLength;
if ( nNewLength > nAllocLen )
nBufferLen += nBufferLen/2 + 128;
MCD_CHAR* pDoc = MCD_GETBUFFER( str, nBufferLen );
if ( nInsLength != nReplace && nLeft+nReplace < nStrLength )
memmove( &pDoc[nLeft+nInsLength], &pDoc[nLeft+nReplace], (nStrLength-nLeft-nReplace)*sizeof(MCD_CHAR) );
if ( nInsLength )
memcpy( &pDoc[nLeft], strInsert, nInsLength*sizeof(MCD_CHAR) );
MCD_RELEASEBUFFER( str, pDoc, nNewLength );
#endif // MFC, no replace method
}
int x_Hash( MCD_PCSZ p, int nSize )
{
unsigned int n=0;
while (*p)
n += (unsigned int)(*p++);
return n % nSize;
}
MCD_STR x_IntToStr( int n )
{
MCD_CHAR sz[25];
MCD_SPRINTF(MCD_SSZ(sz),MCD_T("%d"),n);
MCD_STR s=sz;
return s;
}
enum MarkupResultCode
{
MRC_COUNT = 1,
MRC_TYPE = 2,
MRC_NUMBER = 4,
MRC_ENCODING = 8,
MRC_LENGTH = 16,
MRC_MODIFY = 32,
MRC_MSG = 64
};
void x_AddResult( MCD_STR& strResult, MCD_CSTR pszID, MCD_CSTR pszVal = NULL, int nResultCode = 0, int n = -1, int n2 = -1 )
{
// Call this to append an error result to strResult, discard if accumulating too large
if ( MCD_STRLENGTH(strResult) < 1000 )
{
// Use a temporary CMarkup object but keep strResult in a string to minimize memory footprint
CMarkup mResult( strResult );
if ( nResultCode & MRC_MODIFY )
mResult.FindElem( pszID );
else
mResult.AddElem( pszID, MCD_T(""), CMarkup::MNF_WITHNOLINES );
if ( pszVal.pcsz )
{
if ( nResultCode & MRC_TYPE )
mResult.SetAttrib( MCD_T("type"), pszVal );
else if ( nResultCode & MRC_ENCODING )
mResult.SetAttrib( MCD_T("encoding"), pszVal );
else if ( nResultCode & MRC_MSG )
mResult.SetAttrib( MCD_T("msg"), pszVal );
else
mResult.SetAttrib( MCD_T("tagname"), pszVal );
}
if ( nResultCode & MRC_NUMBER )
mResult.SetAttrib( MCD_T("n"), n );
else if ( nResultCode & MRC_COUNT )
mResult.SetAttrib( MCD_T("count"), n );
else if ( nResultCode & MRC_LENGTH )
mResult.SetAttrib( MCD_T("length"), n );
else if ( n != -1 )
mResult.SetAttrib( MCD_T("offset"), n );
if ( n2 != -1 )
mResult.SetAttrib( MCD_T("offset2"), n2 );
strResult = mResult.GetDoc();
}
}
//////////////////////////////////////////////////////////////////////
// Encoding conversion struct and methods
//
struct TextEncoding
{
TextEncoding( MCD_CSTR pszFromEncoding, const void* pFromBuffer, int nFromBufferLen )
{
m_strFromEncoding = pszFromEncoding;
m_pFrom = pFromBuffer;
m_nFromLen = nFromBufferLen;
m_nFailedChars = 0;
m_nToCount = 0;
};
int PerformConversion( void* pTo, MCD_CSTR pszToEncoding = NULL );
bool FindRaggedEnd( int& nTruncBeforeBytes );
#if defined(MARKUP_ICONV)
static const char* IConvName( char* szEncoding, MCD_CSTR pszEncoding );
int IConv( void* pTo, int nToCharSize, int nFromCharSize );
#endif // ICONV
#if ! defined(MARKUP_WCHAR)
static bool CanConvert( MCD_CSTR pszToEncoding, MCD_CSTR pszFromEncoding );
#endif // WCHAR
MCD_STR m_strToEncoding;
MCD_STR m_strFromEncoding;
const void* m_pFrom;
int m_nFromLen;
int m_nToCount;
int m_nFailedChars;
};
// Encoding names
// This is a precompiled ASCII hash table for speed and minimum memory requirement
// Each entry consists of a 2 digit name length, 5 digit code page, and the encoding name
// Each table slot can have multiple entries, table size 155 was chosen for even distribution
//
MCD_PCSZ EncodingNameTable[155] =
{
MCD_T("0800949ksc_5601"),MCD_T("1920932cseucpkdfmtjapanese0920003x-cp20003"),
MCD_T("1250221_iso-2022-jp0228591l10920004x-cp20004"),
MCD_T("0228592l20920005x-cp20005"),
MCD_T("0228593l30600850ibm8501000858ccsid00858"),
MCD_T("0228594l40600437ibm4370701201ucs-2be0600860ibm860"),
MCD_T("0600852ibm8520501250ms-ee0600861ibm8610228599l50751932cp51932"),
MCD_T("0600862ibm8620620127ibm3670700858cp008581010021x-mac-thai0920261x-cp20261"),
MCD_T("0600737ibm7370500869cp-gr1057003x-iscii-be0600863ibm863"),
MCD_T("0750221ms502210628591ibm8190600855ibm8550600864ibm864"),
MCD_T("0600775ibm7751057002x-iscii-de0300949uhc0228605l91028591iso-ir-1000600865ibm865"),
MCD_T("1028594iso-ir-1101028592iso-ir-1010600866ibm8660500861cp-is0600857ibm857"),
MCD_T("0950227x-cp50227"),
MCD_T("0320866koi1628598csisolatinhebrew1057008x-iscii-ka"),
MCD_T("1000950big5-hkscs1220106x-ia5-german0600869ibm869"),
MCD_T("1057009x-iscii-ma0701200ucs-2le0712001utf32be0920269x-cp20269"),
MCD_T("0800708asmo-7080500437cspc81765000unicode-1-1-utf-70612000utf-320920936x-cp20936"),
MCD_T("1200775ebcdic-cp-be0628598hebrew0701201utf16be1765001unicode-1-1-utf-81765001unicode-2-0-utf-80551932x-euc"),
MCD_T("1028595iso-ir-1441028597iso-ir-1260728605latin-90601200utf-161057011x-iscii-pa"),
MCD_T("1028596iso-ir-1271028593iso-ir-1090751932ms51932"),
MCD_T("0801253ms-greek0600949korean1050225iso2022-kr1128605iso_8859-150920949x-cp20949"),
MCD_T("1200775ebcdic-cp-ch1028598iso-ir-1381057006x-iscii-as1450221iso-2022-jp-ms"),
MCD_T("1057004x-iscii-ta1028599iso-ir-148"),
MCD_T("1000949iso-ir-1490820127us-ascii"),MCD_T(""),
MCD_T("1000936gb_2312-801900850cspc850multilingual0712000utf32le"),
MCD_T("1057005x-iscii-te1300949csksc560119871965000x-unicode-2-0-utf-7"),
MCD_T("0701200utf16le1965001x-unicode-2-0-utf-80928591iso8859-1"),
MCD_T("0928592iso8859-21420002x_chinese-eten0520866koi8r1000932x-ms-cp932"),
MCD_T("1320000x-chinese-cns1138598iso8859-8-i1057010x-iscii-gu0928593iso8859-3"),
MCD_T("0928594iso8859-4"),MCD_T("0928595iso8859-51150221csiso2022jp"),
MCD_T("0928596iso8859-60900154csptcp154"),
MCD_T("0928597iso8859-70900932shift_jis1400154cyrillic-asian"),
MCD_T("0928598iso8859-81057007x-iscii-or1150225csiso2022kr"),
MCD_T("0721866koi8-ru0928599iso8859-9"),MCD_T("0910000macintosh"),MCD_T(""),
MCD_T(""),MCD_T(""),
MCD_T("1210004x-mac-arabic0800936gb2312800628598visual1520108x-ia5-norwegian"),
MCD_T(""),MCD_T("0829001x-europa"),MCD_T(""),MCD_T("1510079x-mac-icelandic"),
MCD_T("0800932sjis-win1128591csisolatin1"),MCD_T("1128592csisolatin2"),
MCD_T("1400949ks_c_5601-19871128593csisolatin3"),MCD_T("1128594csisolatin4"),
MCD_T("0400950big51128595csisolatin51400949ks_c_5601-1989"),
MCD_T("0500775cp5001565000csunicode11utf7"),MCD_T("0501361johab"),
MCD_T("1100932windows-9321100437codepage437"),
MCD_T("1800862cspc862latinhebrew1310081x-mac-turkish"),MCD_T(""),
MCD_T("0701256ms-arab0800775csibm5000500154cp154"),
MCD_T("1100936windows-9360520127ascii"),
MCD_T("1528597csisolatingreek1100874windows-874"),MCD_T("0500850cp850"),
MCD_T("0700720dos-7200500950cp9500500932cp9320500437cp4370500860cp8601650222_iso-2022-jp$sio"),
MCD_T("0500852cp8520500861cp8610700949ksc56010812001utf-32be"),
MCD_T("0528597greek0500862cp8620520127cp3670500853cp853"),
MCD_T("0500737cp7371150220iso-2022-jp0801201utf-16be0500863cp863"),
MCD_T("0500936cp9360528591cp8194520932extended_unix_code_packed_format_for_japanese0500855cp8550500864cp864"),
MCD_T("0500775cp7750500874cp8740800860csibm8600500865cp865"),
MCD_T("0500866cp8660800861csibm8611150225iso-2022-kr0500857cp8571101201unicodefffe"),
MCD_T("0700862dos-8620701255ms-hebr0500858cp858"),
MCD_T("1210005x-mac-hebrew0500949cp9490800863csibm863"),
MCD_T("0500869cp8691600437cspc8codepage4370700874tis-6200800855csibm8550800864csibm864"),
MCD_T("0800950x-x-big50420866koi80800932ms_kanji0700874dos-8740800865csibm865"),
MCD_T("0800866csibm8661210003x-mac-korean0800857csibm8570812000utf-32le"),
MCD_T(""),MCD_T("0500932ms9320801200utf-16le1028591iso-8859-10500154pt154"),
MCD_T("1028592iso-8859-20620866koi8-r0800869csibm869"),
MCD_T("1500936csiso58gb2312800828597elot_9281238598iso-8859-8-i1028593iso-8859-30820127iso-ir-6"),
MCD_T("1028594iso-8859-4"),
MCD_T("0800852cspcp8520500936ms9361028595iso-8859-50621866koi8-u0701252ms-ansi"),
MCD_T("1028596iso-8859-60220127us2400858pc-multilingual-850+euro"),
MCD_T("1028597iso-8859-71028603iso8859-13"),
MCD_T("1320000x-chinese_cns1028598iso-8859-8"),
MCD_T("1828595csisolatincyrillic1028605iso8859-151028599iso-8859-9"),
MCD_T("0465001utf8"),MCD_T("1510017x-mac-ukrainian"),MCD_T(""),
MCD_T("0828595cyrillic"),MCD_T("0900936gb2312-80"),MCD_T(""),
MCD_T("0720866cskoi8r1528591iso_8859-1:1987"),MCD_T("1528592iso_8859-2:1987"),
MCD_T("1354936iso-4873:1986"),MCD_T("0700932sjis-ms1528593iso_8859-3:1988"),
MCD_T("1528594iso_8859-4:19880600936gb23120701251ms-cyrl"),
MCD_T("1528596iso_8859-6:19871528595iso_8859-5:1988"),
MCD_T("1528597iso_8859-7:1987"),
MCD_T("1201250windows-12501300932shifft_jis-ms"),
MCD_T("0810029x-mac-ce1201251windows-12511528598iso_8859-8:19880900949ks_c_56011110000csmacintosh"),
MCD_T("0601200cp12001201252windows-1252"),
MCD_T("1052936hz-gb-23121201253windows-12531400949ks_c_5601_19871528599iso_8859-9:19890601201cp1201"),
MCD_T("1201254windows-1254"),MCD_T("1000936csgb2312801201255windows-1255"),
MCD_T("1201256windows-12561100932windows-31j"),
MCD_T("1201257windows-12570601250cp12500601133cp1133"),
MCD_T("0601251cp12511201258windows-12580601125cp1125"),
MCD_T("0701254ms-turk0601252cp1252"),MCD_T("0601253cp12530601361cp1361"),
MCD_T("0800949ks-c56010601254cp1254"),MCD_T("0651936euc-cn0601255cp1255"),
MCD_T("0601256cp1256"),MCD_T("0601257cp12570600950csbig50800858ibm00858"),
MCD_T("0601258cp1258"),MCD_T("0520105x-ia5"),
MCD_T("0801250x-cp12501110006x-mac-greek0738598logical"),
MCD_T("0801251x-cp1251"),MCD_T(""),
MCD_T("1410001x-mac-japanese1200932cswindows31j"),
MCD_T("0700936chinese0720127csascii0620932euc-jp"),
MCD_T("0851936x-euc-cn0501200ucs-2"),MCD_T("0628597greek8"),
MCD_T("0651949euc-kr"),MCD_T(""),MCD_T("0628591latin1"),
MCD_T("0628592latin21100874iso-8859-11"),
MCD_T("0628593latin31420127ansi_x3.4-19681420127ansi_x3.4-19861028591iso_8859-1"),
MCD_T("0628594latin41028592iso_8859-20701200unicode1128603iso-8859-13"),
MCD_T("1028593iso_8859-30628599latin51410082x-mac-croatian"),
MCD_T("1028594iso_8859-41128605iso-8859-150565000utf-70851932x-euc-jp"),
MCD_T("1300775cspc775baltic1028595iso_8859-50565001utf-80512000utf32"),
MCD_T("1028596iso_8859-61710002x-mac-chinesetrad0601252x-ansi"),
MCD_T("1028597iso_8859-70628605latin90501200utf160700154ptcp1541410010x-mac-romanian"),
MCD_T("0900936iso-ir-581028598iso_8859-8"),MCD_T("1028599iso_8859-9"),
MCD_T("1350221iso2022-jp-ms0400932sjis"),MCD_T("0751949cseuckr"),
MCD_T("1420002x-chinese-eten"),MCD_T("1410007x-mac-cyrillic"),
MCD_T("1000932shifft_jis"),MCD_T("0828596ecma-114"),MCD_T(""),
MCD_T("0900932shift-jis"),MCD_T("0701256cp1256 1320107x-ia5-swedish"),
MCD_T("0828597ecma-118"),
MCD_T("1628596csisolatinarabic1710008x-mac-chinesesimp0600932x-sjis"),MCD_T(""),
MCD_T("0754936gb18030"),MCD_T("1350221windows-502210712000cp12000"),
MCD_T("0628596arabic0500936cn-gb0900932sjis-open0712001cp12001"),MCD_T(""),
MCD_T(""),MCD_T("0700950cn-big50920127iso646-us1001133ibm-cp1133"),MCD_T(""),
MCD_T("0800936csgb23120900949ks-c-56010310000mac"),
MCD_T("1001257winbaltrim0750221cp502211020127iso-ir-6us"),
MCD_T("1000932csshiftjis"),MCD_T("0300936gbk0765001cp65001"),
MCD_T("1620127iso_646.irv:19911351932windows-519320920001x-cp20001")
};
int x_GetEncodingCodePage( MCD_CSTR pszEncoding )
{
// redo for completeness, the iconv set, UTF-32, and uppercase
// Lookup strEncoding in EncodingNameTable and return Windows code page
int nCodePage = -1;
int nEncLen = MCD_PSZLEN( pszEncoding );
if ( ! nEncLen )
nCodePage = MCD_ACP;
else if ( MCD_PSZNCMP(pszEncoding,MCD_T("UTF-32"),6) == 0 )
nCodePage = MCD_UTF32;
else if ( nEncLen < 100 )
{
MCD_CHAR szEncodingLower[100];
for ( int nEncChar=0; nEncChar<nEncLen; ++nEncChar )
{
MCD_CHAR cEncChar = pszEncoding[nEncChar];
szEncodingLower[nEncChar] = (cEncChar>='A' && cEncChar<='Z')? (MCD_CHAR)(cEncChar+('a'-'A')) : cEncChar;
}
szEncodingLower[nEncLen] = '\0';
MCD_PCSZ pEntry = EncodingNameTable[x_Hash(szEncodingLower,sizeof(EncodingNameTable)/sizeof(MCD_PCSZ))];
while ( *pEntry )
{
// e.g. entry: 0565001utf-8 means length 05, code page 65001, encoding name utf-8
int nEntryLen = (*pEntry - '0') * 10;
++pEntry;
nEntryLen += (*pEntry - '0');
++pEntry;
MCD_PCSZ pCodePage = pEntry;
pEntry += 5;
if ( nEntryLen == nEncLen && MCD_PSZNCMP(szEncodingLower,pEntry,nEntryLen) == 0 )
{
// Convert digits to integer up to code name which always starts with alpha
nCodePage = MCD_PSZTOL( pCodePage, NULL, 10 );
break;
}
pEntry += nEntryLen;
}
}
return nCodePage;
}
#if ! defined(MARKUP_WCHAR)
bool TextEncoding::CanConvert( MCD_CSTR pszToEncoding, MCD_CSTR pszFromEncoding )
{
// Return true if MB to MB conversion is possible
#if defined(MARKUP_ICONV)
// iconv_open should fail if either encoding not supported or one is alias for other
char szTo[100], szFrom[100];
iconv_t cd = iconv_open( IConvName(szTo,pszToEncoding), IConvName(szFrom,pszFromEncoding) );
if ( cd == (iconv_t)-1 )
return false;
iconv_close(cd);
#else
int nToCP = x_GetEncodingCodePage( pszToEncoding );
int nFromCP = x_GetEncodingCodePage( pszFromEncoding );
if ( nToCP == -1 || nFromCP == -1 )
return false;
#if defined(MARKUP_WINCONV)
if ( nToCP == MCD_ACP || nFromCP == MCD_ACP ) // either ACP ANSI?
{
int nACP = GetACP();
if ( nToCP == MCD_ACP )
nToCP = nACP;
if ( nFromCP == MCD_ACP )
nFromCP = nACP;
}
#else // no conversion API, but we can do AToUTF8 and UTF8ToA
if ( nToCP != MCD_UTF8 && nFromCP != MCD_UTF8 ) // either UTF-8?
return false;
#endif // no conversion API
if ( nToCP == nFromCP )
return false;
#endif // not ICONV
return true;
}
#endif // not WCHAR
#if defined(MARKUP_ICONV)
const char* TextEncoding::IConvName( char* szEncoding, MCD_CSTR pszEncoding )
{
// Make upper case char-based name from strEncoding which consists only of characters in the ASCII range
int nEncChar = 0;
while ( pszEncoding[nEncChar] )
{
char cEncChar = (char)pszEncoding[nEncChar];
szEncoding[nEncChar] = (cEncChar>='a' && cEncChar<='z')? (cEncChar-('a'-'A')) : cEncChar;
++nEncChar;
}
if ( nEncChar == 6 && strncmp(szEncoding,"UTF-16",6) == 0 )
{
szEncoding[nEncChar++] = 'B';
szEncoding[nEncChar++] = 'E';
}
szEncoding[nEncChar] = '\0';
return szEncoding;
}
int TextEncoding::IConv( void* pTo, int nToCharSize, int nFromCharSize )
{
// Converts from m_pFrom to pTo
char szTo[100], szFrom[100];
iconv_t cd = iconv_open( IConvName(szTo,m_strToEncoding), IConvName(szFrom,m_strFromEncoding) );
int nToLenBytes = 0;
if ( cd != (iconv_t)-1 )
{
size_t nFromLenRemaining = (size_t)m_nFromLen * nFromCharSize;
size_t nToCountRemaining = (size_t)m_nToCount * nToCharSize;
size_t nToCountRemainingBefore;
char* pToChar = (char*)pTo;
char* pFromChar = (char*)m_pFrom;
char* pToTempBuffer = NULL;
const size_t nTempBufferSize = 2048;
size_t nResult;
if ( ! pTo )
{
pToTempBuffer = new char[nTempBufferSize];
pToChar = pToTempBuffer;
nToCountRemaining = nTempBufferSize;
}
while ( nFromLenRemaining )
{
nToCountRemainingBefore = nToCountRemaining;
nResult = iconv( cd, &pFromChar, &nFromLenRemaining, &pToChar, &nToCountRemaining );
nToLenBytes += (int)(nToCountRemainingBefore - nToCountRemaining);
if ( nResult == (size_t)-1 )
{
int nErrno = errno;
if ( nErrno == EILSEQ )
{
// Bypass bad char, question mark denotes problem in source string
pFromChar += nFromCharSize;
nFromLenRemaining -= nFromCharSize;
if ( nToCharSize == 1 )
*pToChar = '?';
else if ( nToCharSize == 2 )
*((unsigned short*)pToChar) = (unsigned short)'?';
else if ( nToCharSize == 4 )
*((unsigned int*)pToChar) = (unsigned int)'?';
pToChar += nToCharSize;
nToCountRemaining -= nToCharSize;
}
else if ( nErrno == EINVAL )
break; // incomplete character or shift sequence at end of input
// E2BIG : output buffer full should only happen when using a temp buffer
}
else
m_nFailedChars += nResult;
if ( pToTempBuffer && nToCountRemaining < 10 )
{
nToCountRemaining = nTempBufferSize;
pToChar = pToTempBuffer;
}
}
if ( pToTempBuffer )
delete[] pToTempBuffer;
iconv_close(cd);
}
return nToLenBytes / nToCharSize;
}
#endif
#if defined(MARKUP_WINCONV)
bool x_NoDefaultChar( int nCP )
{
// WideCharToMultiByte fails if lpUsedDefaultChar is non-NULL for these code pages:
return (bool)(nCP == 65000 || nCP == 65001 || nCP == 50220 || nCP == 50221 || nCP == 50222 || nCP == 50225 ||
nCP == 50227 || nCP == 50229 || nCP == 52936 || nCP == 54936 || (nCP >= 57002 && nCP <= 57011) );
}
#endif
int TextEncoding::PerformConversion( void* pTo, MCD_CSTR pszToEncoding/*=NULL*/ )
{
// If pTo is not NULL, it must be large enough to hold result, length of result is returned
// m_nFailedChars will be set to >0 if characters not supported in strToEncoding
int nToLen = 0;
if ( pszToEncoding.pcsz )
m_strToEncoding = pszToEncoding;
int nToCP = x_GetEncodingCodePage( m_strToEncoding );
if ( nToCP == -1 )
nToCP = MCD_ACP;
int nFromCP = x_GetEncodingCodePage( m_strFromEncoding );
if ( nFromCP == -1 )
nFromCP = MCD_ACP;
m_nFailedChars = 0;
#if ! defined(MARKUP_WINCONV) && ! defined(MARKUP_ICONV)
// Only non-Unicode encoding supported is locale charset, must call setlocale
if ( nToCP != MCD_UTF8 && nToCP != MCD_UTF16 && nToCP != MCD_UTF32 )
nToCP = MCD_ACP;
if ( nFromCP != MCD_UTF8 && nFromCP != MCD_UTF16 && nFromCP != MCD_UTF32 )
nFromCP = MCD_ACP;
if ( nFromCP == MCD_ACP )
{
const char* pA = (const char*)m_pFrom;
int nALenRemaining = m_nFromLen;
int nCharLen;
wchar_t wcChar;
char* pU = (char*)pTo;
while ( nALenRemaining )
{
nCharLen = mbtowc( &wcChar, pA, nALenRemaining );
if ( nCharLen < 1 )
{
wcChar = (wchar_t)'?';
nCharLen = 1;
}
pA += nCharLen;
nALenRemaining -= nCharLen;
if ( nToCP == MCD_UTF8 )
CMarkup::EncodeCharUTF8( (int)wcChar, pU, nToLen );
else if ( nToCP == MCD_UTF16 )
CMarkup::EncodeCharUTF16( (int)wcChar, (unsigned short*)pU, nToLen );
else // UTF32
{
if ( pU )
((unsigned int*)pU)[nToLen] = (unsigned int)wcChar;
++nToLen;
}
}
}
else if ( nToCP == MCD_ACP )
{
union pUnicodeUnion { const char* p8; const unsigned short* p16; const unsigned int* p32; } pU;
pU.p8 = (const char*)m_pFrom;
const char* pUEnd = pU.p8 + m_nFromLen;
if ( nFromCP == MCD_UTF16 )
pUEnd = (char*)( pU.p16 + m_nFromLen );
else if ( nFromCP == MCD_UTF32 )
pUEnd = (char*)( pU.p32 + m_nFromLen );
int nCharLen;
char* pA = (char*)pTo;
char szA[8];
int nUChar;
while ( pU.p8 != pUEnd )
{
if ( nFromCP == MCD_UTF8 )
nUChar = CMarkup::DecodeCharUTF8( pU.p8, pUEnd );
else if ( nFromCP == MCD_UTF16 )
nUChar = CMarkup::DecodeCharUTF16( pU.p16, (const unsigned short*)pUEnd );
else // UTF32
nUChar = *(pU.p32)++;
if ( nUChar == -1 )
nCharLen = -2;
else if ( nUChar & ~0xffff )
nCharLen = -1;
else
nCharLen = wctomb( pA?pA:szA, (wchar_t)nUChar );
if ( nCharLen < 0 )
{
if ( nCharLen == -1 )
++m_nFailedChars;
nCharLen = 1;
if ( pA )
*pA = '?';
}
if ( pA )
pA += nCharLen;
nToLen += nCharLen;
}
}
#endif // not WINCONV and not ICONV
if ( nFromCP == MCD_UTF32 )
{
const unsigned int* p32 = (const unsigned int*)m_pFrom;
const unsigned int* p32End = p32 + m_nFromLen;
if ( nToCP == MCD_UTF8 )
{
char* p8 = (char*)pTo;
while ( p32 != p32End )
CMarkup::EncodeCharUTF8( *p32++, p8, nToLen );
}
else if ( nToCP == MCD_UTF16 )
{
unsigned short* p16 = (unsigned short*)pTo;
while ( p32 != p32End )
CMarkup::EncodeCharUTF16( (int)*p32++, p16, nToLen );
}
else // to ANSI
{
// WINCONV not supported for 32To8, since only used for sizeof(wchar_t) == 4
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 1, 4 );
#endif // ICONV
}
}
else if ( nFromCP == MCD_UTF16 )
{
// UTF16To8 will be deprecated since weird output buffer size sensitivity not worth implementing here
const unsigned short* p16 = (const unsigned short*)m_pFrom;
const unsigned short* p16End = p16 + m_nFromLen;
int nUChar;
if ( nToCP == MCD_UTF32 )
{
unsigned int* p32 = (unsigned int*)pTo;
while ( p16 != p16End )
{
nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
if ( nUChar == -1 )
nUChar = '?';
if ( p32 )
p32[nToLen] = (unsigned int)nUChar;
++nToLen;
}
}
#if defined(MARKUP_WINCONV)
else // to UTF-8 or other multi-byte
{
nToLen = WideCharToMultiByte(nToCP,0,(const wchar_t*)m_pFrom,m_nFromLen,(char*)pTo,
m_nToCount?m_nToCount+1:0,NULL,x_NoDefaultChar(nToCP)?NULL:&m_nFailedChars);
}
#else // not WINCONV
else if ( nToCP == MCD_UTF8 )
{
char* p8 = (char*)pTo;
while ( p16 != p16End )
{
nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
if ( nUChar == -1 )
nUChar = '?';
CMarkup::EncodeCharUTF8( nUChar, p8, nToLen );
}
}
else // to ANSI
{
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 1, 2 );
#endif // ICONV
}
#endif // not WINCONV
}
else if ( nToCP == MCD_UTF16 ) // to UTF-16 from UTF-8/ANSI
{
#if defined(MARKUP_WINCONV)
nToLen = MultiByteToWideChar(nFromCP,0,(const char*)m_pFrom,m_nFromLen,(wchar_t*)pTo,m_nToCount);
#else // not WINCONV
if ( nFromCP == MCD_UTF8 )
{
const char* p8 = (const char*)m_pFrom;
const char* p8End = p8 + m_nFromLen;
int nUChar;
unsigned short* p16 = (unsigned short*)pTo;
while ( p8 != p8End )
{
nUChar = CMarkup::DecodeCharUTF8( p8, p8End );
if ( nUChar == -1 )
nUChar = '?';
if ( p16 )
p16[nToLen] = (unsigned short)nUChar;
++nToLen;
}
}
else // from ANSI
{
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 2, 1 );
#endif // ICONV
}
#endif // not WINCONV
}
else if ( nToCP == MCD_UTF32 ) // to UTF-32 from UTF-8/ANSI
{
if ( nFromCP == MCD_UTF8 )
{
const char* p8 = (const char*)m_pFrom;
const char* p8End = p8 + m_nFromLen;
int nUChar;
unsigned int* p32 = (unsigned int*)pTo;
while ( p8 != p8End )
{
nUChar = CMarkup::DecodeCharUTF8( p8, p8End );
if ( nUChar == -1 )
nUChar = '?';
if ( p32 )
p32[nToLen] = (unsigned int)nUChar;
++nToLen;
}
}
else // from ANSI
{
// WINCONV not supported for ATo32, since only used for sizeof(wchar_t) == 4
#if defined(MARKUP_ICONV)
// nToLen = IConv( pTo, 4, 1 );
// Linux: had trouble getting IConv to leave the BOM off of the UTF-32 output stream
// So converting via UTF-16 with native endianness
unsigned short* pwszUTF16 = new unsigned short[m_nFromLen];
MCD_STR strToEncoding = m_strToEncoding;
m_strToEncoding = MCD_T("UTF-16BE");
short nEndianTest = 1;
if ( ((char*)&nEndianTest)[0] ) // Little-endian?
m_strToEncoding = MCD_T("UTF-16LE");
m_nToCount = m_nFromLen;
int nUTF16Len = IConv( pwszUTF16, 2, 1 );
m_strToEncoding = strToEncoding;
const unsigned short* p16 = (const unsigned short*)pwszUTF16;
const unsigned short* p16End = p16 + nUTF16Len;
int nUChar;
unsigned int* p32 = (unsigned int*)pTo;
while ( p16 != p16End )
{
nUChar = CMarkup::DecodeCharUTF16( p16, p16End );
if ( nUChar == -1 )
nUChar = '?';
if ( p32 )
*p32++ = (unsigned int)nUChar;
++nToLen;
}
delete[] pwszUTF16;
#endif // ICONV
}
}
else
{
#if defined(MARKUP_ICONV)
nToLen = IConv( pTo, 1, 1 );
#elif defined(MARKUP_WINCONV)
wchar_t* pwszUTF16 = new wchar_t[m_nFromLen];
int nUTF16Len = MultiByteToWideChar(nFromCP,0,(const char*)m_pFrom,m_nFromLen,pwszUTF16,m_nFromLen);
nToLen = WideCharToMultiByte(nToCP,0,pwszUTF16,nUTF16Len,(char*)pTo,m_nToCount,NULL,
x_NoDefaultChar(nToCP)?NULL:&m_nFailedChars);
delete[] pwszUTF16;
#endif // WINCONV
}
// Store the length in case this is called again after allocating output buffer to fit
m_nToCount = nToLen;
return nToLen;
}
bool TextEncoding::FindRaggedEnd( int& nTruncBeforeBytes )
{
// Check for ragged end UTF-16 or multi-byte according to m_strToEncoding, expects at least 40 bytes to work with
bool bSuccess = true;
nTruncBeforeBytes = 0;
int nCP = x_GetEncodingCodePage( m_strFromEncoding );
if ( nCP == MCD_UTF16 )
{
unsigned short* pUTF16Buffer = (unsigned short*)m_pFrom;
const unsigned short* pUTF16Last = &pUTF16Buffer[m_nFromLen-1];
if ( CMarkup::DecodeCharUTF16(pUTF16Last,&pUTF16Buffer[m_nFromLen]) == -1 )
nTruncBeforeBytes = 2;
}
else // UTF-8, SBCS DBCS
{
if ( nCP == MCD_UTF8 )
{
char* pUTF8Buffer = (char*)m_pFrom;
char* pUTF8End = &pUTF8Buffer[m_nFromLen];
int nLast = m_nFromLen - 1;
const char* pUTF8Last = &pUTF8Buffer[nLast];
while ( nLast > 0 && CMarkup::DecodeCharUTF8(pUTF8Last,pUTF8End) == -1 )
pUTF8Last = &pUTF8Buffer[--nLast];
nTruncBeforeBytes = (int)(pUTF8End - pUTF8Last);
}
else
{
// Do a conversion-based test unless we can determine it is not multi-byte
// If m_strEncoding="" default code page then GetACP can tell us the code page, otherwise just do the test
#if defined(MARKUP_WINCONV)
if ( nCP == 0 )
nCP = GetACP();
#endif
int nMultibyteCharsToTest = 2;
switch ( nCP )
{
case 54936:
nMultibyteCharsToTest = 4;
case 932: case 51932: case 20932: case 50220: case 50221: case 50222: case 10001: // Japanese
case 949: case 51949: case 50225: case 1361: case 10003: case 20949: // Korean
case 874: case 20001: case 20004: case 10021: case 20003: // Taiwan
case 50930: case 50939: case 50931: case 50933: case 20833: case 50935: case 50937: // EBCDIC
case 936: case 51936: case 20936: case 52936: // Chinese
case 950: case 50227: case 10008: case 20000: case 20002: case 10002: // Chinese
nCP = 0;
break;
}
if ( nMultibyteCharsToTest > m_nFromLen )
nMultibyteCharsToTest = m_nFromLen;
if ( nCP == 0 && nMultibyteCharsToTest )
{
/*
1. convert the piece to Unicode with MultiByteToWideChar
2. Identify at least two Unicode code point boundaries at the end of
the converted piece by stepping backwards from the end and re-
converting the final 2 bytes, 3 bytes, 4 bytes etc, comparing the
converted end string to the end of the entire converted piece to find
a valid code point boundary.
3. Upon finding a code point boundary, I still want to make sure it
will convert the same separately on either side of the divide as it
does together, so separately convert the first byte and the remaining
bytes and see if the result together is the same as the whole end, if
not try the first two bytes and the remaining bytes. etc., until I
find a useable dividing point. If none found, go back to step 2 and
get a longer end string to try.
*/
m_strToEncoding = MCD_T("UTF-16");
m_nToCount = m_nFromLen*2;
unsigned short* pUTF16Buffer = new unsigned short[m_nToCount];
int nUTF16Len = PerformConversion( (void*)pUTF16Buffer );
int nOriginalByteLen = m_nFromLen;
// Guaranteed to have at least MARKUP_FILEBLOCKSIZE/2 bytes to work with
const int nMaxBytesToTry = 40;
unsigned short wsz16End[nMaxBytesToTry*2];
unsigned short wsz16EndDivided[nMaxBytesToTry*2];
const char* pszOriginalBytes = (const char*)m_pFrom;
int nBoundariesFound = 0;
bSuccess = false;
while ( nTruncBeforeBytes < nMaxBytesToTry && ! bSuccess )
{
++nTruncBeforeBytes;
m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes];
m_nFromLen = nTruncBeforeBytes;
m_nToCount = nMaxBytesToTry*2;
int nEndUTF16Len = PerformConversion( (void*)wsz16End );
if ( nEndUTF16Len && memcmp(wsz16End,&pUTF16Buffer[nUTF16Len-nEndUTF16Len],nEndUTF16Len*2) == 0 )
{
++nBoundariesFound;
if ( nBoundariesFound > 2 )
{
int nDivideAt = 1;
while ( nDivideAt < nTruncBeforeBytes )
{
m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes];
m_nFromLen = nDivideAt;
m_nToCount = nMaxBytesToTry*2;
int nDividedUTF16Len = PerformConversion( (void*)wsz16EndDivided );
if ( nDividedUTF16Len )
{
m_pFrom = &pszOriginalBytes[nOriginalByteLen-nTruncBeforeBytes+nDivideAt];
m_nFromLen = nTruncBeforeBytes-nDivideAt;
m_nToCount = nMaxBytesToTry*2-nDividedUTF16Len;
nDividedUTF16Len += PerformConversion( (void*)&wsz16EndDivided[nDividedUTF16Len] );
if ( m_nToCount && nEndUTF16Len == nDividedUTF16Len && memcmp(wsz16End,wsz16EndDivided,nEndUTF16Len) == 0 )
{
nTruncBeforeBytes -= nDivideAt;
bSuccess = true;
break;
}
}
++nDivideAt;
}
}
}
}
delete [] pUTF16Buffer;
}
}
}
return bSuccess;
}
bool x_EndianSwapRequired( int nDocFlags )
{
short nWord = 1;
char cFirstByte = ((char*)&nWord)[0];
if ( cFirstByte ) // LE
{
if ( nDocFlags & CMarkup::MDF_UTF16BEFILE )
return true;
}
else if ( nDocFlags & CMarkup::MDF_UTF16LEFILE )
return true;
return false;
}
void x_EndianSwapUTF16( unsigned short* pBuffer, int nCharLen )
{
unsigned short cChar;
while ( nCharLen-- )
{
cChar = pBuffer[nCharLen];
pBuffer[nCharLen] = (unsigned short)((cChar<<8) | (cChar>>8));
}
}
//////////////////////////////////////////////////////////////////////
// Element position indexes
// This is the primary means of storing the layout of the document
//
struct ElemPos
{
ElemPos() {};
ElemPos( const ElemPos& pos ) { *this = pos; };
int StartTagLen() const { return nStartTagLen; };
void SetStartTagLen( int n ) { nStartTagLen = n; };
void AdjustStartTagLen( int n ) { nStartTagLen += n; };
int EndTagLen() const { return nEndTagLen; };
void SetEndTagLen( int n ) { nEndTagLen = n; };
bool IsEmptyElement() { return (StartTagLen()==nLength)?true:false; };
int StartContent() const { return nStart + StartTagLen(); };
int ContentLen() const { return nLength - StartTagLen() - EndTagLen(); };
int StartAfter() const { return nStart + nLength; };
int Level() const { return nFlags & 0xffff; };
void SetLevel( int nLev ) { nFlags = (nFlags & ~0xffff) | nLev; };
void ClearVirtualParent() { memset(this,0,sizeof(ElemPos)); };
void SetEndTagLenUnparsed() { SetEndTagLen(1); };
bool IsUnparsed() { return EndTagLen() == 1; };
// Memory size: 8 32-bit integers == 32 bytes
int nStart;
int nLength;
unsigned int nStartTagLen : 22; // 4MB limit for start tag
unsigned int nEndTagLen : 10; // 1K limit for end tag
int nFlags; // 16 bits flags, 16 bits level 65536 depth limit
int iElemParent;
int iElemChild; // first child
int iElemNext; // next sibling
int iElemPrev; // if this is first, iElemPrev points to last
};
enum MarkupNodeFlagsInternal2
{
MNF_REPLACE = 0x001000,
MNF_QUOTED = 0x008000,
MNF_EMPTY = 0x010000,
MNF_DELETED = 0x020000,
MNF_FIRST = 0x080000,
MNF_PUBLIC = 0x300000,
MNF_ILLFORMED = 0x800000,
MNF_USER = 0xf000000
};
struct ElemPosTree
{
ElemPosTree() { Clear(); };
~ElemPosTree() { Release(); };
enum { PA_SEGBITS = 16, PA_SEGMASK = 0xffff };
void ReleaseElemPosTree() { Release(); Clear(); };
void Release() { for (int n=0;n<SegsUsed();++n) delete[] (char*)m_pSegs[n]; if (m_pSegs) delete[] (char*)m_pSegs; };
void Clear() { m_nSegs=0; m_nSize=0; m_pSegs=NULL; };
int GetSize() const { return m_nSize; };
int SegsUsed() const { return ((m_nSize-1)>>PA_SEGBITS) + 1; };
ElemPos& GetRefElemPosAt(int i) const { return m_pSegs[i>>PA_SEGBITS][i&PA_SEGMASK]; };
void CopyElemPosTree( ElemPosTree* pOtherTree, int n );
void GrowElemPosTree( int nNewSize );
private:
ElemPos** m_pSegs;
int m_nSize;
int m_nSegs;
};
void ElemPosTree::CopyElemPosTree( ElemPosTree* pOtherTree, int n )
{
ReleaseElemPosTree();
m_nSize = n;
if ( m_nSize < 8 )
m_nSize = 8;
m_nSegs = SegsUsed();
if ( m_nSegs )
{
m_pSegs = (ElemPos**)(new char[m_nSegs*sizeof(char*)]);
int nSegSize = 1 << PA_SEGBITS;
for ( int nSeg=0; nSeg < m_nSegs; ++nSeg )
{
if ( nSeg + 1 == m_nSegs )
nSegSize = m_nSize - (nSeg << PA_SEGBITS);
m_pSegs[nSeg] = (ElemPos*)(new char[nSegSize*sizeof(ElemPos)]);
memcpy( m_pSegs[nSeg], pOtherTree->m_pSegs[nSeg], nSegSize*sizeof(ElemPos) );
}
}
}
void ElemPosTree::GrowElemPosTree( int nNewSize )
{
// Called by x_AllocElemPos when the document is created or the array is filled
// The ElemPosTree class is implemented using segments to reduce contiguous memory requirements
// It reduces reallocations (copying of memory) since this only occurs within one segment
// The "Grow By" algorithm ensures there are no reallocations after 2 segments
//
// Grow By: new size can be at most one more complete segment
int nSeg = (m_nSize?m_nSize-1:0) >> PA_SEGBITS;
int nNewSeg = (nNewSize-1) >> PA_SEGBITS;
if ( nNewSeg > nSeg + 1 )
{
nNewSeg = nSeg + 1;
nNewSize = (nNewSeg+1) << PA_SEGBITS;
}
// Allocate array of segments
if ( m_nSegs <= nNewSeg )
{
int nNewSegments = 4 + nNewSeg * 2;
char* pNewSegments = new char[nNewSegments*sizeof(char*)];
if ( SegsUsed() )
memcpy( pNewSegments, m_pSegs, SegsUsed()*sizeof(char*) );
if ( m_pSegs )
delete[] (char*)m_pSegs;
m_pSegs = (ElemPos**)pNewSegments;
m_nSegs = nNewSegments;
}
// Calculate segment sizes
int nSegSize = m_nSize - (nSeg << PA_SEGBITS);
int nNewSegSize = nNewSize - (nNewSeg << PA_SEGBITS);
// Complete first segment
int nFullSegSize = 1 << PA_SEGBITS;
if ( nSeg < nNewSeg && nSegSize < nFullSegSize )
{
char* pNewFirstSeg = new char[ nFullSegSize * sizeof(ElemPos) ];
if ( nSegSize )
{
// Reallocate
memcpy( pNewFirstSeg, m_pSegs[nSeg], nSegSize * sizeof(ElemPos) );
delete[] (char*)m_pSegs[nSeg];
}
m_pSegs[nSeg] = (ElemPos*)pNewFirstSeg;
}
// New segment
char* pNewSeg = new char[ nNewSegSize * sizeof(ElemPos) ];
if ( nNewSeg == nSeg && nSegSize )
{
// Reallocate
memcpy( pNewSeg, m_pSegs[nSeg], nSegSize * sizeof(ElemPos) );
delete[] (char*)m_pSegs[nSeg];
}
m_pSegs[nNewSeg] = (ElemPos*)pNewSeg;
m_nSize = nNewSize;
}
#define ELEM(i) m_pElemPosTree->GetRefElemPosAt(i)
//////////////////////////////////////////////////////////////////////
// NodePos stores information about an element or node during document creation and parsing
//
struct NodePos
{
NodePos() {};
NodePos( int n ) { nNodeFlags=n; nNodeType=0; nStart=0; nLength=0; };
int nNodeType;
int nStart;
int nLength;
int nNodeFlags;
MCD_STR strMeta;
};
//////////////////////////////////////////////////////////////////////
// Token struct and tokenizing functions
// TokenPos handles parsing operations on a constant text pointer
//
struct TokenPos
{
TokenPos( MCD_CSTR sz, int n, FilePos* p=NULL ) { Clear(); m_pDocText=sz; m_nTokenFlags=n; m_pReaderFilePos=p; };
void Clear() { m_nL=0; m_nR=-1; m_nNext=0; };
int Length() const { return m_nR - m_nL + 1; };
MCD_PCSZ GetTokenPtr() const { return &m_pDocText[m_nL]; };
MCD_STR GetTokenText() const { return MCD_STR( GetTokenPtr(), Length() ); };
int WhitespaceToTag( int n ) { m_nNext = n; if (FindAny()&&m_pDocText[m_nNext]!='<') { m_nNext=n; m_nR=n-1; } return m_nNext; };
void ForwardUntil( MCD_PCSZ szStopChars ) { while ( m_pDocText[m_nNext] && ! MCD_PSZCHR(szStopChars,m_pDocText[m_nNext]) ) m_nNext += MCD_CLEN(&m_pDocText[m_nNext]); }
bool FindAny()
{
// Go to non-whitespace or end
while ( m_pDocText[m_nNext] && MCD_PSZCHR(MCD_T(" \t\n\r"),m_pDocText[m_nNext]) )
++m_nNext;
m_nL = m_nNext;
m_nR = m_nNext-1;
return m_pDocText[m_nNext]!='\0';
};
bool FindName()
{
if ( ! FindAny() ) // go to first non-whitespace
return false;
ForwardUntil(MCD_T(" \t\n\r<>=\\/?!\"';"));
if ( m_nNext == m_nL )
++m_nNext; // it is a special char
m_nR = m_nNext - 1;
return true;
}
static int StrNIACmp( MCD_PCSZ p1, MCD_PCSZ p2, int n )
{
// string compare ignore case
bool bNonAsciiFound = false;
MCD_CHAR c1, c2;
while ( n-- )
{
c1 = *p1++;
c2 = *p2++;
if ( c1 != c2 )
{
if ( bNonAsciiFound )
return c1 - c2;
if ( c1 >= 'a' && c1 <= 'z' )
c1 = (MCD_CHAR)( c1 - ('a'-'A') );
if ( c2 >= 'a' && c2 <= 'z' )
c2 = (MCD_CHAR)( c2 - ('a'-'A') );
if ( c1 != c2 )
return c1 - c2;
}
else if ( (unsigned int)c1 > 127 )
bNonAsciiFound = true;
}
return 0;
}
bool Match( MCD_CSTR szName )
{
int nLen = Length();
if ( m_nTokenFlags & CMarkup::MDF_IGNORECASE )
return ( (StrNIACmp( GetTokenPtr(), szName, nLen ) == 0)
&& ( szName[nLen] == '\0' || MCD_PSZCHR(MCD_T(" =/[]"),szName[nLen]) ) );
else
return ( (MCD_PSZNCMP( GetTokenPtr(), szName, nLen ) == 0)
&& ( szName[nLen] == '\0' || MCD_PSZCHR(MCD_T(" =/[]"),szName[nLen]) ) );
};
bool FindAttrib( MCD_PCSZ pAttrib, int n = 0 );
int ParseNode( NodePos& node );
int m_nL;
int m_nR;
int m_nNext;
MCD_PCSZ m_pDocText;
int m_nTokenFlags;
int m_nPreSpaceStart;
int m_nPreSpaceLength;
FilePos* m_pReaderFilePos;
};
bool TokenPos::FindAttrib( MCD_PCSZ pAttrib, int n/*=0*/ )
{
// Return true if found, otherwise false and token.m_nNext is new insertion point
// If pAttrib is NULL find attrib n and leave token at attrib name
// If pAttrib is given, find matching attrib and leave token at value
// support non-well-formed attributes e.g. href=/advanced_search?hl=en, nowrap
// token also holds start and length of preceeding whitespace to support remove
//
int nTempPreSpaceStart;
int nTempPreSpaceLength;
MCD_CHAR cFirstChar;
int nAttrib = -1; // starts at tag name
int nFoundAttribNameR = 0;
bool bAfterEqual = false;
while ( 1 )
{
// Starting at m_nNext, bypass whitespace and find the next token
nTempPreSpaceStart = m_nNext;
if ( ! FindAny() )
break;
nTempPreSpaceLength = m_nNext - nTempPreSpaceStart;
// Is it an opening quote?
cFirstChar = m_pDocText[m_nNext];
if ( cFirstChar == '\"' || cFirstChar == '\'' )
{
m_nTokenFlags |= MNF_QUOTED;
// Move past opening quote
++m_nNext;
m_nL = m_nNext;
// Look for closing quote
while ( m_pDocText[m_nNext] && m_pDocText[m_nNext] != cFirstChar )
m_nNext += MCD_CLEN( &m_pDocText[m_nNext] );
// Set right to before closing quote
m_nR = m_nNext - 1;
// Set m_nNext past closing quote unless at end of document
if ( m_pDocText[m_nNext] )
++m_nNext;
}
else
{
m_nTokenFlags &= ~MNF_QUOTED;
// Go until special char or whitespace
m_nL = m_nNext;
if ( bAfterEqual )
ForwardUntil(MCD_T(" \t\n\r>"));
else
ForwardUntil(MCD_T("= \t\n\r>/?"));
// Adjust end position if it is one special char
if ( m_nNext == m_nL )
++m_nNext; // it is a special char
m_nR = m_nNext - 1;
}
if ( ! bAfterEqual && ! (m_nTokenFlags&MNF_QUOTED) )
{
// Is it an equal sign?
MCD_CHAR cChar = m_pDocText[m_nL];
if ( cChar == '=' )
{
bAfterEqual = true;
continue;
}
// Is it the right angle bracket?
if ( cChar == '>' || cChar == '/' || cChar == '?' )
{
m_nNext = nTempPreSpaceStart;
break; // attrib not found
}
if ( nFoundAttribNameR )
break;
// Attribute name
if ( nAttrib != -1 )
{
if ( ! pAttrib )
{
if ( nAttrib == n )
return true; // found by number
}
else if ( Match(pAttrib) )
{
// Matched attrib name, go forward to value
nFoundAttribNameR = m_nR;
m_nPreSpaceStart = nTempPreSpaceStart;
m_nPreSpaceLength = nTempPreSpaceLength;
}
}
++nAttrib;
}
else if ( nFoundAttribNameR )
break;
bAfterEqual = false;
}
if ( nFoundAttribNameR )
{
if ( ! bAfterEqual )
{
// when attribute has no value the value is the attribute name
m_nL = m_nPreSpaceStart + m_nPreSpaceLength;
m_nR = nFoundAttribNameR;
m_nNext = nFoundAttribNameR + 1;
}
return true; // found by name
}
return false; // not found
}
//////////////////////////////////////////////////////////////////////
// Element tag stack: an array of TagPos structs to track nested elements
// This is used during parsing to match end tags with corresponding start tags
// For x_ParseElem only ElemStack::iTop is used with PushIntoLevel, PopOutOfLevel, and Current
// For file mode then the full capabilities are used to track counts of sibling tag names for path support
//
struct TagPos
{
TagPos() { Init(); };
void SetTagName( MCD_PCSZ pName, int n ) { MCD_STRASSIGN(strTagName,pName,n); };
void Init( int i=0, int n=1 ) { nCount=1; nTagNames=n; iNext=i; iPrev=0; nSlot=-1; iSlotPrev=0; iSlotNext=0; };
void IncCount() { if (nCount) ++nCount; };
MCD_STR strTagName;
int nCount;
int nTagNames;
int iParent;
int iNext;
int iPrev;
int nSlot;
int iSlotNext;
int iSlotPrev;
};
struct ElemStack
{
enum { LS_TABLESIZE = 23 };
ElemStack() { iTop=0; iUsed=0; iPar=0; nLevel=0; nSize=0; pL=NULL; Alloc(7); pL[0].Init(); InitTable(); };
~ElemStack() { if (pL) delete [] pL; };
TagPos& Current() { return pL[iTop]; };
void InitTable() { memset(anTable,0,sizeof(int)*LS_TABLESIZE); };
TagPos& NextParent( int& i ) { int iCur=i; i=pL[i].iParent; return pL[iCur]; };
TagPos& GetRefTagPosAt( int i ) { return pL[i]; };
void Push( MCD_PCSZ pName, int n ) { ++iUsed; if (iUsed==nSize) Alloc(nSize*2); pL[iUsed].SetTagName(pName,n); pL[iUsed].iParent=iPar; iTop=iUsed; };
void IntoLevel() { iPar = iTop; ++nLevel; };
void OutOfLevel() { if (iPar!=iTop) Pop(); iPar = pL[iTop].iParent; --nLevel; };
void PushIntoLevel( MCD_PCSZ pName, int n ) { ++iTop; if (iTop==nSize) Alloc(nSize*2); pL[iTop].SetTagName(pName,n); };
void PopOutOfLevel() { --iTop; };
void Pop() { iTop = iPar; while (iUsed && pL[iUsed].iParent==iPar) { if (pL[iUsed].nSlot!=-1) Unslot(pL[iUsed]); --iUsed; } };
void Slot( int n ) { pL[iUsed].nSlot=n; int i=anTable[n]; anTable[n]=iUsed; pL[iUsed].iSlotNext=i; if (i) pL[i].iSlotPrev=iUsed; };
void Unslot( TagPos& lp ) { int n=lp.iSlotNext,p=lp.iSlotPrev; if (n) pL[n].iSlotPrev=p; if (p) pL[p].iSlotNext=n; else anTable[lp.nSlot]=n; };
static int CalcSlot( MCD_PCSZ pName, int n, bool bIC );
void PushTagAndCount( TokenPos& token );
int iTop;
int nLevel;
int iPar;
protected:
void Alloc( int nNewSize ) { TagPos* pLNew = new TagPos[nNewSize]; Copy(pLNew); nSize=nNewSize; };
void Copy( TagPos* pLNew ) { for(int n=0;n<nSize;++n) pLNew[n]=pL[n]; if (pL) delete [] pL; pL=pLNew; };
TagPos* pL;
int iUsed;
int nSize;
int anTable[LS_TABLESIZE];
};
int ElemStack::CalcSlot( MCD_PCSZ pName, int n, bool bIC )
{
// If bIC (ASCII ignore case) then return an ASCII case insensitive hash
unsigned int nHash = 0;
MCD_PCSZ pEnd = pName + n;
while ( pName != pEnd )
{
nHash += (unsigned int)(*pName);
if ( bIC && *pName >= 'A' && *pName <= 'Z' )
nHash += ('a'-'A');
++pName;
}
return nHash%LS_TABLESIZE;
}
void ElemStack::PushTagAndCount( TokenPos& token )
{
// Check for a matching tag name at the top level and set current if found or add new one
// Calculate hash of tag name, support ignore ASCII case for MDF_IGNORECASE
int nSlot = -1;
int iNext = 0;
MCD_PCSZ pTagName = token.GetTokenPtr();
if ( iTop != iPar )
{
// See if tag name is already used, first try previous sibling (almost always)
iNext = iTop;
if ( token.Match(Current().strTagName) )
{
iNext = -1;
Current().IncCount();
}
else
{
nSlot = CalcSlot( pTagName, token.Length(), (token.m_nTokenFlags & CMarkup::MDF_IGNORECASE)?true:false );
int iLookup = anTable[nSlot];
while ( iLookup )
{
TagPos& tag = pL[iLookup];
if ( tag.iParent == iPar && token.Match(tag.strTagName) )
{
pL[tag.iPrev].iNext = tag.iNext;
if ( tag.iNext )
pL[tag.iNext].iPrev = tag.iPrev;
tag.nTagNames = Current().nTagNames;
tag.iNext = iTop;
tag.IncCount();
iTop = iLookup;
iNext = -1;
break;
}
iLookup = tag.iSlotNext;
}
}
}
if ( iNext != -1 )
{
// Turn off in the rare case where a document uses unique tag names like record1, record2, etc, more than 256
int nTagNames = 0;
if ( iNext )
nTagNames = Current().nTagNames;
if ( nTagNames == 256 )
{
MCD_STRASSIGN( (Current().strTagName), pTagName, (token.Length()) );
Current().nCount = 0;
Unslot( Current() );
}
else
{
Push( pTagName, token.Length() );
Current().Init( iNext, nTagNames+1 );
}
if ( nSlot == -1 )
nSlot = CalcSlot( pTagName, token.Length(), (token.m_nTokenFlags & CMarkup::MDF_IGNORECASE)?true:false );
Slot( nSlot );
}
}
//////////////////////////////////////////////////////////////////////
// FilePos is created for a file while it is open
// In file mode the file stays open between CMarkup calls and is stored in m_pFilePos
//
struct FilePos
{
FilePos()
{
m_fp=NULL; m_nDocFlags=0; m_nFileByteLen=0; m_nFileByteOffset=0; m_nOpFileByteLen=0; m_nBlockSizeBasis=MARKUP_FILEBLOCKSIZE;
m_nFileCharUnitSize=0; m_nOpFileTextLen=0; m_pstrBuffer=NULL; m_nReadBufferStart=0; m_nReadBufferRemoved=0; m_nReadGatherStart=-1;
};
bool FileOpen( MCD_CSTR_FILENAME szFileName );
bool FileRead( void* pBuffer );
bool FileReadText( MCD_STR& strDoc );
bool FileCheckRaggedEnd( void* pBuffer );
bool FileReadNextBuffer();
void FileGatherStart( int nStart );
int FileGatherEnd( MCD_STR& strSubDoc );
bool FileWrite( void* pBuffer, const void* pConstBuffer = NULL );
bool FileWriteText( const MCD_STR& strDoc, int nWriteStrLen = -1 );
bool FileFlush( MCD_STR& strBuffer, int nWriteStrLen = -1, bool bFflush = false );
bool FileClose();
void FileSpecifyEncoding( MCD_STR* pstrEncoding );
bool FileAtTop();
bool FileErrorAddResult();
FILE* m_fp;
int m_nDocFlags;
int m_nOpFileByteLen;
int m_nBlockSizeBasis;
MCD_INTFILEOFFSET m_nFileByteLen;
MCD_INTFILEOFFSET m_nFileByteOffset;
int m_nFileCharUnitSize;
int m_nOpFileTextLen;
MCD_STR m_strIOResult;
MCD_STR m_strEncoding;
MCD_STR* m_pstrBuffer;
ElemStack m_elemstack;
int m_nReadBufferStart;
int m_nReadBufferRemoved;
int m_nReadGatherStart;
MCD_STR m_strReadGatherMarkup;
};
struct BomTableStruct { const char* pszBom; int nBomLen; MCD_PCSZ pszBomEnc; int nBomFlag; } BomTable[] =
{
{ "\xef\xbb\xbf", 3, MCD_T("UTF-8"), CMarkup::MDF_UTF8PREAMBLE },
{ "\xff\xfe", 2, MCD_T("UTF-16LE"), CMarkup::MDF_UTF16LEFILE },
{ "\xfe\xff", 2, MCD_T("UTF-16BE"), CMarkup::MDF_UTF16BEFILE },
{ NULL,0,NULL,0 }
};
bool FilePos::FileErrorAddResult()
{
// strerror has difficulties cross-platform
// VC++ leaves MCD_STRERROR undefined and uses FormatMessage
// Non-VC++ use strerror (even for MARKUP_WCHAR and convert)
// additional notes:
// _WIN32_WCE (Windows CE) has no strerror (Embedded VC++ uses FormatMessage)
// _MSC_VER >= 1310 (VC++ 2003/7.1) has _wcserror (but not used)
//
const int nErrorBufferSize = 100;
int nErr = 0;
MCD_CHAR szError[nErrorBufferSize+1];
#if defined(MCD_STRERROR) // C error routine
nErr = (int)errno;
#if defined(MARKUP_WCHAR)
char szMBError[nErrorBufferSize+1];
strncpy( szMBError, MCD_STRERROR, nErrorBufferSize );
szMBError[nErrorBufferSize] = '\0';
TextEncoding textencoding( MCD_T(""), (const void*)szMBError, strlen(szMBError) );
textencoding.m_nToCount = nErrorBufferSize;
int nWideLen = textencoding.PerformConversion( (void*)szError, MCD_ENC );
szError[nWideLen] = '\0';
#else
MCD_PSZNCPY( szError, MCD_STRERROR, nErrorBufferSize );
szError[nErrorBufferSize] = '\0';
#endif
#else // no C error routine, use Windows API
DWORD dwErr = ::GetLastError();
if ( ::FormatMessage(0x1200,0,dwErr,0,szError,nErrorBufferSize,0) < 1 )
szError[0] = '\0';
nErr = (int)dwErr;
#endif // no C error routine
MCD_STR strError = szError;
for ( int nChar=0; nChar<MCD_STRLENGTH(strError); ++nChar )
if ( strError[nChar] == '\r' || strError[nChar] == '\n' )
{
strError = MCD_STRMID( strError, 0, nChar ); // no trailing newline
break;
}
x_AddResult( m_strIOResult, MCD_T("file_error"), strError, MRC_MSG|MRC_NUMBER, nErr );
return false;
}
void FilePos::FileSpecifyEncoding( MCD_STR* pstrEncoding )
{
// In ReadTextFile, WriteTextFile and Open, the pstrEncoding argument can override or return the detected encoding
if ( pstrEncoding && m_strEncoding != *pstrEncoding )
{
if ( m_nFileCharUnitSize == 1 && *pstrEncoding != MCD_T("") )
m_strEncoding = *pstrEncoding; // override the encoding
else // just report the encoding
*pstrEncoding = m_strEncoding;
}
}
bool FilePos::FileAtTop()
{
// Return true if in the first block of file mode, max BOM < 5 bytes
if ( ((m_nDocFlags & CMarkup::MDF_READFILE) && m_nFileByteOffset < (MCD_INTFILEOFFSET)m_nOpFileByteLen + 5 )
|| ((m_nDocFlags & CMarkup::MDF_WRITEFILE) && m_nFileByteOffset < 5) )
return true;
return false;
}
bool FilePos::FileOpen( MCD_CSTR_FILENAME szFileName )
{
MCD_STRCLEAR( m_strIOResult );
// Open file
MCD_PCSZ_FILENAME pMode = MCD_T_FILENAME("rb");
if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
pMode = MCD_T_FILENAME("ab");
else if ( m_nDocFlags & CMarkup::MDF_WRITEFILE )
pMode = MCD_T_FILENAME("wb");
m_fp = NULL;
MCD_FOPEN( m_fp, szFileName, pMode );
if ( ! m_fp )
return FileErrorAddResult();
// Prepare file
bool bSuccess = true;
int nBomLen = 0;
m_nFileCharUnitSize = 1; // unless UTF-16 BOM
if ( m_nDocFlags & CMarkup::MDF_READFILE )
{
// Get file length
MCD_FSEEK( m_fp, 0, SEEK_END );
m_nFileByteLen = MCD_FTELL( m_fp );
MCD_FSEEK( m_fp, 0, SEEK_SET );
// Read the top of the file to check BOM and encoding
int nReadTop = 1024;
if ( m_nFileByteLen < nReadTop )
nReadTop = (int)m_nFileByteLen;
if ( nReadTop )
{
char* pFileTop = new char[nReadTop];
if ( nReadTop )
bSuccess = ( fread( pFileTop, nReadTop, 1, m_fp ) == 1 );
if ( bSuccess )
{
// Check for Byte Order Mark (preamble)
int nBomCheck = 0;
m_nDocFlags &= ~( CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF8PREAMBLE );
while ( BomTable[nBomCheck].pszBom )
{
while ( nBomLen < BomTable[nBomCheck].nBomLen )
{
if ( nBomLen >= nReadTop || pFileTop[nBomLen] != BomTable[nBomCheck].pszBom[nBomLen] )
break;
++nBomLen;
}
if ( nBomLen == BomTable[nBomCheck].nBomLen )
{
m_nDocFlags |= BomTable[nBomCheck].nBomFlag;
if ( nBomLen == 2 )
m_nFileCharUnitSize = 2;
m_strEncoding = BomTable[nBomCheck].pszBomEnc;
break;
}
++nBomCheck;
nBomLen = 0;
}
if ( nReadTop > nBomLen )
MCD_FSEEK( m_fp, nBomLen, SEEK_SET );
// Encoding check
if ( ! nBomLen )
{
MCD_STR strDeclCheck;
#if defined(MARKUP_WCHAR) // WCHAR
TextEncoding textencoding( MCD_T("UTF-8"), (const void*)pFileTop, nReadTop );
MCD_CHAR* pWideBuffer = MCD_GETBUFFER(strDeclCheck,nReadTop);
textencoding.m_nToCount = nReadTop;
int nDeclWideLen = textencoding.PerformConversion( (void*)pWideBuffer, MCD_ENC );
MCD_RELEASEBUFFER(strDeclCheck,pWideBuffer,nDeclWideLen);
#else // not WCHAR
MCD_STRASSIGN(strDeclCheck,pFileTop,nReadTop);
#endif // not WCHAR
m_strEncoding = CMarkup::GetDeclaredEncoding( strDeclCheck );
}
// Assume markup files starting with < sign are UTF-8 if otherwise unknown
if ( MCD_STRISEMPTY(m_strEncoding) && pFileTop[0] == '<' )
m_strEncoding = MCD_T("UTF-8");
}
delete [] pFileTop;
}
}
else if ( m_nDocFlags & CMarkup::MDF_WRITEFILE )
{
if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
{
// fopen for append does not move the file pointer to the end until first I/O operation
MCD_FSEEK( m_fp, 0, SEEK_END );
m_nFileByteLen = MCD_FTELL( m_fp );
}
int nBomCheck = 0;
while ( BomTable[nBomCheck].pszBom )
{
if ( m_nDocFlags & BomTable[nBomCheck].nBomFlag )
{
nBomLen = BomTable[nBomCheck].nBomLen;
if ( nBomLen == 2 )
m_nFileCharUnitSize = 2;
m_strEncoding = BomTable[nBomCheck].pszBomEnc;
if ( m_nFileByteLen ) // append
nBomLen = 0;
else // write BOM
bSuccess = ( fwrite(BomTable[nBomCheck].pszBom,nBomLen,1,m_fp) == 1 );
break;
}
++nBomCheck;
}
}
if ( ! bSuccess )
return FileErrorAddResult();
if ( m_nDocFlags & CMarkup::MDF_APPENDFILE )
m_nFileByteOffset = m_nFileByteLen;
else
m_nFileByteOffset = (MCD_INTFILEOFFSET)nBomLen;
if ( nBomLen )
x_AddResult( m_strIOResult, MCD_T("bom") );
return bSuccess;
}
bool FilePos::FileRead( void* pBuffer )
{
bool bSuccess = ( fread( pBuffer,m_nOpFileByteLen,1,m_fp) == 1 );
m_nOpFileTextLen = m_nOpFileByteLen / m_nFileCharUnitSize;
if ( bSuccess )
{
m_nFileByteOffset += m_nOpFileByteLen;
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, m_nOpFileTextLen );
// Microsoft components can produce apparently valid docs with some nulls at ends of values
int nNullCount = 0;
int nNullCheckCharsRemaining = m_nOpFileTextLen;
char* pAfterNull = NULL;
char* pNullScan = (char*)pBuffer;
bool bSingleByteChar = m_nFileCharUnitSize == 1;
while ( nNullCheckCharsRemaining-- )
{
if ( bSingleByteChar? (! *pNullScan) : (! (*(unsigned short*)pNullScan)) )
{
if ( pAfterNull && pNullScan != pAfterNull )
memmove( pAfterNull - (nNullCount*m_nFileCharUnitSize), pAfterNull, pNullScan - pAfterNull );
pAfterNull = pNullScan + m_nFileCharUnitSize;
++nNullCount;
}
pNullScan += m_nFileCharUnitSize;
}
if ( pAfterNull && pNullScan != pAfterNull )
memmove( pAfterNull - (nNullCount*m_nFileCharUnitSize), pAfterNull, pNullScan - pAfterNull );
if ( nNullCount )
{
x_AddResult( m_strIOResult, MCD_T("nulls_removed"), NULL, MRC_COUNT, nNullCount );
m_nOpFileTextLen -= nNullCount;
}
// Big endian/little endian conversion
if ( m_nFileCharUnitSize > 1 && x_EndianSwapRequired(m_nDocFlags) )
{
x_EndianSwapUTF16( (unsigned short*)pBuffer, m_nOpFileTextLen );
x_AddResult( m_strIOResult, MCD_T("endian_swap") );
}
}
if ( ! bSuccess )
FileErrorAddResult();
return bSuccess;
}
bool FilePos::FileCheckRaggedEnd( void* pBuffer )
{
// In file read mode, piece of file text in memory must end on a character boundary
// This check must happen after the encoding has been decided, so after UTF-8 autodetection
// If ragged, adjust file position, m_nOpFileTextLen and m_nOpFileByteLen
int nTruncBeforeBytes = 0;
TextEncoding textencoding( m_strEncoding, pBuffer, m_nOpFileTextLen );
if ( ! textencoding.FindRaggedEnd(nTruncBeforeBytes) )
{
// Input must be garbled? decoding error before potentially ragged end, add error result and continue
MCD_STR strEncoding = m_strEncoding;
if ( MCD_STRISEMPTY(strEncoding) )
strEncoding = MCD_T("ANSI");
x_AddResult( m_strIOResult, MCD_T("truncation_error"), strEncoding, MRC_ENCODING );
}
else if ( nTruncBeforeBytes )
{
nTruncBeforeBytes *= -1;
m_nFileByteOffset += nTruncBeforeBytes;
MCD_FSEEK( m_fp, m_nFileByteOffset, SEEK_SET );
m_nOpFileByteLen += nTruncBeforeBytes;
m_nOpFileTextLen += nTruncBeforeBytes / m_nFileCharUnitSize;
x_AddResult( m_strIOResult, MCD_T("read"), NULL, MRC_MODIFY|MRC_LENGTH, m_nOpFileTextLen );
}
return true;
}
bool FilePos::FileReadText( MCD_STR& strDoc )
{
bool bSuccess = true;
MCD_STRCLEAR( m_strIOResult );
if ( ! m_nOpFileByteLen )
{
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, 0 );
return bSuccess;
}
// Only read up to end of file (a single read byte length cannot be over the capacity of int)
bool bCheckRaggedEnd = true;
MCD_INTFILEOFFSET nBytesRemaining = m_nFileByteLen - m_nFileByteOffset;
if ( (MCD_INTFILEOFFSET)m_nOpFileByteLen >= nBytesRemaining )
{
m_nOpFileByteLen = (int)nBytesRemaining;
bCheckRaggedEnd = false;
}
if ( m_nDocFlags & (CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF16BEFILE) )
{
int nUTF16Len = m_nOpFileByteLen / 2;
#if defined(MARKUP_WCHAR) // WCHAR
int nBufferSizeForGrow = nUTF16Len + nUTF16Len/100; // extra 1%
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
unsigned short* pUTF16Buffer = new unsigned short[nUTF16Len+1];
bSuccess = FileRead( pUTF16Buffer );
if ( bSuccess )
{
if ( bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pUTF16Buffer );
TextEncoding textencoding( MCD_T("UTF-16"), (const void*)pUTF16Buffer, m_nOpFileTextLen );
textencoding.m_nToCount = nBufferSizeForGrow;
MCD_CHAR* pUTF32Buffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
int nUTF32Len = textencoding.PerformConversion( (void*)pUTF32Buffer, MCD_T("UTF-32") );
MCD_RELEASEBUFFER(strDoc,pUTF32Buffer,nUTF32Len);
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_T("UTF-32"), MRC_ENCODING|MRC_LENGTH, nUTF32Len );
}
#else // sizeof(wchar_t) == 2
MCD_CHAR* pUTF16Buffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
bSuccess = FileRead( pUTF16Buffer );
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pUTF16Buffer );
MCD_RELEASEBUFFER(strDoc,pUTF16Buffer,m_nOpFileTextLen);
#endif // sizeof(wchar_t) == 2
#else // not WCHAR
// Convert file from UTF-16; it needs to be in memory as UTF-8 or MBCS
unsigned short* pUTF16Buffer = new unsigned short[nUTF16Len+1];
bSuccess = FileRead( pUTF16Buffer );
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pUTF16Buffer );
TextEncoding textencoding( MCD_T("UTF-16"), (const void*)pUTF16Buffer, m_nOpFileTextLen );
int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
int nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
MCD_CHAR* pMBBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pMBBuffer );
delete [] pUTF16Buffer;
MCD_RELEASEBUFFER(strDoc,pMBBuffer,nMBLen);
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
#endif // not WCHAR
}
else // single or multibyte file (i.e. not UTF-16)
{
#if defined(MARKUP_WCHAR) // WCHAR
char* pBuffer = new char[m_nOpFileByteLen];
bSuccess = FileRead( pBuffer );
if ( MCD_STRISEMPTY(m_strEncoding) )
{
int nNonASCII;
bool bErrorAtEnd;
if ( CMarkup::DetectUTF8(pBuffer,m_nOpFileByteLen,&nNonASCII,&bErrorAtEnd) || (bCheckRaggedEnd && bErrorAtEnd) )
{
m_strEncoding = MCD_T("UTF-8");
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_MODIFY|MRC_ENCODING );
}
x_AddResult( m_strIOResult, MCD_T("utf8_detection") );
}
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pBuffer );
TextEncoding textencoding( m_strEncoding, (const void*)pBuffer, m_nOpFileTextLen );
int nWideLen = textencoding.PerformConversion( NULL, MCD_ENC );
int nBufferSizeForGrow = nWideLen + nWideLen/100; // extra 1%
MCD_CHAR* pWideBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pWideBuffer );
MCD_RELEASEBUFFER( strDoc, pWideBuffer, nWideLen );
delete [] pBuffer;
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWideLen );
#else // not WCHAR
// After loading a file with unknown multi-byte encoding
bool bAssumeUnknownIsNative = false;
if ( MCD_STRISEMPTY(m_strEncoding) )
{
bAssumeUnknownIsNative = true;
m_strEncoding = MCD_ENC;
}
if ( TextEncoding::CanConvert(MCD_ENC,m_strEncoding) )
{
char* pBuffer = new char[m_nOpFileByteLen];
bSuccess = FileRead( pBuffer );
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pBuffer );
TextEncoding textencoding( m_strEncoding, (const void*)pBuffer, m_nOpFileTextLen );
int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
int nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
MCD_CHAR* pMBBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pMBBuffer );
MCD_RELEASEBUFFER( strDoc, pMBBuffer, nMBLen );
delete [] pBuffer;
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
}
else // load directly into string
{
int nBufferSizeForGrow = m_nOpFileByteLen + m_nOpFileByteLen/100; // extra 1%
MCD_CHAR* pBuffer = MCD_GETBUFFER(strDoc,nBufferSizeForGrow);
bSuccess = FileRead( pBuffer );
bool bConvertMB = false;
if ( bAssumeUnknownIsNative )
{
// Might need additional conversion if we assumed an encoding
int nNonASCII;
bool bErrorAtEnd;
bool bIsUTF8 = CMarkup::DetectUTF8( pBuffer, m_nOpFileByteLen, &nNonASCII, &bErrorAtEnd ) || (bCheckRaggedEnd && bErrorAtEnd);
MCD_STR strDetectedEncoding = bIsUTF8? MCD_T("UTF-8"): MCD_T("");
if ( nNonASCII && m_strEncoding != strDetectedEncoding ) // only need to convert non-ASCII
bConvertMB = true;
m_strEncoding = strDetectedEncoding;
if ( bIsUTF8 )
x_AddResult( m_strIOResult, MCD_T("read"), m_strEncoding, MRC_MODIFY|MRC_ENCODING );
}
if ( bSuccess && bCheckRaggedEnd )
FileCheckRaggedEnd( (void*)pBuffer );
MCD_RELEASEBUFFER( strDoc, pBuffer, m_nOpFileTextLen );
if ( bConvertMB )
{
TextEncoding textencoding( m_strEncoding, MCD_2PCSZ(strDoc), m_nOpFileTextLen );
int nMBLen = textencoding.PerformConversion( NULL, MCD_ENC );
nBufferSizeForGrow = nMBLen + nMBLen/100; // extra 1%
MCD_STR strConvDoc;
pBuffer = MCD_GETBUFFER(strConvDoc,nBufferSizeForGrow);
textencoding.PerformConversion( (void*)pBuffer );
MCD_RELEASEBUFFER( strConvDoc, pBuffer, nMBLen );
strDoc = strConvDoc;
x_AddResult( m_strIOResult, MCD_T("converted_to"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nMBLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
}
if ( bAssumeUnknownIsNative )
x_AddResult( m_strIOResult, MCD_T("utf8_detection") );
}
#endif // not WCHAR
}
return bSuccess;
}
bool FilePos::FileWrite( void* pBuffer, const void* pConstBuffer /*=NULL*/ )
{
m_nOpFileByteLen = m_nOpFileTextLen * m_nFileCharUnitSize;
if ( ! pConstBuffer )
pConstBuffer = pBuffer;
unsigned short* pTempEndianBuffer = NULL;
if ( x_EndianSwapRequired(m_nDocFlags) )
{
if ( ! pBuffer )
{
pTempEndianBuffer = new unsigned short[m_nOpFileTextLen];
memcpy( pTempEndianBuffer, pConstBuffer, m_nOpFileTextLen * 2 );
pBuffer = pTempEndianBuffer;
pConstBuffer = pTempEndianBuffer;
}
x_EndianSwapUTF16( (unsigned short*)pBuffer, m_nOpFileTextLen );
x_AddResult( m_strIOResult, MCD_T("endian_swap") );
}
bool bSuccess = ( fwrite( pConstBuffer, m_nOpFileByteLen, 1, m_fp ) == 1 );
if ( pTempEndianBuffer )
delete [] pTempEndianBuffer;
if ( bSuccess )
{
m_nFileByteOffset += m_nOpFileByteLen;
x_AddResult( m_strIOResult, MCD_T("write"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, m_nOpFileTextLen );
}
else
FileErrorAddResult();
return bSuccess;
}
bool FilePos::FileWriteText( const MCD_STR& strDoc, int nWriteStrLen/*=-1*/ )
{
bool bSuccess = true;
MCD_STRCLEAR( m_strIOResult );
MCD_PCSZ pDoc = MCD_2PCSZ(strDoc);
if ( nWriteStrLen == -1 )
nWriteStrLen = MCD_STRLENGTH(strDoc);
if ( ! nWriteStrLen )
{
x_AddResult( m_strIOResult, MCD_T("write"), m_strEncoding, MRC_ENCODING|MRC_LENGTH, 0 );
return bSuccess;
}
if ( m_nDocFlags & (CMarkup::MDF_UTF16LEFILE | CMarkup::MDF_UTF16BEFILE) )
{
#if defined(MARKUP_WCHAR) // WCHAR
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
TextEncoding textencoding( MCD_T("UTF-32"), (const void*)pDoc, nWriteStrLen );
m_nOpFileTextLen = textencoding.PerformConversion( NULL, MCD_T("UTF-16") );
unsigned short* pUTF16Buffer = new unsigned short[m_nOpFileTextLen];
textencoding.PerformConversion( (void*)pUTF16Buffer );
x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_T("UTF-32"), MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
bSuccess = FileWrite( pUTF16Buffer );
delete [] pUTF16Buffer;
#else // sizeof(wchar_t) == 2
m_nOpFileTextLen = nWriteStrLen;
bSuccess = FileWrite( NULL, pDoc );
#endif
#else // not WCHAR
TextEncoding textencoding( MCD_ENC, (const void*)pDoc, nWriteStrLen );
m_nOpFileTextLen = textencoding.PerformConversion( NULL, MCD_T("UTF-16") );
unsigned short* pUTF16Buffer = new unsigned short[m_nOpFileTextLen];
textencoding.PerformConversion( (void*)pUTF16Buffer );
x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
bSuccess = FileWrite( pUTF16Buffer );
delete [] pUTF16Buffer;
#endif // not WCHAR
}
else // single or multibyte file (i.e. not UTF-16)
{
#if ! defined(MARKUP_WCHAR) // not WCHAR
if ( ! TextEncoding::CanConvert(m_strEncoding,MCD_ENC) )
{
// Same or unsupported multi-byte to multi-byte, so save directly from string
m_nOpFileTextLen = nWriteStrLen;
bSuccess = FileWrite( NULL, pDoc );
return bSuccess;
}
#endif // not WCHAR
TextEncoding textencoding( MCD_ENC, (const void*)pDoc, nWriteStrLen );
m_nOpFileTextLen = textencoding.PerformConversion( NULL, m_strEncoding );
char* pMBBuffer = new char[m_nOpFileTextLen];
textencoding.PerformConversion( (void*)pMBBuffer );
x_AddResult( m_strIOResult, MCD_T("converted_from"), MCD_ENC, MRC_ENCODING|MRC_LENGTH, nWriteStrLen );
if ( textencoding.m_nFailedChars )
x_AddResult( m_strIOResult, MCD_T("conversion_loss") );
bSuccess = FileWrite( pMBBuffer );
delete [] pMBBuffer;
}
return bSuccess;
}
bool FilePos::FileClose()
{
if ( m_fp )
{
if ( fclose(m_fp) )
FileErrorAddResult();
m_fp = NULL;
m_nDocFlags &= ~(CMarkup::MDF_WRITEFILE|CMarkup::MDF_READFILE|CMarkup::MDF_APPENDFILE);
return true;
}
return false;
}
bool FilePos::FileReadNextBuffer()
{
// If not end of file, returns amount to subtract from offsets
if ( m_nFileByteOffset < m_nFileByteLen )
{
// Prepare to put this node at beginning
MCD_STR& str = *m_pstrBuffer;
int nDocLength = MCD_STRLENGTH( str );
int nRemove = m_nReadBufferStart;
m_nReadBufferRemoved = nRemove;
// Gather
if ( m_nReadGatherStart != -1 )
{
if ( m_nReadBufferStart > m_nReadGatherStart )
{
// In case it is a large subdoc, reduce reallocs by using x_StrInsertReplace
MCD_STR strAppend = MCD_STRMID( str, m_nReadGatherStart, m_nReadBufferStart - m_nReadGatherStart );
x_StrInsertReplace( m_strReadGatherMarkup, MCD_STRLENGTH(m_strReadGatherMarkup), 0, strAppend );
}
m_nReadGatherStart = 0;
}
// Increase capacity if already at the beginning keeping more than half
int nKeepLength = nDocLength - nRemove;
int nEstimatedKeepBytes = m_nBlockSizeBasis * nKeepLength / nDocLength; // block size times fraction of doc kept
if ( nRemove == 0 || nKeepLength > nDocLength / 2 )
m_nBlockSizeBasis *= 2;
if ( nRemove )
x_StrInsertReplace( str, 0, nRemove, MCD_STR() );
MCD_STR strRead;
m_nOpFileByteLen = m_nBlockSizeBasis - nEstimatedKeepBytes;
m_nOpFileByteLen += 4 - m_nOpFileByteLen % 4;
FileReadText( strRead );
x_StrInsertReplace( str, nKeepLength, 0, strRead );
m_nReadBufferStart = 0; // next time just elongate/increase capacity
return true;
}
return false;
}
void FilePos::FileGatherStart( int nStart )
{
m_nReadGatherStart = nStart;
}
int FilePos::FileGatherEnd( MCD_STR& strMarkup )
{
int nStart = m_nReadGatherStart;
m_nReadGatherStart = -1;
strMarkup = m_strReadGatherMarkup;
MCD_STRCLEAR( m_strReadGatherMarkup );
return nStart;
}
bool FilePos::FileFlush( MCD_STR& strBuffer, int nWriteStrLen/*=-1*/, bool bFflush/*=false*/ )
{
bool bSuccess = true;
MCD_STRCLEAR( m_strIOResult );
if ( nWriteStrLen == -1 )
nWriteStrLen = MCD_STRLENGTH( strBuffer );
if ( nWriteStrLen )
{
if ( (! m_nFileByteOffset) && MCD_STRISEMPTY(m_strEncoding) && ! MCD_STRISEMPTY(strBuffer) )
{
m_strEncoding = CMarkup::GetDeclaredEncoding( strBuffer );
if ( MCD_STRISEMPTY(m_strEncoding) )
m_strEncoding = MCD_T("UTF-8");
}
bSuccess = FileWriteText( strBuffer, nWriteStrLen );
if ( bSuccess )
x_StrInsertReplace( strBuffer, 0, nWriteStrLen, MCD_STR() );
}
if ( bFflush && bSuccess )
{
if ( fflush(m_fp) )
bSuccess = FileErrorAddResult();
}
return bSuccess;
}
//////////////////////////////////////////////////////////////////////
// PathPos encapsulates parsing of the path string used in Find methods
//
struct PathPos
{
PathPos( MCD_PCSZ pszPath, bool b ) { p=pszPath; bReader=b; i=0; iPathAttribName=0; iSave=0; nPathType=0; if (!ParsePath()) nPathType=-1; };
int GetTypeAndInc() { i=-1; if (p) { if (p[0]=='/') { if (p[1]=='/') i=2; else i=1; } else if (p[0]) i=0; } nPathType=i+1; return nPathType; };
int GetNumAndInc() { int n=0; while (p[i]>='0'&&p[i]<='9') n=n*10+(int)p[i++]-(int)'0'; return n; };
MCD_PCSZ GetValAndInc() { ++i; MCD_CHAR cEnd=']'; if (p[i]=='\''||p[i]=='\"') cEnd=p[i++]; int iVal=i; IncWord(cEnd); nLen=i-iVal; if (cEnd!=']') ++i; return &p[iVal]; };
int GetValOrWordLen() { return nLen; };
MCD_CHAR GetChar() { return p[i]; };
bool IsAtPathEnd() { return ((!p[i])||(iPathAttribName&&i+2>=iPathAttribName))?true:false; };
MCD_PCSZ GetPtr() { return &p[i]; };
void SaveOffset() { iSave=i; };
void RevertOffset() { i=iSave; };
void RevertOffsetAsName() { i=iSave; nPathType=1; };
MCD_PCSZ GetWordAndInc() { int iWord=i; IncWord(); nLen=i-iWord; return &p[iWord]; };
void IncWord() { while (p[i]&&!MCD_PSZCHR(MCD_T(" =/[]"),p[i])) i+=MCD_CLEN(&p[i]); };
void IncWord( MCD_CHAR c ) { while (p[i]&&p[i]!=c) i+=MCD_CLEN(&p[i]); };
void IncChar() { ++i; };
void Inc( int n ) { i+=n; };
bool IsAnywherePath() { return nPathType == 3; };
bool IsAbsolutePath() { return nPathType == 2; };
bool IsPath() { return nPathType > 0; };
bool ValidPath() { return nPathType != -1; };
MCD_PCSZ GetPathAttribName() { if (iPathAttribName) return &p[iPathAttribName]; return NULL; };
bool AttribPredicateMatch( TokenPos& token );
private:
bool ParsePath();
int nPathType; // -1 invalid, 0 empty, 1 name, 2 absolute path, 3 anywhere path
bool bReader;
MCD_PCSZ p;
int i;
int iPathAttribName;
int iSave;
int nLen;
};
bool PathPos::ParsePath()
{
// Determine if the path seems to be in a valid format before attempting to find
if ( GetTypeAndInc() )
{
SaveOffset();
while ( 1 )
{
if ( ! GetChar() )
return false;
IncWord(); // Tag name
if ( GetChar() == '[' ) // predicate
{
IncChar(); // [
if ( GetChar() >= '1' && GetChar() <= '9' )
GetNumAndInc();
else // attrib or child tag name
{
if ( GetChar() == '@' )
{
IncChar(); // @
IncWord(); // attrib name
if ( GetChar() == '=' )
GetValAndInc();
}
else
{
if ( bReader )
return false;
IncWord();
}
}
if ( GetChar() != ']' )
return false;
IncChar(); // ]
}
// Another level of path
if ( GetChar() == '/' )
{
if ( IsAnywherePath() )
return false; // multiple levels not supported for // path
IncChar();
if ( GetChar() == '@' )
{
// FindGetData and FindSetData support paths ending in attribute
IncChar(); // @
iPathAttribName = i;
IncWord(); // attrib name
if ( GetChar() )
return false; // it should have ended with attribute name
break;
}
}
else
{
if ( GetChar() )
return false; // not a slash, so it should have ended here
break;
}
}
RevertOffset();
}
return true;
}
bool PathPos::AttribPredicateMatch( TokenPos& token )
{
// Support attribute predicate matching in regular and file read mode
// token.m_nNext must already be set to node.nStart + 1 or ELEM(i).nStart + 1
IncChar(); // @
if ( token.FindAttrib(GetPtr()) )
{
IncWord();
if ( GetChar() == '=' )
{
MCD_PCSZ pszVal = GetValAndInc();
MCD_STR strPathValue = CMarkup::UnescapeText( pszVal, GetValOrWordLen() );
MCD_STR strAttribValue = CMarkup::UnescapeText( token.GetTokenPtr(), token.Length() );
if ( strPathValue != strAttribValue )
return false;
}
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
// A map is a table of SavedPos structs
//
struct SavedPos
{
// SavedPos is an entry in the SavedPosMap hash table
SavedPos() { nSavedPosFlags=0; iPos=0; };
MCD_STR strName;
int iPos;
enum { SPM_MAIN = 1, SPM_CHILD = 2, SPM_USED = 4, SPM_LAST = 8 };
int nSavedPosFlags;
};
struct SavedPosMap
{
// SavedPosMap is only created if SavePos/RestorePos are used
SavedPosMap( int nSize ) { nMapSize=nSize; pTable = new SavedPos*[nSize]; memset(pTable,0,nSize*sizeof(SavedPos*)); };
~SavedPosMap() { if (pTable) { for (int n=0;n<nMapSize;++n) if (pTable[n]) delete[] pTable[n]; delete[] pTable; } };
SavedPos** pTable;
int nMapSize;
};
struct SavedPosMapArray
{
// SavedPosMapArray keeps pointers to SavedPosMap instances
SavedPosMapArray() { m_pMaps = NULL; };
~SavedPosMapArray() { ReleaseMaps(); };
void ReleaseMaps() { SavedPosMap**p = m_pMaps; if (p) { while (*p) delete *p++; delete[] m_pMaps; m_pMaps=NULL; } };
bool GetMap( SavedPosMap*& pMap, int nMap, int nMapSize = 7 );
void CopySavedPosMaps( SavedPosMapArray* pOtherMaps );
SavedPosMap** m_pMaps; // NULL terminated array
};
bool SavedPosMapArray::GetMap( SavedPosMap*& pMap, int nMap, int nMapSize /*=7*/ )
{
// Find or create map, returns true if map(s) created
SavedPosMap** pMapsExisting = m_pMaps;
int nMapIndex = 0;
if ( pMapsExisting )
{
// Length of array is unknown, so loop through maps
while ( nMapIndex <= nMap )
{
pMap = pMapsExisting[nMapIndex];
if ( ! pMap )
break;
if ( nMapIndex == nMap )
return false; // not created
++nMapIndex;
}
nMapIndex = 0;
}
// Create map(s)
// If you access map 1 before map 0 created, then 2 maps will be created
m_pMaps = new SavedPosMap*[nMap+2];
if ( pMapsExisting )
{
while ( pMapsExisting[nMapIndex] )
{
m_pMaps[nMapIndex] = pMapsExisting[nMapIndex];
++nMapIndex;
}
delete[] pMapsExisting;
}
while ( nMapIndex <= nMap )
{
m_pMaps[nMapIndex] = new SavedPosMap( nMapSize );
++nMapIndex;
}
m_pMaps[nMapIndex] = NULL;
pMap = m_pMaps[nMap];
return true; // map(s) created
}
void SavedPosMapArray::CopySavedPosMaps( SavedPosMapArray* pOtherMaps )
{
ReleaseMaps();
if ( pOtherMaps->m_pMaps )
{
int nMap = 0;
SavedPosMap* pMap = NULL;
while ( pOtherMaps->m_pMaps[nMap] )
{
SavedPosMap* pMapSrc = pOtherMaps->m_pMaps[nMap];
GetMap( pMap, nMap, pMapSrc->nMapSize );
for ( int nSlot=0; nSlot < pMap->nMapSize; ++nSlot )
{
SavedPos* pCopySavedPos = pMapSrc->pTable[nSlot];
if ( pCopySavedPos )
{
int nCount = 0;
while ( pCopySavedPos[nCount].nSavedPosFlags & SavedPos::SPM_USED )
{
++nCount;
if ( pCopySavedPos[nCount-1].nSavedPosFlags & SavedPos::SPM_LAST )
break;
}
if ( nCount )
{
SavedPos* pNewSavedPos = new SavedPos[nCount];
for ( int nCopy=0; nCopy<nCount; ++nCopy )
pNewSavedPos[nCopy] = pCopySavedPos[nCopy];
pNewSavedPos[nCount-1].nSavedPosFlags |= SavedPos::SPM_LAST;
pMap->pTable[nSlot] = pNewSavedPos;
}
}
}
++nMap;
}
}
}
//////////////////////////////////////////////////////////////////////
// Core parser function
//
int TokenPos::ParseNode( NodePos& node )
{
// Call this with m_nNext set to the start of the node or tag
// Upon return m_nNext points to the char after the node or tag
// m_nL and m_nR are set to name location if it is a tag with a name
// node members set to node location, strMeta used for parse error
//
// <!--...--> comment
// <!DOCTYPE ...> dtd
// <?target ...?> processing instruction
// <![CDATA[...]]> cdata section
// <NAME ...> element start tag
// </NAME ...> element end tag
//
// returns the nodetype or
// 0 for end tag
// -1 for bad node
// -2 for end of document
//
enum ParseBits
{
PD_OPENTAG = 1,
PD_BANG = 2,
PD_DASH = 4,
PD_BRACKET = 8,
PD_TEXTORWS = 16,
PD_DOCTYPE = 32,
PD_INQUOTE_S = 64,
PD_INQUOTE_D = 128,
PD_EQUALS = 256
};
int nParseFlags = 0;
MCD_PCSZ pFindEnd = NULL;
int nNodeType = -1;
int nEndLen = 0;
int nName = 0;
int nNameLen = 0;
unsigned int cDminus1 = 0, cDminus2 = 0;
#define FINDNODETYPE(e,t) { pFindEnd=e; nEndLen=(sizeof(e)-1)/sizeof(MCD_CHAR); nNodeType=t; }
#define FINDNODETYPENAME(e,t,n) { FINDNODETYPE(e,t) nName=(int)(pD-m_pDocText)+n; }
#define FINDNODEBAD(e) { pFindEnd=MCD_T(">"); nEndLen=1; x_AddResult(node.strMeta,e,NULL,0,m_nNext); nNodeType=-1; }
node.nStart = m_nNext;
node.nNodeFlags = 0;
MCD_PCSZ pD = &m_pDocText[m_nNext];
unsigned int cD;
while ( 1 )
{
cD = (unsigned int)*pD;
if ( ! cD )
{
m_nNext = (int)(pD - m_pDocText);
if ( m_pReaderFilePos ) // read file mode
{
int nRemovedAlready = m_pReaderFilePos->m_nReadBufferRemoved;
if ( m_pReaderFilePos->FileReadNextBuffer() ) // more text in file?
{
int nNodeLength = m_nNext - node.nStart;
int nRemove = m_pReaderFilePos->m_nReadBufferRemoved - nRemovedAlready;
if ( nRemove )
{
node.nStart -= nRemove;
if ( nName )
nName -= nRemove;
else if ( nNameLen )
{
m_nL -= nRemove;
m_nR -= nRemove;
}
m_nNext -= nRemove;
}
int nNewOffset = node.nStart + nNodeLength;
MCD_STR& str = *m_pReaderFilePos->m_pstrBuffer;
m_pDocText = MCD_2PCSZ( str );
pD = &m_pDocText[nNewOffset];
cD = (unsigned int)*pD; // loaded char replaces null terminator
}
}
if ( ! cD )
{
if ( m_nNext == node.nStart )
{
node.nLength = 0;
node.nNodeType = 0;
return -2; // end of document
}
if ( nNodeType != CMarkup::MNT_WHITESPACE && nNodeType != CMarkup::MNT_TEXT )
{
MCD_PCSZ pType = MCD_T("tag");
if ( (nParseFlags & PD_DOCTYPE) || nNodeType == CMarkup::MNT_DOCUMENT_TYPE )
pType = MCD_T("document_type");
else if ( nNodeType == CMarkup::MNT_ELEMENT )
pType = MCD_T("start_tag");
else if ( nNodeType == 0 )
pType = MCD_T("end_tag");
else if ( nNodeType == CMarkup::MNT_CDATA_SECTION )
pType = MCD_T("cdata_section");
else if ( nNodeType == CMarkup::MNT_PROCESSING_INSTRUCTION )
pType = MCD_T("processing_instruction");
else if ( nNodeType == CMarkup::MNT_COMMENT )
pType = MCD_T("comment");
nNodeType = -1;
x_AddResult(node.strMeta,MCD_T("unterminated_tag_syntax"),pType,MRC_TYPE,node.nStart);
}
break;
}
}
if ( nName )
{
if ( MCD_PSZCHR(MCD_T(" \t\n\r/>"),(MCD_CHAR)cD) )
{
nNameLen = (int)(pD - m_pDocText) - nName;
m_nL = nName;
m_nR = nName + nNameLen - 1;
nName = 0;
cDminus2 = 0;
cDminus1 = 0;
}
else
{
pD += MCD_CLEN( pD );
continue;
}
}
if ( pFindEnd )
{
if ( cD == '>' && ! (nParseFlags & (PD_INQUOTE_S|PD_INQUOTE_D)) )
{
m_nNext = (int)(pD - m_pDocText) + 1;
if ( nEndLen == 1 )
{
pFindEnd = NULL;
if ( nNodeType == CMarkup::MNT_ELEMENT && cDminus1 == '/' )
{
if ( (! cDminus2) || MCD_PSZCHR(MCD_T(" \t\n\r\'\""),(MCD_CHAR)cDminus2) )
node.nNodeFlags |= MNF_EMPTY;
}
}
else if ( m_nNext - 1 > nEndLen )
{
// Test for end of PI or comment
MCD_PCSZ pEnd = pD - nEndLen + 1;
MCD_PCSZ pInFindEnd = pFindEnd;
int nLen = nEndLen;
while ( --nLen && *pEnd++ == *pInFindEnd++ );
if ( nLen == 0 )
pFindEnd = NULL;
}
if ( ! pFindEnd && ! (nParseFlags & PD_DOCTYPE) )
break;
}
else if ( cD == '<' && (nNodeType == CMarkup::MNT_TEXT || nNodeType == -1) )
{
m_nNext = (int)(pD - m_pDocText);
break;
}
else if ( nNodeType & CMarkup::MNT_ELEMENT )
{
if ( (nParseFlags & (PD_INQUOTE_S|PD_INQUOTE_D)) )
{
if ( cD == '\"' && (nParseFlags&PD_INQUOTE_D) )
nParseFlags ^= PD_INQUOTE_D; // off
else if ( cD == '\'' && (nParseFlags&PD_INQUOTE_S) )
nParseFlags ^= PD_INQUOTE_S; // off
}
else // not in quotes
{
// Only set INQUOTE status when preceeded by equal sign
if ( cD == '\"' && (nParseFlags&PD_EQUALS) )
nParseFlags ^= PD_INQUOTE_D|PD_EQUALS; // D on, equals off
else if ( cD == '\'' && (nParseFlags&PD_EQUALS) )
nParseFlags ^= PD_INQUOTE_S|PD_EQUALS; // S on, equals off
else if ( cD == '=' && cDminus1 != '=' && ! (nParseFlags&PD_EQUALS) )
nParseFlags ^= PD_EQUALS; // on
else if ( (nParseFlags&PD_EQUALS) && ! MCD_PSZCHR(MCD_T(" \t\n\r"),(MCD_CHAR)cD) )
nParseFlags ^= PD_EQUALS; // off
}
cDminus2 = cDminus1;
cDminus1 = cD;
}
else if ( nNodeType & CMarkup::MNT_DOCUMENT_TYPE )
{
if ( cD == '\"' && ! (nParseFlags&PD_INQUOTE_S) )
nParseFlags ^= PD_INQUOTE_D; // toggle
else if ( cD == '\'' && ! (nParseFlags&PD_INQUOTE_D) )
nParseFlags ^= PD_INQUOTE_S; // toggle
}
}
else if ( nParseFlags )
{
if ( nParseFlags & PD_TEXTORWS )
{
if ( cD == '<' )
{
m_nNext = (int)(pD - m_pDocText);
nNodeType = CMarkup::MNT_WHITESPACE;
break;
}
else if ( ! MCD_PSZCHR(MCD_T(" \t\n\r"),(MCD_CHAR)cD) )
{
nParseFlags ^= PD_TEXTORWS;
FINDNODETYPE( MCD_T("<"), CMarkup::MNT_TEXT )
}
}
else if ( nParseFlags & PD_OPENTAG )
{
nParseFlags ^= PD_OPENTAG;
if ( cD > 0x60 || ( cD > 0x40 && cD < 0x5b ) || cD == 0x5f || cD == 0x3a )
FINDNODETYPENAME( MCD_T(">"), CMarkup::MNT_ELEMENT, 0 )
else if ( cD == '/' )
FINDNODETYPENAME( MCD_T(">"), 0, 1 )
else if ( cD == '!' )
nParseFlags |= PD_BANG;
else if ( cD == '?' )
FINDNODETYPENAME( MCD_T("?>"), CMarkup::MNT_PROCESSING_INSTRUCTION, 1 )
else
FINDNODEBAD( MCD_T("first_tag_syntax") )
}
else if ( nParseFlags & PD_BANG )
{
nParseFlags ^= PD_BANG;
if ( cD == '-' )
nParseFlags |= PD_DASH;
else if ( nParseFlags & PD_DOCTYPE )
{
if ( MCD_PSZCHR(MCD_T("EAN"),(MCD_CHAR)cD) ) // <!ELEMENT ATTLIST ENTITY NOTATION
FINDNODETYPE( MCD_T(">"), CMarkup::MNT_DOCUMENT_TYPE )
else
FINDNODEBAD( MCD_T("doctype_tag_syntax") )
}
else
{
if ( cD == '[' )
nParseFlags |= PD_BRACKET;
else if ( cD == 'D' )
nParseFlags |= PD_DOCTYPE;
else
FINDNODEBAD( MCD_T("exclamation_tag_syntax") )
}
}
else if ( nParseFlags & PD_DASH )
{
nParseFlags ^= PD_DASH;
if ( cD == '-' )
FINDNODETYPE( MCD_T("-->"), CMarkup::MNT_COMMENT )
else
FINDNODEBAD( MCD_T("comment_tag_syntax") )
}
else if ( nParseFlags & PD_BRACKET )
{
nParseFlags ^= PD_BRACKET;
if ( cD == 'C' )
FINDNODETYPE( MCD_T("]]>"), CMarkup::MNT_CDATA_SECTION )
else
FINDNODEBAD( MCD_T("cdata_section_syntax") )
}
else if ( nParseFlags & PD_DOCTYPE )
{
if ( cD == '<' )
nParseFlags |= PD_OPENTAG;
else if ( cD == '>' )
{
m_nNext = (int)(pD - m_pDocText) + 1;
nNodeType = CMarkup::MNT_DOCUMENT_TYPE;
break;
}
}
}
else if ( cD == '<' )
{
nParseFlags |= PD_OPENTAG;
}
else
{
nNodeType = CMarkup::MNT_WHITESPACE;
if ( MCD_PSZCHR(MCD_T(" \t\n\r"),(MCD_CHAR)cD) )
nParseFlags |= PD_TEXTORWS;
else
FINDNODETYPE( MCD_T("<"), CMarkup::MNT_TEXT )
}
pD += MCD_CLEN( pD );
}
node.nLength = m_nNext - node.nStart;
node.nNodeType = nNodeType;
return nNodeType;
}
//////////////////////////////////////////////////////////////////////
// CMarkup public methods
//
CMarkup::~CMarkup()
{
delete m_pSavedPosMaps;
delete m_pElemPosTree;
}
void CMarkup::operator=( const CMarkup& markup )
{
// Copying not supported during file mode because of file pointer
if ( (m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) || (markup.m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) )
return;
m_iPosParent = markup.m_iPosParent;
m_iPos = markup.m_iPos;
m_iPosChild = markup.m_iPosChild;
m_iPosFree = markup.m_iPosFree;
m_iPosDeleted = markup.m_iPosDeleted;
m_nNodeType = markup.m_nNodeType;
m_nNodeOffset = markup.m_nNodeOffset;
m_nNodeLength = markup.m_nNodeLength;
m_strDoc = markup.m_strDoc;
m_strResult = markup.m_strResult;
m_nDocFlags = markup.m_nDocFlags;
m_pElemPosTree->CopyElemPosTree( markup.m_pElemPosTree, m_iPosFree );
m_pSavedPosMaps->CopySavedPosMaps( markup.m_pSavedPosMaps );
MARKUP_SETDEBUGSTATE;
}
bool CMarkup::SetDoc( MCD_PCSZ pDoc )
{
// pDoc is markup text, not a filename!
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Set document text
if ( pDoc )
m_strDoc = pDoc;
else
{
MCD_STRCLEARSIZE( m_strDoc );
m_pElemPosTree->ReleaseElemPosTree();
}
MCD_STRCLEAR(m_strResult);
return x_ParseDoc();
}
bool CMarkup::SetDoc( const MCD_STR& strDoc )
{
// strDoc is markup text, not a filename!
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
m_strDoc = strDoc;
MCD_STRCLEAR(m_strResult);
return x_ParseDoc();
}
bool CMarkup::IsWellFormed()
{
if ( m_nDocFlags & MDF_WRITEFILE )
return true;
if ( m_nDocFlags & MDF_READFILE )
{
if ( ! (ELEM(0).nFlags & MNF_ILLFORMED) )
return true;
}
else if ( m_pElemPosTree->GetSize()
&& ! (ELEM(0).nFlags & MNF_ILLFORMED)
&& ELEM(0).iElemChild
&& ! ELEM(ELEM(0).iElemChild).iElemNext )
return true;
return false;
}
MCD_STR CMarkup::GetError() const
{
// For backwards compatibility, return a readable English string built from m_strResult
// In release 11.0 you can use GetResult and examine result in XML format
CMarkup mResult( m_strResult );
MCD_STR strError;
int nSyntaxErrors = 0;
while ( mResult.FindElem() )
{
MCD_STR strItem;
MCD_STR strID = mResult.GetTagName();
// Parse result
if ( strID == MCD_T("root_has_sibling") )
strItem = MCD_T("root element has sibling");
else if ( strID == MCD_T("no_root_element") )
strItem = MCD_T("no root element");
else if ( strID == MCD_T("lone_end_tag") )
strItem = MCD_T("lone end tag '") + mResult.GetAttrib(MCD_T("tagname")) + MCD_T("' at offset ")
+ mResult.GetAttrib(MCD_T("offset"));
else if ( strID == MCD_T("unended_start_tag") )
strItem = MCD_T("start tag '") + mResult.GetAttrib(MCD_T("tagname")) + MCD_T("' at offset ")
+ mResult.GetAttrib(MCD_T("offset")) + MCD_T(" expecting end tag at offset ") + mResult.GetAttrib(MCD_T("offset2"));
else if ( strID == MCD_T("first_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting tag name / ! or ?");
else if ( strID == MCD_T("exclamation_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting 'DOCTYPE' [ or -");
else if ( strID == MCD_T("doctype_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting markup declaration"); // ELEMENT ATTLIST ENTITY NOTATION
else if ( strID == MCD_T("comment_tag_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting - to begin comment");
else if ( strID == MCD_T("cdata_section_syntax") )
strItem = MCD_T("tag syntax error at offset ") + mResult.GetAttrib(MCD_T("offset"))
+ MCD_T(" expecting 'CDATA'");
else if ( strID == MCD_T("unterminated_tag_syntax") )
strItem = MCD_T("unterminated tag at offset ") + mResult.GetAttrib(MCD_T("offset"));
// Report only the first syntax or well-formedness error
if ( ! MCD_STRISEMPTY(strItem) )
{
++nSyntaxErrors;
if ( nSyntaxErrors > 1 )
continue;
}
// I/O results
if ( strID == MCD_T("file_error") )
strItem = mResult.GetAttrib(MCD_T("msg"));
else if ( strID == MCD_T("bom") )
strItem = MCD_T("BOM +");
else if ( strID == MCD_T("read") || strID == MCD_T("write") || strID == MCD_T("converted_to") || strID == MCD_T("converted_from") )
{
if ( strID == MCD_T("converted_to") )
strItem = MCD_T("to ");
MCD_STR strEncoding = mResult.GetAttrib( MCD_T("encoding") );
if ( ! MCD_STRISEMPTY(strEncoding) )
strItem += strEncoding + MCD_T(" ");
strItem += MCD_T("length ") + mResult.GetAttrib(MCD_T("length"));
if ( strID == MCD_T("converted_from") )
strItem += MCD_T(" to");
}
else if ( strID == MCD_T("nulls_removed") )
strItem = MCD_T("removed ") + mResult.GetAttrib(MCD_T("count")) + MCD_T(" nulls");
else if ( strID == MCD_T("conversion_loss") )
strItem = MCD_T("(chars lost in conversion!)");
else if ( strID == MCD_T("utf8_detection") )
strItem = MCD_T("(used UTF-8 detection)");
else if ( strID == MCD_T("endian_swap") )
strItem = MCD_T("endian swap");
else if ( strID == MCD_T("truncation_error") )
strItem = MCD_T("encoding ") + mResult.GetAttrib(MCD_T("encoding")) + MCD_T(" adjustment error");
// Concatenate result item to error string
if ( ! MCD_STRISEMPTY(strItem) )
{
if ( ! MCD_STRISEMPTY(strError) )
strError += MCD_T(" ");
strError += strItem;
}
}
return strError;
}
bool CMarkup::Load( MCD_CSTR_FILENAME szFileName )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
if ( ! ReadTextFile(szFileName, m_strDoc, &m_strResult, &m_nDocFlags) )
return false;
return x_ParseDoc();
}
bool CMarkup::ReadTextFile( MCD_CSTR_FILENAME szFileName, MCD_STR& strDoc, MCD_STR* pstrResult, int* pnDocFlags, MCD_STR* pstrEncoding )
{
// Static utility method to load text file into strDoc
//
FilePos file;
file.m_nDocFlags = (pnDocFlags?*pnDocFlags:0) | MDF_READFILE;
bool bSuccess = file.FileOpen( szFileName );
if ( pstrResult )
*pstrResult = file.m_strIOResult;
MCD_STRCLEAR(strDoc);
if ( bSuccess )
{
file.FileSpecifyEncoding( pstrEncoding );
file.m_nOpFileByteLen = (int)((MCD_INTFILEOFFSET)(file.m_nFileByteLen - file.m_nFileByteOffset));
bSuccess = file.FileReadText( strDoc );
file.FileClose();
if ( pstrResult )
*pstrResult += file.m_strIOResult;
if ( pnDocFlags )
*pnDocFlags = file.m_nDocFlags;
}
return bSuccess;
}
bool CMarkup::Save( MCD_CSTR_FILENAME szFileName )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
return WriteTextFile( szFileName, m_strDoc, &m_strResult, &m_nDocFlags );
}
bool CMarkup::WriteTextFile( MCD_CSTR_FILENAME szFileName, const MCD_STR& strDoc, MCD_STR* pstrResult, int* pnDocFlags, MCD_STR* pstrEncoding )
{
// Static utility method to save strDoc to text file
//
FilePos file;
file.m_nDocFlags = (pnDocFlags?*pnDocFlags:0) | MDF_WRITEFILE;
bool bSuccess = file.FileOpen( szFileName );
if ( pstrResult )
*pstrResult = file.m_strIOResult;
if ( bSuccess )
{
if ( MCD_STRISEMPTY(file.m_strEncoding) && ! MCD_STRISEMPTY(strDoc) )
{
file.m_strEncoding = GetDeclaredEncoding( strDoc );
if ( MCD_STRISEMPTY(file.m_strEncoding) )
file.m_strEncoding = MCD_T("UTF-8"); // to do: MDF_ANSIFILE
}
file.FileSpecifyEncoding( pstrEncoding );
bSuccess = file.FileWriteText( strDoc );
file.FileClose();
if ( pstrResult )
*pstrResult += file.m_strIOResult;
if ( pnDocFlags )
*pnDocFlags = file.m_nDocFlags;
}
return bSuccess;
}
bool CMarkup::FindElem( MCD_CSTR szName )
{
if ( m_nDocFlags & MDF_WRITEFILE )
return false;
if ( m_pElemPosTree->GetSize() )
{
// Change current position only if found
PathPos path( szName, false );
int iPos = x_FindElem( m_iPosParent, m_iPos, path );
if ( iPos )
{
// Assign new position
x_SetPos( ELEM(iPos).iElemParent, iPos, 0 );
return true;
}
}
return false;
}
bool CMarkup::FindChildElem( MCD_CSTR szName )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Shorthand: if no current main position, find first child under parent element
if ( ! m_iPos )
FindElem();
// Change current child position only if found
PathPos path( szName, false );
int iPosChild = x_FindElem( m_iPos, m_iPosChild, path );
if ( iPosChild )
{
// Assign new position
int iPos = ELEM(iPosChild).iElemParent;
x_SetPos( ELEM(iPos).iElemParent, iPos, iPosChild );
return true;
}
return false;
}
MCD_STR CMarkup::EscapeText( MCD_CSTR szText, int nFlags )
{
// Convert text as seen outside XML document to XML friendly
// replacing special characters with ampersand escape codes
// E.g. convert "6>7" to "6>7"
//
// < less than
// & ampersand
// > greater than
//
// and for attributes:
//
// ' apostrophe or single quote
// " double quote
//
static MCD_PCSZ apReplace[] = { MCD_T("<"),MCD_T("&"),MCD_T(">"),MCD_T("'"),MCD_T(""") };
MCD_PCSZ pFind = (nFlags&MNF_ESCAPEQUOTES)?MCD_T("<&>\'\""):MCD_T("<&>");
MCD_STR strText;
MCD_PCSZ pSource = szText;
int nDestSize = MCD_PSZLEN(pSource);
nDestSize += nDestSize / 10 + 7;
MCD_BLDRESERVE(strText,nDestSize);
MCD_CHAR cSource = *pSource;
MCD_PCSZ pFound;
int nCharLen;
while ( cSource )
{
MCD_BLDCHECK(strText,nDestSize,6);
if ( (pFound=MCD_PSZCHR(pFind,cSource)) != NULL )
{
bool bIgnoreAmpersand = false;
if ( (nFlags&MNF_WITHREFS) && *pFound == '&' )
{
// Do not replace ampersand if it is start of any entity reference
// &[#_:A-Za-zU][_:-.A-Za-z0-9U]*; where U is > 0x7f
MCD_PCSZ pCheckEntity = pSource;
++pCheckEntity;
MCD_CHAR c = *pCheckEntity;
if ( (c>='A'&&c<='Z') || (c>='a'&&c<='z')
|| c=='#' || c=='_' || c==':' || ((unsigned int)c)>0x7f )
{
while ( 1 )
{
pCheckEntity += MCD_CLEN( pCheckEntity );
c = *pCheckEntity;
if ( c == ';' )
{
int nEntityLen = (int)(pCheckEntity - pSource) + 1;
MCD_BLDAPPENDN(strText,pSource,nEntityLen);
pSource = pCheckEntity;
bIgnoreAmpersand = true;
}
else if ( (c>='A'&&c<='Z') || (c>='a'&&c<='z') || (c>='0'&&c<='9')
|| c=='_' || c==':' || c=='-' || c=='.' || ((unsigned int)c)>0x7f )
continue;
break;
}
}
}
if ( ! bIgnoreAmpersand )
{
pFound = apReplace[pFound-pFind];
MCD_BLDAPPEND(strText,pFound);
}
++pSource; // ASCII, so 1 byte
}
else
{
nCharLen = MCD_CLEN( pSource );
MCD_BLDAPPENDN(strText,pSource,nCharLen);
pSource += nCharLen;
}
cSource = *pSource;
}
MCD_BLDRELEASE(strText);
return strText;
}
// Predefined character entities
// By default UnescapeText will decode standard HTML entities as well as the 5 in XML
// To unescape only the 5 standard XML entities, use this short table instead:
// MCD_PCSZ PredefEntityTable[4] =
// { MCD_T("20060lt"),MCD_T("40034quot"),MCD_T("30038amp"),MCD_T("20062gt40039apos") };
//
// This is a precompiled ASCII hash table for speed and minimum memory requirement
// Each entry consists of a 1 digit code name length, 4 digit code point, and the code name
// Each table slot can have multiple entries, table size 130 was chosen for even distribution
//
MCD_PCSZ PredefEntityTable[130] =
{
MCD_T("60216oslash60217ugrave60248oslash60249ugrave"),
MCD_T("50937omega60221yacute58968lceil50969omega60253yacute"),
MCD_T("50916delta50206icirc50948delta50238icirc68472weierp"),MCD_T("40185sup1"),
MCD_T("68970lfloor40178sup2"),
MCD_T("50922kappa60164curren50954kappa58212mdash40179sup3"),
MCD_T("59830diams58211ndash"),MCD_T("68855otimes58969rceil"),
MCD_T("50338oelig50212ocirc50244ocirc50339oelig58482trade"),
MCD_T("50197aring50931sigma50229aring50963sigma"),
MCD_T("50180acute68971rfloor50732tilde"),MCD_T("68249lsaquo"),
MCD_T("58734infin68201thinsp"),MCD_T("50161iexcl"),
MCD_T("50920theta50219ucirc50952theta50251ucirc"),MCD_T("58254oline"),
MCD_T("58260frasl68727lowast"),MCD_T("59827clubs60191iquest68250rsaquo"),
MCD_T("58629crarr50181micro"),MCD_T("58222bdquo"),MCD_T(""),
MCD_T("58243prime60177plusmn58242prime"),MCD_T("40914beta40946beta"),MCD_T(""),
MCD_T(""),MCD_T(""),MCD_T("50171laquo50215times"),MCD_T("40710circ"),
MCD_T("49001lang"),MCD_T("58220ldquo40175macr"),
MCD_T("40182para50163pound48476real"),MCD_T(""),MCD_T("58713notin50187raquo"),
MCD_T("48773cong50223szlig50978upsih"),
MCD_T("58776asymp58801equiv49002rang58218sbquo"),
MCD_T("50222thorn48659darr48595darr40402fnof58221rdquo50254thorn"),
MCD_T("40162cent58722minus"),MCD_T("58707exist40170ordf"),MCD_T(""),
MCD_T("40921iota58709empty48660harr48596harr40953iota"),MCD_T(""),
MCD_T("40196auml40228auml48226bull40167sect48838sube"),MCD_T(""),
MCD_T("48656larr48592larr58853oplus"),MCD_T("30176deg58216lsquo40186ordm"),
MCD_T("40203euml40039apos40235euml48712isin40160nbsp"),
MCD_T("40918zeta40950zeta"),MCD_T("38743and48195emsp48719prod"),
MCD_T("30935chi38745cap30967chi48194ensp"),
MCD_T("40207iuml40239iuml48706part48869perp48658rarr48594rarr"),
MCD_T("38736ang48836nsub58217rsquo"),MCD_T(""),
MCD_T("48901sdot48657uarr48593uarr"),MCD_T("40169copy48364euro"),
MCD_T("30919eta30951eta"),MCD_T("40214ouml40246ouml48839supe"),MCD_T(""),
MCD_T(""),MCD_T("30038amp30174reg"),MCD_T("48733prop"),MCD_T(""),
MCD_T("30208eth30934phi40220uuml30240eth30966phi40252uuml"),MCD_T(""),MCD_T(""),
MCD_T(""),MCD_T("40376yuml40255yuml"),MCD_T(""),MCD_T("40034quot48204zwnj"),
MCD_T("38746cup68756there4"),MCD_T("30929rho30961rho38764sim"),
MCD_T("30932tau38834sub30964tau"),MCD_T("38747int38206lrm38207rlm"),
MCD_T("30936psi30968psi30165yen"),MCD_T(""),MCD_T("28805ge30168uml"),
MCD_T("30982piv"),MCD_T(""),MCD_T("30172not"),MCD_T(""),MCD_T("28804le"),
MCD_T("30173shy"),MCD_T("39674loz28800ne38721sum"),MCD_T(""),MCD_T(""),
MCD_T("38835sup"),MCD_T("28715ni"),MCD_T(""),MCD_T("20928pi20960pi38205zwj"),
MCD_T(""),MCD_T("60923lambda20062gt60955lambda"),MCD_T(""),MCD_T(""),
MCD_T("60199ccedil60231ccedil"),MCD_T(""),MCD_T("20060lt"),
MCD_T("20926xi28744or20958xi"),MCD_T("20924mu20956mu"),MCD_T("20925nu20957nu"),
MCD_T("68225dagger68224dagger"),MCD_T("80977thetasym"),MCD_T(""),MCD_T(""),
MCD_T(""),MCD_T("78501alefsym"),MCD_T(""),MCD_T(""),MCD_T(""),
MCD_T("60193aacute60195atilde60225aacute60227atilde"),MCD_T(""),
MCD_T("70927omicron60247divide70959omicron"),MCD_T("60192agrave60224agrave"),
MCD_T("60201eacute60233eacute60962sigmaf"),MCD_T("70917epsilon70949epsilon"),
MCD_T(""),MCD_T("60200egrave60232egrave"),MCD_T("60205iacute60237iacute"),
MCD_T(""),MCD_T(""),MCD_T("60204igrave68230hellip60236igrave"),
MCD_T("60166brvbar"),
MCD_T("60209ntilde68704forall58711nabla60241ntilde69824spades"),
MCD_T("60211oacute60213otilde60189frac1260183middot60243oacute60245otilde"),
MCD_T(""),MCD_T("50184cedil60188frac14"),
MCD_T("50198aelig50194acirc60210ograve50226acirc50230aelig60242ograve"),
MCD_T("50915gamma60190frac3450947gamma58465image58730radic"),
MCD_T("60352scaron60353scaron"),MCD_T("60218uacute69829hearts60250uacute"),
MCD_T("50913alpha50202ecirc70933upsilon50945alpha50234ecirc70965upsilon"),
MCD_T("68240permil")
};
MCD_STR CMarkup::UnescapeText( MCD_CSTR szText, int nTextLength /*=-1*/ )
{
// Convert XML friendly text to text as seen outside XML document
// ampersand escape codes replaced with special characters e.g. convert "6>7" to "6>7"
// ampersand numeric codes replaced with character e.g. convert < to <
// Conveniently the result is always the same or shorter in byte length
//
MCD_STR strText;
MCD_PCSZ pSource = szText;
if ( nTextLength == -1 )
nTextLength = MCD_PSZLEN(szText);
MCD_BLDRESERVE(strText,nTextLength);
MCD_CHAR szCodeName[10];
int nCharLen;
int nChar = 0;
while ( nChar < nTextLength )
{
if ( pSource[nChar] == '&' )
{
// Get corresponding unicode code point
int nUnicode = 0;
// Look for terminating semi-colon within 9 ASCII characters
int nCodeLen = 0;
MCD_CHAR cCodeChar = pSource[nChar+1];
while ( nCodeLen < 9 && ((unsigned int)cCodeChar) < 128 && cCodeChar != ';' )
{
if ( cCodeChar >= 'A' && cCodeChar <= 'Z') // upper case?
cCodeChar += ('a' - 'A'); // make lower case
szCodeName[nCodeLen] = cCodeChar;
++nCodeLen;
cCodeChar = pSource[nChar+1+nCodeLen];
}
if ( cCodeChar == ';' ) // found semi-colon?
{
// Decode szCodeName
szCodeName[nCodeLen] = '\0';
if ( *szCodeName == '#' ) // numeric character reference?
{
// Is it a hex number?
int nBase = 10; // decimal
int nNumberOffset = 1; // after #
if ( szCodeName[1] == 'x' )
{
nNumberOffset = 2; // after #x
nBase = 16; // hex
}
nUnicode = MCD_PSZTOL( &szCodeName[nNumberOffset], NULL, nBase );
}
else // does not start with #
{
// Look for matching code name in PredefEntityTable
MCD_PCSZ pEntry = PredefEntityTable[x_Hash(szCodeName,sizeof(PredefEntityTable)/sizeof(MCD_PCSZ))];
while ( *pEntry )
{
// e.g. entry: 40039apos means length 4, code point 0039, code name apos
int nEntryLen = (*pEntry - '0');
++pEntry;
MCD_PCSZ pCodePoint = pEntry;
pEntry += 4;
if ( nEntryLen == nCodeLen && MCD_PSZNCMP(szCodeName,pEntry,nEntryLen) == 0 )
{
// Convert digits to integer up to code name which always starts with alpha
nUnicode = MCD_PSZTOL( pCodePoint, NULL, 10 );
break;
}
pEntry += nEntryLen;
}
}
}
// If a code point found, encode it into text
if ( nUnicode )
{
MCD_CHAR szChar[5];
nCharLen = 0;
#if defined(MARKUP_WCHAR) // WCHAR
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
szChar[0] = (MCD_CHAR)nUnicode;
nCharLen = 1;
#else // sizeof(wchar_t) == 2
EncodeCharUTF16( nUnicode, (unsigned short*)szChar, nCharLen );
#endif
#elif defined(MARKUP_MBCS) // MBCS/double byte
#if defined(MARKUP_WINCONV)
int nUsedDefaultChar = 0;
wchar_t wszUTF16[2];
EncodeCharUTF16( nUnicode, (unsigned short*)wszUTF16, nCharLen );
nCharLen = WideCharToMultiByte( CP_ACP, 0, wszUTF16, nCharLen, szChar, 5, NULL, &nUsedDefaultChar );
if ( nUsedDefaultChar || nCharLen <= 0 )
nUnicode = 0;
#else // not WINCONV
wchar_t wcUnicode = (wchar_t)nUnicode;
nCharLen = wctomb( szChar, wcUnicode );
if ( nCharLen <= 0 )
nUnicode = 0;
#endif // not WINCONV
#else // not WCHAR and not MBCS/double byte
EncodeCharUTF8( nUnicode, szChar, nCharLen );
#endif // not WCHAR and not MBCS/double byte
// Increment index past ampersand semi-colon
if ( nUnicode ) // must check since MBCS case can clear it
{
MCD_BLDAPPENDN(strText,szChar,nCharLen);
nChar += nCodeLen + 2;
}
}
if ( ! nUnicode )
{
// If the code is not converted, leave it as is
MCD_BLDAPPEND1(strText,'&');
++nChar;
}
}
else // not &
{
nCharLen = MCD_CLEN(&pSource[nChar]);
MCD_BLDAPPENDN(strText,&pSource[nChar],nCharLen);
nChar += nCharLen;
}
}
MCD_BLDRELEASE(strText);
return strText;
}
bool CMarkup::DetectUTF8( const char* pText, int nTextLen, int* pnNonASCII/*=NULL*/, bool* bErrorAtEnd/*=NULL*/ )
{
// return true if ASCII or all non-ASCII byte sequences are valid UTF-8 pattern:
// ASCII 0xxxxxxx
// 2-byte 110xxxxx 10xxxxxx
// 3-byte 1110xxxx 10xxxxxx 10xxxxxx
// 4-byte 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// *pnNonASCII is set (if pnNonASCII is not NULL) to the number of non-ASCII UTF-8 sequences
// or if an invalid UTF-8 sequence is found, to 1 + the valid non-ASCII sequences up to the invalid sequence
// *bErrorAtEnd is set (if bErrorAtEnd is not NULL) to true if the UTF-8 was cut off at the end in mid valid sequence
int nUChar;
if ( pnNonASCII )
*pnNonASCII = 0;
const char* pTextEnd = pText + nTextLen;
while ( *pText && pText != pTextEnd )
{
if ( (unsigned char)(*pText) & 0x80 )
{
if ( pnNonASCII )
++(*pnNonASCII);
nUChar = DecodeCharUTF8( pText, pTextEnd );
if ( nUChar == -1 )
{
if ( bErrorAtEnd )
*bErrorAtEnd = (pTextEnd == pText)? true:false;
return false;
}
}
else
++pText;
}
if ( bErrorAtEnd )
*bErrorAtEnd = false;
return true;
}
int CMarkup::DecodeCharUTF8( const char*& pszUTF8, const char* pszUTF8End/*=NULL*/ )
{
// Return Unicode code point and increment pszUTF8 past 1-4 bytes
// pszUTF8End can be NULL if pszUTF8 is null terminated
int nUChar = (unsigned char)*pszUTF8;
++pszUTF8;
if ( nUChar & 0x80 )
{
int nExtraChars;
if ( ! (nUChar & 0x20) )
{
nExtraChars = 1;
nUChar &= 0x1f;
}
else if ( ! (nUChar & 0x10) )
{
nExtraChars = 2;
nUChar &= 0x0f;
}
else if ( ! (nUChar & 0x08) )
{
nExtraChars = 3;
nUChar &= 0x07;
}
else
return -1;
while ( nExtraChars-- )
{
if ( pszUTF8 == pszUTF8End || ! (*pszUTF8 & 0x80) )
return -1;
nUChar = nUChar<<6;
nUChar |= *pszUTF8 & 0x3f;
++pszUTF8;
}
}
return nUChar;
}
void CMarkup::EncodeCharUTF16( int nUChar, unsigned short* pwszUTF16, int& nUTF16Len )
{
// Write UTF-16 sequence to pwszUTF16 for Unicode code point nUChar and update nUTF16Len
// Be sure pwszUTF16 has room for up to 2 wide chars
if ( nUChar & ~0xffff )
{
if ( pwszUTF16 )
{
// Surrogate pair
nUChar -= 0x10000;
pwszUTF16[nUTF16Len++] = (unsigned short)(((nUChar>>10) & 0x3ff) | 0xd800); // W1
pwszUTF16[nUTF16Len++] = (unsigned short)((nUChar & 0x3ff) | 0xdc00); // W2
}
else
nUTF16Len += 2;
}
else
{
if ( pwszUTF16 )
pwszUTF16[nUTF16Len++] = (unsigned short)nUChar;
else
++nUTF16Len;
}
}
int CMarkup::DecodeCharUTF16( const unsigned short*& pwszUTF16, const unsigned short* pszUTF16End/*=NULL*/ )
{
// Return Unicode code point and increment pwszUTF16 past 1 or 2 (if surrogrates) UTF-16 code points
// pszUTF16End can be NULL if pszUTF16 is zero terminated
int nUChar = *pwszUTF16;
++pwszUTF16;
if ( (nUChar & ~0x000007ff) == 0xd800 ) // W1
{
if ( pwszUTF16 == pszUTF16End || ! (*pwszUTF16) ) // W2
return -1; // incorrect UTF-16
nUChar = (((nUChar & 0x3ff) << 10) | (*pwszUTF16 & 0x3ff)) + 0x10000;
++pwszUTF16;
}
return nUChar;
}
void CMarkup::EncodeCharUTF8( int nUChar, char* pszUTF8, int& nUTF8Len )
{
// Write UTF-8 sequence to pszUTF8 for Unicode code point nUChar and update nUTF8Len
// Be sure pszUTF8 has room for up to 4 bytes
if ( ! (nUChar & ~0x0000007f) ) // < 0x80
{
if ( pszUTF8 )
pszUTF8[nUTF8Len++] = (char)nUChar;
else
++nUTF8Len;
}
else if ( ! (nUChar & ~0x000007ff) ) // < 0x800
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x7c0)>>6)|0xc0);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 2;
}
else if ( ! (nUChar & ~0x0000ffff) ) // < 0x10000
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xf000)>>12)|0xe0);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 3;
}
else // < 0x110000
{
if ( pszUTF8 )
{
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x1c0000)>>18)|0xf0);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0x3f000)>>12)|0x80);
pszUTF8[nUTF8Len++] = (char)(((nUChar&0xfc0)>>6)|0x80);
pszUTF8[nUTF8Len++] = (char)((nUChar&0x3f)|0x80);
}
else
nUTF8Len += 4;
}
}
int CMarkup::UTF16To8( char* pszUTF8, const unsigned short* pwszUTF16, int nUTF8Count )
{
// Supports the same arguments as wcstombs
// the pwszUTF16 source must be a NULL-terminated UTF-16 string
// if pszUTF8 is NULL, the number of bytes required is returned and nUTF8Count is ignored
// otherwise pszUTF8 is filled with the result string and NULL-terminated if nUTF8Count allows
// nUTF8Count is the byte size of pszUTF8 and must be large enough for the NULL if NULL desired
// and the number of bytes (excluding NULL) is returned
//
int nUChar, nUTF8Len = 0;
while ( *pwszUTF16 )
{
// Decode UTF-16
nUChar = DecodeCharUTF16( pwszUTF16, NULL );
if ( nUChar == -1 )
nUChar = '?';
// Encode UTF-8
if ( pszUTF8 && nUTF8Len + 4 > nUTF8Count )
{
int nUTF8LenSoFar = nUTF8Len;
EncodeCharUTF8( nUChar, NULL, nUTF8Len );
if ( nUTF8Len > nUTF8Count )
return nUTF8LenSoFar;
nUTF8Len = nUTF8LenSoFar;
}
EncodeCharUTF8( nUChar, pszUTF8, nUTF8Len );
}
if ( pszUTF8 && nUTF8Len < nUTF8Count )
pszUTF8[nUTF8Len] = 0;
return nUTF8Len;
}
int CMarkup::UTF8To16( unsigned short* pwszUTF16, const char* pszUTF8, int nUTF8Count )
{
// Supports the same arguments as mbstowcs
// the pszUTF8 source must be a UTF-8 string which will be processed up to NULL-terminator or nUTF8Count
// if pwszUTF16 is NULL, the number of UTF-16 chars required is returned
// nUTF8Count is maximum UTF-8 bytes to convert and should include NULL if NULL desired in result
// if pwszUTF16 is not NULL it is filled with the result string and it must be large enough
// result will be NULL-terminated if NULL encountered in pszUTF8 before nUTF8Count
// and the number of UTF-8 bytes converted is returned
//
const char* pszPosUTF8 = pszUTF8;
const char* pszUTF8End = pszUTF8 + nUTF8Count;
int nUChar, nUTF8Len = 0, nUTF16Len = 0;
while ( pszPosUTF8 != pszUTF8End )
{
nUChar = DecodeCharUTF8( pszPosUTF8, pszUTF8End );
if ( ! nUChar )
{
if ( pwszUTF16 )
pwszUTF16[nUTF16Len] = 0;
break;
}
else if ( nUChar == -1 )
nUChar = '?';
// Encode UTF-16
EncodeCharUTF16( nUChar, pwszUTF16, nUTF16Len );
}
nUTF8Len = (int)(pszPosUTF8 - pszUTF8);
if ( ! pwszUTF16 )
return nUTF16Len;
return nUTF8Len;
}
#if ! defined(MARKUP_WCHAR) // not WCHAR
MCD_STR CMarkup::UTF8ToA( MCD_CSTR pszUTF8, int* pnFailed/*=NULL*/ )
{
// Converts from UTF-8 to locale ANSI charset
MCD_STR strANSI;
int nMBLen = (int)MCD_PSZLEN( pszUTF8 );
if ( pnFailed )
*pnFailed = 0;
if ( nMBLen )
{
TextEncoding textencoding( MCD_T("UTF-8"), (const void*)pszUTF8, nMBLen );
textencoding.m_nToCount = nMBLen;
MCD_CHAR* pANSIBuffer = MCD_GETBUFFER(strANSI,textencoding.m_nToCount);
nMBLen = textencoding.PerformConversion( (void*)pANSIBuffer );
MCD_RELEASEBUFFER(strANSI,pANSIBuffer,nMBLen);
if ( pnFailed )
*pnFailed = textencoding.m_nFailedChars;
}
return strANSI;
}
MCD_STR CMarkup::AToUTF8( MCD_CSTR pszANSI )
{
// Converts locale ANSI charset to UTF-8
MCD_STR strUTF8;
int nMBLen = (int)MCD_PSZLEN( pszANSI );
if ( nMBLen )
{
TextEncoding textencoding( MCD_T(""), (const void*)pszANSI, nMBLen );
textencoding.m_nToCount = nMBLen * 4;
MCD_CHAR* pUTF8Buffer = MCD_GETBUFFER(strUTF8,textencoding.m_nToCount);
nMBLen = textencoding.PerformConversion( (void*)pUTF8Buffer, MCD_T("UTF-8") );
MCD_RELEASEBUFFER(strUTF8,pUTF8Buffer,nMBLen);
}
return strUTF8;
}
#endif // not WCHAR
MCD_STR CMarkup::GetDeclaredEncoding( MCD_CSTR szDoc )
{
// Extract encoding attribute from XML Declaration, or HTML meta charset
MCD_STR strEncoding;
TokenPos token( szDoc, MDF_IGNORECASE );
NodePos node;
bool bHtml = false;
int nTypeFound = 0;
while ( nTypeFound >= 0 )
{
nTypeFound = token.ParseNode( node );
int nNext = token.m_nNext;
if ( nTypeFound == MNT_PROCESSING_INSTRUCTION && node.nStart == 0 )
{
token.m_nNext = node.nStart + 2; // after <?
if ( token.FindName() && token.Match(MCD_T("xml")) )
{
// e.g. <?xml version="1.0" encoding="UTF-8"?>
if ( token.FindAttrib(MCD_T("encoding")) )
strEncoding = token.GetTokenText();
break;
}
}
else if ( nTypeFound == 0 ) // end tag
{
// Check for end of HTML head
token.m_nNext = node.nStart + 2; // after </
if ( token.FindName() && token.Match(MCD_T("head")) )
break;
}
else if ( nTypeFound == MNT_ELEMENT )
{
token.m_nNext = node.nStart + 1; // after <
token.FindName();
if ( ! bHtml )
{
if ( ! token.Match(MCD_T("html")) )
break;
bHtml = true;
}
else if ( token.Match(MCD_T("meta")) )
{
// e.g. <META http-equiv=Content-Type content="text/html; charset=UTF-8">
int nAttribOffset = node.nStart + 1;
token.m_nNext = nAttribOffset;
if ( token.FindAttrib(MCD_T("http-equiv")) && token.Match(MCD_T("Content-Type")) )
{
token.m_nNext = nAttribOffset;
if ( token.FindAttrib(MCD_T("content")) )
{
int nContentEndOffset = token.m_nNext;
token.m_nNext = token.m_nL;
while ( token.m_nNext < nContentEndOffset && token.FindName() )
{
if ( token.Match(MCD_T("charset")) && token.FindName() && token.Match(MCD_T("=")) )
{
token.FindName();
strEncoding = token.GetTokenText();
break;
}
}
}
break;
}
}
}
token.m_nNext = nNext;
}
return strEncoding;
}
int CMarkup::GetEncodingCodePage( MCD_CSTR pszEncoding )
{
return x_GetEncodingCodePage( pszEncoding );
}
int CMarkup::FindNode( int nType )
{
// Change current node position only if a node is found
// If nType is 0 find any node, otherwise find node of type nType
// Return type of node or 0 if not found
// Determine where in document to start scanning for node
int nNodeOffset = m_nNodeOffset;
if ( m_nNodeType > MNT_ELEMENT )
{
// By-pass current node
nNodeOffset += m_nNodeLength;
}
else // element or no current main position
{
// Set position to begin looking for node
if ( m_iPos )
{
// After element
nNodeOffset = ELEM(m_iPos).StartAfter();
}
else if ( m_iPosParent )
{
// Immediately after start tag of parent
if ( ELEM(m_iPosParent).IsEmptyElement() )
return 0;
else
nNodeOffset = ELEM(m_iPosParent).StartContent();
}
}
// Get nodes until we find what we're looking for
int nTypeFound = 0;
int iPosNew = m_iPos;
TokenPos token( m_strDoc, m_nDocFlags );
NodePos node;
token.m_nNext = nNodeOffset;
do
{
nNodeOffset = token.m_nNext;
nTypeFound = token.ParseNode( node );
if ( nTypeFound == 0 )
{
// Check if we have reached the end of the parent element
if ( m_iPosParent && nNodeOffset == ELEM(m_iPosParent).StartContent()
+ ELEM(m_iPosParent).ContentLen() )
return 0;
nTypeFound = MNT_LONE_END_TAG; // otherwise it is a lone end tag
}
else if ( nTypeFound < 0 )
{
if ( nTypeFound == -2 ) // end of document
return 0;
// -1 is node error
nTypeFound = MNT_NODE_ERROR;
}
else if ( nTypeFound == MNT_ELEMENT )
{
if ( iPosNew )
iPosNew = ELEM(iPosNew).iElemNext;
else
iPosNew = ELEM(m_iPosParent).iElemChild;
if ( ! iPosNew )
return 0;
if ( ! nType || (nType & nTypeFound) )
{
// Found element node, move position to this element
x_SetPos( m_iPosParent, iPosNew, 0 );
return m_nNodeType;
}
token.m_nNext = ELEM(iPosNew).StartAfter();
}
}
while ( nType && ! (nType & nTypeFound) );
m_iPos = iPosNew;
m_iPosChild = 0;
m_nNodeOffset = node.nStart;
m_nNodeLength = node.nLength;
m_nNodeType = nTypeFound;
MARKUP_SETDEBUGSTATE;
return m_nNodeType;
}
bool CMarkup::RemoveNode()
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
if ( m_iPos || m_nNodeLength )
{
x_RemoveNode( m_iPosParent, m_iPos, m_nNodeType, m_nNodeOffset, m_nNodeLength );
m_iPosChild = 0;
MARKUP_SETDEBUGSTATE;
return true;
}
return false;
}
MCD_STR CMarkup::GetTagName() const
{
// Return the tag name at the current main position
MCD_STR strTagName;
// This method is primarily for elements, however
// it does return something for certain other nodes
if ( m_nNodeLength )
{
switch ( m_nNodeType )
{
case MNT_PROCESSING_INSTRUCTION:
case MNT_LONE_END_TAG:
{
// <?target or </tagname
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = m_nNodeOffset + 2;
if ( token.FindName() )
strTagName = token.GetTokenText();
}
break;
case MNT_COMMENT:
strTagName = MCD_T("#comment");
break;
case MNT_CDATA_SECTION:
strTagName = MCD_T("#cdata-section");
break;
case MNT_DOCUMENT_TYPE:
{
// <!DOCTYPE name
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = m_nNodeOffset + 2;
if ( token.FindName() && token.FindName() )
strTagName = token.GetTokenText();
}
break;
case MNT_TEXT:
case MNT_WHITESPACE:
strTagName = MCD_T("#text");
break;
}
return strTagName;
}
if ( m_iPos )
strTagName = x_GetTagName( m_iPos );
return strTagName;
}
bool CMarkup::IntoElem()
{
// Make current element the parent
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
{
x_SetPos( m_iPos, m_iPosChild, 0 );
return true;
}
return false;
}
bool CMarkup::OutOfElem()
{
// Go to parent element
if ( m_iPosParent )
{
x_SetPos( ELEM(m_iPosParent).iElemParent, m_iPosParent, m_iPos );
return true;
}
return false;
}
MCD_STR CMarkup::GetAttribName( int n ) const
{
// Return nth attribute name of main position
TokenPos token( m_strDoc, m_nDocFlags );
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
token.m_nNext = ELEM(m_iPos).nStart + 1;
else if ( m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
token.m_nNext = m_nNodeOffset + 2;
else
return MCD_T("");
if ( token.FindAttrib(NULL,n) )
return token.GetTokenText();
return MCD_T("");
}
bool CMarkup::SavePos( MCD_CSTR szPosName /*=""*/, int nMap /*=0*/ )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Save current element position in saved position map
if ( szPosName )
{
SavedPosMap* pMap;
m_pSavedPosMaps->GetMap( pMap, nMap );
SavedPos savedpos;
if ( szPosName )
savedpos.strName = szPosName;
if ( m_iPosChild )
{
savedpos.iPos = m_iPosChild;
savedpos.nSavedPosFlags |= SavedPos::SPM_CHILD;
}
else if ( m_iPos )
{
savedpos.iPos = m_iPos;
savedpos.nSavedPosFlags |= SavedPos::SPM_MAIN;
}
else
{
savedpos.iPos = m_iPosParent;
}
savedpos.nSavedPosFlags |= SavedPos::SPM_USED;
int nSlot = x_Hash( szPosName, pMap->nMapSize);
SavedPos* pSavedPos = pMap->pTable[nSlot];
int nOffset = 0;
if ( ! pSavedPos )
{
pSavedPos = new SavedPos[2];
pSavedPos[1].nSavedPosFlags = SavedPos::SPM_LAST;
pMap->pTable[nSlot] = pSavedPos;
}
else
{
while ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
{
if ( pSavedPos[nOffset].strName == (MCD_PCSZ)szPosName )
break;
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
{
int nNewSize = (nOffset + 6) * 2;
SavedPos* pNewSavedPos = new SavedPos[nNewSize];
for ( int nCopy=0; nCopy<=nOffset; ++nCopy )
pNewSavedPos[nCopy] = pSavedPos[nCopy];
pNewSavedPos[nOffset].nSavedPosFlags ^= SavedPos::SPM_LAST;
pNewSavedPos[nNewSize-1].nSavedPosFlags = SavedPos::SPM_LAST;
delete [] pSavedPos;
pSavedPos = pNewSavedPos;
pMap->pTable[nSlot] = pSavedPos;
++nOffset;
break;
}
++nOffset;
}
}
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
savedpos.nSavedPosFlags |= SavedPos::SPM_LAST;
pSavedPos[nOffset] = savedpos;
/*
// To review hash table balance, uncomment and watch strBalance
MCD_STR strBalance, strSlot;
for ( nSlot=0; nSlot < pMap->nMapSize; ++nSlot )
{
pSavedPos = pMap->pTable[nSlot];
int nCount = 0;
while ( pSavedPos && pSavedPos->nSavedPosFlags & SavedPos::SPM_USED )
{
++nCount;
if ( pSavedPos->nSavedPosFlags & SavedPos::SPM_LAST )
break;
++pSavedPos;
}
strSlot.Format( MCD_T("%d "), nCount );
strBalance += strSlot;
}
*/
return true;
}
return false;
}
bool CMarkup::RestorePos( MCD_CSTR szPosName /*=""*/, int nMap /*=0*/ )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Restore element position if found in saved position map
if ( szPosName )
{
SavedPosMap* pMap;
m_pSavedPosMaps->GetMap( pMap, nMap );
int nSlot = x_Hash( szPosName, pMap->nMapSize );
SavedPos* pSavedPos = pMap->pTable[nSlot];
if ( pSavedPos )
{
int nOffset = 0;
while ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
{
if ( pSavedPos[nOffset].strName == (MCD_PCSZ)szPosName )
{
int i = pSavedPos[nOffset].iPos;
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_CHILD )
x_SetPos( ELEM(ELEM(i).iElemParent).iElemParent, ELEM(i).iElemParent, i );
else if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_MAIN )
x_SetPos( ELEM(i).iElemParent, i, 0 );
else
x_SetPos( i, 0, 0 );
return true;
}
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
break;
++nOffset;
}
}
}
return false;
}
bool CMarkup::SetMapSize( int nSize, int nMap /*=0*/ )
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Set saved position map hash table size before using it
// Returns false if map already exists
// Some prime numbers: 53, 101, 211, 503, 1009, 2003, 10007, 20011, 50021, 100003, 200003, 500009
SavedPosMap* pNewMap;
return m_pSavedPosMaps->GetMap( pNewMap, nMap, nSize );
}
bool CMarkup::RemoveElem()
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Remove current main position element
if ( m_iPos && m_nNodeType == MNT_ELEMENT )
{
int iPos = x_RemoveElem( m_iPos );
x_SetPos( m_iPosParent, iPos, 0 );
return true;
}
return false;
}
bool CMarkup::RemoveChildElem()
{
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Remove current child position element
if ( m_iPosChild )
{
int iPosChild = x_RemoveElem( m_iPosChild );
x_SetPos( m_iPosParent, m_iPos, iPosChild );
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
// CMarkup private methods
//
void CMarkup::x_InitMarkup()
{
// Only called from CMarkup constructors
m_pFilePos = NULL;
m_pSavedPosMaps = new SavedPosMapArray;
m_pElemPosTree = new ElemPosTree;
// To always ignore case, define MARKUP_IGNORECASE
#if defined(MARKUP_IGNORECASE) // ignore case
m_nDocFlags = MDF_IGNORECASE;
#else // not ignore case
m_nDocFlags = 0;
#endif // not ignore case
}
int CMarkup::x_GetParent( int i )
{
return ELEM(i).iElemParent;
}
void CMarkup::x_SetPos( int iPosParent, int iPos, int iPosChild )
{
m_iPosParent = iPosParent;
m_iPos = iPos;
m_iPosChild = iPosChild;
m_nNodeOffset = 0;
m_nNodeLength = 0;
m_nNodeType = iPos?MNT_ELEMENT:0;
MARKUP_SETDEBUGSTATE;
}
#if defined(_DEBUG) // DEBUG
void CMarkup::x_SetDebugState()
{
// Set m_pDebugCur and m_pDebugPos to point into document
MCD_PCSZ pD = MCD_2PCSZ(m_strDoc);
// Node (non-element) position is determined differently in file mode
if ( m_nNodeLength || (m_nNodeOffset && !m_pFilePos)
|| (m_pFilePos && (!m_iPos) && (!m_iPosParent) && ! m_pFilePos->FileAtTop()) )
{
if ( ! m_nNodeLength )
m_pDebugCur = MCD_T("main position offset"); // file mode only
else
m_pDebugCur = MCD_T("main position node");
m_pDebugPos = &pD[m_nNodeOffset];
}
else
{
if ( m_iPosChild )
{
m_pDebugCur = MCD_T("child position element");
m_pDebugPos = &pD[ELEM(m_iPosChild).nStart];
}
else if ( m_iPos )
{
m_pDebugCur = MCD_T("main position element");
m_pDebugPos = &pD[ELEM(m_iPos).nStart];
}
else if ( m_iPosParent )
{
m_pDebugCur = MCD_T("parent position element");
m_pDebugPos = &pD[ELEM(m_iPosParent).nStart];
}
else
{
m_pDebugCur = MCD_T("top of document");
m_pDebugPos = pD;
}
}
}
#endif // DEBUG
int CMarkup::x_GetFreePos()
{
if ( m_iPosFree == m_pElemPosTree->GetSize() )
x_AllocElemPos();
return m_iPosFree++;
}
bool CMarkup::x_AllocElemPos( int nNewSize /*=0*/ )
{
// Resize m_aPos when the document is created or the array is filled
if ( ! nNewSize )
nNewSize = m_iPosFree + (m_iPosFree>>1); // Grow By: multiply size by 1.5
if ( m_pElemPosTree->GetSize() < nNewSize )
m_pElemPosTree->GrowElemPosTree( nNewSize );
return true;
}
bool CMarkup::x_ParseDoc()
{
// Reset indexes
ResetPos();
m_pSavedPosMaps->ReleaseMaps();
// Starting size of position array: 1 element per 64 bytes of document
// Tight fit when parsing small doc, only 0 to 2 reallocs when parsing large doc
// Start at 8 when creating new document
int nDocLen = MCD_STRLENGTH(m_strDoc);
m_iPosFree = 1;
x_AllocElemPos( nDocLen / 64 + 8 );
m_iPosDeleted = 0;
// Parse document
ELEM(0).ClearVirtualParent();
if ( nDocLen )
{
TokenPos token( m_strDoc, m_nDocFlags );
int iPos = x_ParseElem( 0, token );
ELEM(0).nLength = nDocLen;
if ( iPos > 0 )
{
ELEM(0).iElemChild = iPos;
if ( ELEM(iPos).iElemNext )
x_AddResult( m_strResult, MCD_T("root_has_sibling") );
}
else
x_AddResult( m_strResult, MCD_T("no_root_element") );
}
ResetPos();
return IsWellFormed();
}
int CMarkup::x_ParseElem( int iPosParent, TokenPos& token )
{
// This is either called by x_ParseDoc or x_AddSubDoc or x_SetElemContent
// Returns index of the first element encountered or zero if no elements
//
int iPosRoot = 0;
int iPos = iPosParent;
int iVirtualParent = iPosParent;
int nRootDepth = ELEM(iPos).Level();
int nMatchLevel;
int iPosMatch;
int iTag;
int nTypeFound;
int iPosFirst;
int iPosLast;
ElemPos* pElem;
ElemPos* pElemParent;
ElemPos* pElemChild;
// Loop through the nodes of the document
ElemStack elemstack;
NodePos node;
token.m_nNext = 0;
while ( 1 )
{
nTypeFound = token.ParseNode( node );
nMatchLevel = 0;
if ( nTypeFound == MNT_ELEMENT ) // start tag
{
iPos = x_GetFreePos();
if ( ! iPosRoot )
iPosRoot = iPos;
pElem = &ELEM(iPos);
pElem->iElemParent = iPosParent;
pElem->iElemNext = 0;
pElemParent = &ELEM(iPosParent);
if ( pElemParent->iElemChild )
{
iPosFirst = pElemParent->iElemChild;
pElemChild = &ELEM(iPosFirst);
iPosLast = pElemChild->iElemPrev;
ELEM(iPosLast).iElemNext = iPos;
pElem->iElemPrev = iPosLast;
pElemChild->iElemPrev = iPos;
pElem->nFlags = 0;
}
else
{
pElemParent->iElemChild = iPos;
pElem->iElemPrev = iPos;
pElem->nFlags = MNF_FIRST;
}
pElem->SetLevel( nRootDepth + elemstack.iTop );
pElem->iElemChild = 0;
pElem->nStart = node.nStart;
pElem->SetStartTagLen( node.nLength );
if ( node.nNodeFlags & MNF_EMPTY )
{
iPos = iPosParent;
pElem->SetEndTagLen( 0 );
pElem->nLength = node.nLength;
}
else
{
iPosParent = iPos;
elemstack.PushIntoLevel( token.GetTokenPtr(), token.Length() );
}
}
else if ( nTypeFound == 0 ) // end tag
{
iPosMatch = iPos;
iTag = elemstack.iTop;
nMatchLevel = iTag;
while ( nMatchLevel && ! token.Match(elemstack.GetRefTagPosAt(iTag--).strTagName) )
{
--nMatchLevel;
iPosMatch = ELEM(iPosMatch).iElemParent;
}
if ( nMatchLevel == 0 )
{
// Not matched at all, it is a lone end tag, a non-element node
ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
ELEM(iPos).nFlags |= MNF_ILLDATA;
x_AddResult( m_strResult, MCD_T("lone_end_tag"), token.GetTokenText(), 0, node.nStart );
}
else
{
pElem = &ELEM(iPosMatch);
pElem->nLength = node.nStart - pElem->nStart + node.nLength;
pElem->SetEndTagLen( node.nLength );
}
}
else if ( nTypeFound == -1 )
{
ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
ELEM(iPos).nFlags |= MNF_ILLDATA;
m_strResult += node.strMeta;
}
// Matched end tag, or end of document
if ( nMatchLevel || nTypeFound == -2 )
{
if ( elemstack.iTop > nMatchLevel )
ELEM(iVirtualParent).nFlags |= MNF_ILLFORMED;
// Process any non-ended elements
while ( elemstack.iTop > nMatchLevel )
{
// Element with no end tag
pElem = &ELEM(iPos);
int iPosChild = pElem->iElemChild;
iPosParent = pElem->iElemParent;
pElem->SetEndTagLen( 0 );
pElem->nFlags |= MNF_NONENDED;
pElem->iElemChild = 0;
pElem->nLength = pElem->StartTagLen();
if ( pElem->nFlags & MNF_ILLDATA )
{
pElem->nFlags ^= MNF_ILLDATA;
ELEM(iPosParent).nFlags |= MNF_ILLDATA;
}
while ( iPosChild )
{
ELEM(iPosChild).iElemParent = iPosParent;
ELEM(iPosChild).iElemPrev = iPos;
ELEM(iPos).iElemNext = iPosChild;
iPos = iPosChild;
iPosChild = ELEM(iPosChild).iElemNext;
}
// If end tag did not match, top node is end tag that did not match pElem
// if end of document, any nodes below top have no end tag
// second offset represents location where end tag was expected but end of document or other end tag was found
// end tag that was found is token.GetTokenText() but not reported in error
int nOffset2 = (nTypeFound==0)? token.m_nL-1: MCD_STRLENGTH(m_strDoc);
x_AddResult( m_strResult, MCD_T("unended_start_tag"), elemstack.Current().strTagName, 0, pElem->nStart, nOffset2 );
iPos = iPosParent;
elemstack.PopOutOfLevel();
}
if ( nTypeFound == -2 )
break;
iPosParent = ELEM(iPos).iElemParent;
iPos = iPosParent;
elemstack.PopOutOfLevel();
}
}
return iPosRoot;
}
int CMarkup::x_FindElem( int iPosParent, int iPos, PathPos& path ) const
{
// If pPath is NULL or empty, go to next sibling element
// Otherwise go to next sibling element with matching path
//
if ( ! path.ValidPath() )
return 0;
// Paths other than simple tag name are only supported in the developer version
if ( path.IsAnywherePath() || path.IsAbsolutePath() )
return 0;
if ( iPos )
iPos = ELEM(iPos).iElemNext;
else
iPos = ELEM(iPosParent).iElemChild;
// Finished here if pPath not specified
if ( ! path.IsPath() )
return iPos;
// Search
TokenPos token( m_strDoc, m_nDocFlags );
while ( iPos )
{
// Compare tag name
token.m_nNext = ELEM(iPos).nStart + 1;
token.FindName(); // Locate tag name
if ( token.Match(path.GetPtr()) )
return iPos;
iPos = ELEM(iPos).iElemNext;
}
return 0;
}
MCD_STR CMarkup::x_GetPath( int iPos ) const
{
// In file mode, iPos is an index into m_pFilePos->m_elemstack or zero
MCD_STR strPath;
while ( iPos )
{
MCD_STR strTagName;
int iPosParent;
int nCount = 0;
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
{
TagPos& tag = m_pFilePos->m_elemstack.GetRefTagPosAt(iPos);
strTagName = tag.strTagName;
nCount = tag.nCount;
iPosParent = tag.iParent;
}
else
{
strTagName = x_GetTagName( iPos );
PathPos path( MCD_2PCSZ(strTagName), false );
iPosParent = ELEM(iPos).iElemParent;
int iPosSib = 0;
while ( iPosSib != iPos )
{
path.RevertOffset();
iPosSib = x_FindElem( iPosParent, iPosSib, path );
++nCount;
}
}
if ( nCount == 1 )
strPath = MCD_T("/") + strTagName + strPath;
else
{
MCD_CHAR szPred[25];
MCD_SPRINTF( MCD_SSZ(szPred), MCD_T("[%d]"), nCount );
strPath = MCD_T("/") + strTagName + szPred + strPath;
}
iPos = iPosParent;
}
return strPath;
}
MCD_STR CMarkup::x_GetTagName( int iPos ) const
{
// Return the tag name at specified element
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = ELEM(iPos).nStart + 1;
if ( ! iPos || ! token.FindName() )
return MCD_T("");
// Return substring of document
return token.GetTokenText();
}
MCD_STR CMarkup::x_GetAttrib( int iPos, MCD_PCSZ pAttrib ) const
{
// Return the value of the attrib
TokenPos token( m_strDoc, m_nDocFlags );
if ( iPos && m_nNodeType == MNT_ELEMENT )
token.m_nNext = ELEM(iPos).nStart + 1;
else if ( iPos == m_iPos && m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
token.m_nNext = m_nNodeOffset + 2;
else
return MCD_T("");
if ( pAttrib && token.FindAttrib(pAttrib) )
return UnescapeText( token.GetTokenPtr(), token.Length() );
return MCD_T("");
}
bool CMarkup::x_SetAttrib( int iPos, MCD_PCSZ pAttrib, int nValue, int nFlags /*=0*/ )
{
// Convert integer to string
MCD_CHAR szVal[25];
MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
return x_SetAttrib( iPos, pAttrib, szVal, nFlags );
}
bool CMarkup::x_SetAttrib( int iPos, MCD_PCSZ pAttrib, MCD_PCSZ pValue, int nFlags /*=0*/ )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
int nNodeStart = 0;
if ( iPos && m_nNodeType == MNT_ELEMENT )
nNodeStart = ELEM(iPos).nStart;
else if ( iPos == m_iPos && m_nNodeLength && m_nNodeType == MNT_PROCESSING_INSTRUCTION )
nNodeStart = m_nNodeOffset;
else
return false;
// Create insertion text depending on whether attribute already exists
// Decision: for empty value leaving attrib="" instead of removing attrib
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = nNodeStart + ((m_nNodeType == MNT_ELEMENT)?1:2);
int nReplace = 0;
int nInsertAt;
MCD_STR strEscapedValue = EscapeText( pValue, MNF_ESCAPEQUOTES|nFlags );
int nEscapedValueLen = MCD_STRLENGTH( strEscapedValue );
MCD_STR strInsert;
if ( token.FindAttrib(pAttrib) )
{
// Replace value
MCD_BLDRESERVE( strInsert, nEscapedValueLen + 2 );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDAPPENDN( strInsert, MCD_2PCSZ(strEscapedValue), nEscapedValueLen );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDRELEASE( strInsert );
nInsertAt = token.m_nL - ((token.m_nTokenFlags&MNF_QUOTED)?1:0);
nReplace = token.Length() + ((token.m_nTokenFlags&MNF_QUOTED)?2:0);
}
else
{
// Insert string name value pair
int nAttribNameLen = MCD_PSZLEN( pAttrib );
MCD_BLDRESERVE( strInsert, nAttribNameLen + nEscapedValueLen + 4 );
MCD_BLDAPPEND1( strInsert, ' ' );
MCD_BLDAPPENDN( strInsert, pAttrib, nAttribNameLen );
MCD_BLDAPPEND1( strInsert, '=' );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDAPPENDN( strInsert, MCD_2PCSZ(strEscapedValue), nEscapedValueLen );
MCD_BLDAPPEND1( strInsert, x_ATTRIBQUOTE );
MCD_BLDRELEASE( strInsert );
nInsertAt = token.m_nNext;
}
int nAdjust = MCD_STRLENGTH(strInsert) - nReplace;
if ( m_nDocFlags & MDF_WRITEFILE )
{
int nNewDocLength = MCD_STRLENGTH(m_strDoc) + nAdjust;
MCD_STRCLEAR( m_strResult );
if ( nNodeStart && nNewDocLength > m_pFilePos->m_nBlockSizeBasis )
{
int nDocCapacity = MCD_STRCAPACITY(m_strDoc);
if ( nNewDocLength > nDocCapacity )
{
m_pFilePos->FileFlush( *m_pFilePos->m_pstrBuffer, nNodeStart );
m_strResult = m_pFilePos->m_strIOResult;
nInsertAt -= nNodeStart;
m_nNodeOffset = 0;
if ( m_nNodeType == MNT_ELEMENT )
ELEM(iPos).nStart = 0;
}
}
}
x_DocChange( nInsertAt, nReplace, strInsert );
if ( m_nNodeType == MNT_PROCESSING_INSTRUCTION )
{
x_AdjustForNode( m_iPosParent, m_iPos, nAdjust );
m_nNodeLength += nAdjust;
}
else
{
ELEM(iPos).AdjustStartTagLen( nAdjust );
ELEM(iPos).nLength += nAdjust;
x_Adjust( iPos, nAdjust );
}
MARKUP_SETDEBUGSTATE;
return true;
}
bool CMarkup::x_CreateNode( MCD_STR& strNode, int nNodeType, MCD_PCSZ pText )
{
// Set strNode based on nNodeType and szData
// Return false if szData would jeopardize well-formed document
//
switch ( nNodeType )
{
case MNT_PROCESSING_INSTRUCTION:
strNode = MCD_T("<?");
strNode += pText;
strNode += MCD_T("?>");
break;
case MNT_COMMENT:
strNode = MCD_T("<!--");
strNode += pText;
strNode += MCD_T("-->");
break;
case MNT_ELEMENT:
strNode = MCD_T("<");
strNode += pText;
strNode += MCD_T("/>");
break;
case MNT_TEXT:
case MNT_WHITESPACE:
strNode = EscapeText( pText );
break;
case MNT_DOCUMENT_TYPE:
strNode = pText;
break;
case MNT_LONE_END_TAG:
strNode = MCD_T("</");
strNode += pText;
strNode += MCD_T(">");
break;
case MNT_CDATA_SECTION:
if ( MCD_PSZSTR(pText,MCD_T("]]>")) != NULL )
return false;
strNode = MCD_T("<![CDATA[");
strNode += pText;
strNode += MCD_T("]]>");
break;
}
return true;
}
MCD_STR CMarkup::x_EncodeCDATASection( MCD_PCSZ szData )
{
// Split CDATA Sections if there are any end delimiters
MCD_STR strData = MCD_T("<![CDATA[");
MCD_PCSZ pszNextStart = szData;
MCD_PCSZ pszEnd = MCD_PSZSTR( szData, MCD_T("]]>") );
while ( pszEnd )
{
strData += MCD_STR( pszNextStart, (int)(pszEnd - pszNextStart) );
strData += MCD_T("]]]]><![CDATA[>");
pszNextStart = pszEnd + 3;
pszEnd = MCD_PSZSTR( pszNextStart, MCD_T("]]>") );
}
strData += pszNextStart;
strData += MCD_T("]]>");
return strData;
}
bool CMarkup::x_SetData( int iPos, int nValue )
{
// Convert integer to string
MCD_CHAR szVal[25];
MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
return x_SetData( iPos, szVal, 0 );
}
bool CMarkup::x_SetData( int iPos, MCD_PCSZ szData, int nFlags )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
MCD_STR strInsert;
if ( m_nDocFlags & MDF_WRITEFILE )
{
if ( ! iPos || m_nNodeType != 1 || ! ELEM(iPos).IsEmptyElement() )
return false; // only set data on current empty element (no other kinds of nodes)
}
if ( iPos == m_iPos && m_nNodeLength )
{
// Not an element
if ( ! x_CreateNode(strInsert, m_nNodeType, szData) )
return false;
x_DocChange( m_nNodeOffset, m_nNodeLength, strInsert );
x_AdjustForNode( m_iPosParent, iPos, MCD_STRLENGTH(strInsert) - m_nNodeLength );
m_nNodeLength = MCD_STRLENGTH(strInsert);
MARKUP_SETDEBUGSTATE;
return true;
}
// Set data in iPos element
if ( ! iPos || ELEM(iPos).iElemChild )
return false;
// Build strInsert from szData based on nFlags
if ( nFlags & MNF_WITHCDATA )
strInsert = x_EncodeCDATASection( szData );
else
strInsert = EscapeText( szData, nFlags );
// Insert
NodePos node( MNF_WITHNOLINES|MNF_REPLACE );
node.strMeta = strInsert;
int iPosBefore = 0;
int nReplace = x_InsertNew( iPos, iPosBefore, node );
int nAdjust = MCD_STRLENGTH(node.strMeta) - nReplace;
x_Adjust( iPos, nAdjust );
ELEM(iPos).nLength += nAdjust;
if ( ELEM(iPos).nFlags & MNF_ILLDATA )
ELEM(iPos).nFlags &= ~MNF_ILLDATA;
MARKUP_SETDEBUGSTATE;
return true;
}
MCD_STR CMarkup::x_GetData( int iPos )
{
if ( iPos == m_iPos && m_nNodeLength )
{
if ( m_nNodeType == MNT_COMMENT )
return MCD_STRMID( m_strDoc, m_nNodeOffset+4, m_nNodeLength-7 );
else if ( m_nNodeType == MNT_PROCESSING_INSTRUCTION )
return MCD_STRMID( m_strDoc, m_nNodeOffset+2, m_nNodeLength-4 );
else if ( m_nNodeType == MNT_CDATA_SECTION )
return MCD_STRMID( m_strDoc, m_nNodeOffset+9, m_nNodeLength-12 );
else if ( m_nNodeType == MNT_TEXT )
return UnescapeText( &(MCD_2PCSZ(m_strDoc))[m_nNodeOffset], m_nNodeLength );
else if ( m_nNodeType == MNT_LONE_END_TAG )
return MCD_STRMID( m_strDoc, m_nNodeOffset+2, m_nNodeLength-3 );
return MCD_STRMID( m_strDoc, m_nNodeOffset, m_nNodeLength );
}
// Return a string representing data between start and end tag
// Return empty string if there are any children elements
MCD_STR strData;
if ( iPos && ! ELEM(iPos).IsEmptyElement() )
{
ElemPos* pElem = &ELEM(iPos);
int nStartContent = pElem->StartContent();
if ( pElem->IsUnparsed() )
{
TokenPos token( m_strDoc, m_nDocFlags, m_pFilePos );
token.m_nNext = nStartContent;
NodePos node;
m_pFilePos->m_nReadBufferStart = pElem->nStart;
while ( 1 )
{
m_pFilePos->m_nReadBufferRemoved = 0; // will be non-zero after ParseNode if read buffer shifted
token.ParseNode( node );
if ( m_pFilePos->m_nReadBufferRemoved )
{
pElem->nStart = 0;
MARKUP_SETDEBUGSTATE;
}
if ( node.nNodeType == MNT_TEXT )
strData += UnescapeText( &token.m_pDocText[node.nStart], node.nLength );
else if ( node.nNodeType == MNT_CDATA_SECTION )
strData += MCD_STRMID( m_strDoc, node.nStart+9, node.nLength-12 );
else if ( node.nNodeType == MNT_ELEMENT )
{
MCD_STRCLEAR(strData);
break;
}
else if ( node.nNodeType == 0 )
{
if ( token.Match(m_pFilePos->m_elemstack.Current().strTagName) )
{
pElem->SetEndTagLen( node.nLength );
pElem->nLength = node.nStart + node.nLength - pElem->nStart;
m_pFilePos->m_elemstack.OutOfLevel();
}
else
{
MCD_STRCLEAR(strData);
}
break;
}
}
}
else if ( ! pElem->iElemChild )
{
// Quick scan for any tags inside content
int nContentLen = pElem->ContentLen();
MCD_PCSZ pszContent = &(MCD_2PCSZ(m_strDoc))[nStartContent];
MCD_PCSZ pszTag = MCD_PSZCHR( pszContent, '<' );
if ( pszTag && ((int)(pszTag-pszContent) < nContentLen) )
{
// Concatenate all CDATA Sections and text nodes, ignore other nodes
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nNext = nStartContent;
NodePos node;
while ( token.m_nNext < nStartContent + nContentLen )
{
token.ParseNode( node );
if ( node.nNodeType == MNT_TEXT )
strData += UnescapeText( &token.m_pDocText[node.nStart], node.nLength );
else if ( node.nNodeType == MNT_CDATA_SECTION )
strData += MCD_STRMID( m_strDoc, node.nStart+9, node.nLength-12 );
}
}
else // no tags
strData = UnescapeText( &(MCD_2PCSZ(m_strDoc))[nStartContent], nContentLen );
}
}
return strData;
}
MCD_STR CMarkup::x_GetElemContent( int iPos ) const
{
if ( ! (m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE)) )
{
ElemPos* pElem = &ELEM(iPos);
if ( iPos && pElem->ContentLen() )
return MCD_STRMID( m_strDoc, pElem->StartContent(), pElem->ContentLen() );
}
return MCD_T("");
}
bool CMarkup::x_SetElemContent( MCD_PCSZ szContent )
{
MCD_STRCLEAR(m_strResult);
if ( m_nDocFlags & (MDF_READFILE|MDF_WRITEFILE) )
return false;
// Set data in iPos element only
if ( ! m_iPos )
return false;
if ( m_nNodeLength )
return false; // not an element
// Unlink all children
int iPos = m_iPos;
int iPosChild = ELEM(iPos).iElemChild;
bool bHadChild = (iPosChild != 0);
while ( iPosChild )
iPosChild = x_ReleaseSubDoc( iPosChild );
if ( bHadChild )
x_CheckSavedPos();
// Parse content
bool bWellFormed = true;
TokenPos token( szContent, m_nDocFlags );
int iPosVirtual = x_GetFreePos();
ELEM(iPosVirtual).ClearVirtualParent();
ELEM(iPosVirtual).SetLevel( ELEM(iPos).Level() + 1 );
iPosChild = x_ParseElem( iPosVirtual, token );
if ( ELEM(iPosVirtual).nFlags & MNF_ILLFORMED )
bWellFormed = false;
ELEM(iPos).nFlags = (ELEM(iPos).nFlags & ~MNF_ILLDATA) | (ELEM(iPosVirtual).nFlags & MNF_ILLDATA);
// Prepare insert and adjust offsets
NodePos node( MNF_WITHNOLINES|MNF_REPLACE );
node.strMeta = szContent;
int iPosBefore = 0;
int nReplace = x_InsertNew( iPos, iPosBefore, node );
// Adjust and link in the inserted elements
x_Adjust( iPosChild, node.nStart );
ELEM(iPosChild).nStart += node.nStart;
ELEM(iPos).iElemChild = iPosChild;
while ( iPosChild )
{
ELEM(iPosChild).iElemParent = iPos;
iPosChild = ELEM(iPosChild).iElemNext;
}
x_ReleasePos( iPosVirtual );
int nAdjust = MCD_STRLENGTH(node.strMeta) - nReplace;
x_Adjust( iPos, nAdjust, true );
ELEM(iPos).nLength += nAdjust;
x_SetPos( m_iPosParent, m_iPos, 0 );
return bWellFormed;
}
void CMarkup::x_DocChange( int nLeft, int nReplace, const MCD_STR& strInsert )
{
x_StrInsertReplace( m_strDoc, nLeft, nReplace, strInsert );
}
void CMarkup::x_Adjust( int iPos, int nShift, bool bAfterPos /*=false*/ )
{
// Loop through affected elements and adjust indexes
// Algorithm:
// 1. update children unless bAfterPos
// (if no children or bAfterPos is true, length of iPos not affected)
// 2. update starts of next siblings and their children
// 3. go up until there is a next sibling of a parent and update starts
// 4. step 2
int iPosTop = ELEM(iPos).iElemParent;
bool bPosFirst = bAfterPos; // mark as first to skip its children
// Stop when we've reached the virtual parent (which has no tags)
while ( ELEM(iPos).StartTagLen() )
{
// Were we at containing parent of affected position?
bool bPosTop = false;
if ( iPos == iPosTop )
{
// Move iPosTop up one towards root
iPosTop = ELEM(iPos).iElemParent;
bPosTop = true;
}
// Traverse to the next update position
if ( ! bPosTop && ! bPosFirst && ELEM(iPos).iElemChild )
{
// Depth first
iPos = ELEM(iPos).iElemChild;
}
else if ( ELEM(iPos).iElemNext )
{
iPos = ELEM(iPos).iElemNext;
}
else
{
// Look for next sibling of a parent of iPos
// When going back up, parents have already been done except iPosTop
while ( 1 )
{
iPos = ELEM(iPos).iElemParent;
if ( iPos == iPosTop )
break;
if ( ELEM(iPos).iElemNext )
{
iPos = ELEM(iPos).iElemNext;
break;
}
}
}
bPosFirst = false;
// Shift indexes at iPos
if ( iPos != iPosTop )
ELEM(iPos).nStart += nShift;
else
ELEM(iPos).nLength += nShift;
}
}
int CMarkup::x_InsertNew( int iPosParent, int& iPosRel, NodePos& node )
{
// Parent empty tag or tags with no content?
bool bEmptyParentTag = iPosParent && ELEM(iPosParent).IsEmptyElement();
bool bNoContentParentTags = iPosParent && ! ELEM(iPosParent).ContentLen();
if ( iPosRel && ! node.nLength ) // current position element?
{
node.nStart = ELEM(iPosRel).nStart;
if ( ! (node.nNodeFlags & MNF_INSERT) ) // follow iPosRel
node.nStart += ELEM(iPosRel).nLength;
}
else if ( bEmptyParentTag ) // parent has no separate end tag?
{
// Split empty parent element
if ( ELEM(iPosParent).nFlags & MNF_NONENDED )
node.nStart = ELEM(iPosParent).StartContent();
else
node.nStart = ELEM(iPosParent).StartContent() - 1;
}
else if ( node.nLength || (m_nDocFlags&MDF_WRITEFILE) ) // non-element node or a file mode zero length position?
{
if ( ! (node.nNodeFlags & MNF_INSERT) )
node.nStart += node.nLength; // after node or file mode position
}
else // no current node
{
// Insert relative to parent's content
if ( node.nNodeFlags & (MNF_INSERT|MNF_REPLACE) )
node.nStart = ELEM(iPosParent).StartContent(); // beginning of parent's content
else // in front of parent's end tag
node.nStart = ELEM(iPosParent).StartAfter() - ELEM(iPosParent).EndTagLen();
}
// Go up to start of next node, unless its splitting an empty element
if ( ! (node.nNodeFlags&(MNF_WITHNOLINES|MNF_REPLACE)) && ! bEmptyParentTag )
{
TokenPos token( m_strDoc, m_nDocFlags );
node.nStart = token.WhitespaceToTag( node.nStart );
}
// Is insert relative to element position? (i.e. not other kind of node)
if ( ! node.nLength )
{
// Modify iPosRel to reflect position before
if ( iPosRel )
{
if ( node.nNodeFlags & MNF_INSERT )
{
if ( ! (ELEM(iPosRel).nFlags & MNF_FIRST) )
iPosRel = ELEM(iPosRel).iElemPrev;
else
iPosRel = 0;
}
}
else if ( ! (node.nNodeFlags & MNF_INSERT) )
{
// If parent has a child, add after last child
if ( ELEM(iPosParent).iElemChild )
iPosRel = ELEM(ELEM(iPosParent).iElemChild).iElemPrev;
}
}
// Get node length (needed for x_AddNode and x_AddSubDoc in file write mode)
node.nLength = MCD_STRLENGTH(node.strMeta);
// Prepare end of lines
if ( (! (node.nNodeFlags & MNF_WITHNOLINES)) && (bEmptyParentTag || bNoContentParentTags) )
node.nStart += x_EOLLEN;
if ( ! (node.nNodeFlags & MNF_WITHNOLINES) )
node.strMeta += x_EOL;
// Calculate insert offset and replace length
int nReplace = 0;
int nInsertAt = node.nStart;
if ( bEmptyParentTag )
{
MCD_STR strTagName = x_GetTagName( iPosParent );
MCD_STR strFormat;
if ( node.nNodeFlags & MNF_WITHNOLINES )
strFormat = MCD_T(">");
else
strFormat = MCD_T(">") x_EOL;
strFormat += node.strMeta;
strFormat += MCD_T("</");
strFormat += strTagName;
node.strMeta = strFormat;
if ( ELEM(iPosParent).nFlags & MNF_NONENDED )
{
nInsertAt = ELEM(iPosParent).StartAfter() - 1;
nReplace = 0;
ELEM(iPosParent).nFlags ^= MNF_NONENDED;
}
else
{
nInsertAt = ELEM(iPosParent).StartAfter() - 2;
nReplace = 1;
ELEM(iPosParent).AdjustStartTagLen( -1 );
}
ELEM(iPosParent).SetEndTagLen( 3 + MCD_STRLENGTH(strTagName) );
}
else
{
if ( node.nNodeFlags & MNF_REPLACE )
{
nInsertAt = ELEM(iPosParent).StartContent();
nReplace = ELEM(iPosParent).ContentLen();
}
else if ( bNoContentParentTags )
{
node.strMeta = x_EOL + node.strMeta;
nInsertAt = ELEM(iPosParent).StartContent();
}
}
if ( m_nDocFlags & MDF_WRITEFILE )
{
// Check if buffer is full
int nNewDocLength = MCD_STRLENGTH(m_strDoc) + MCD_STRLENGTH(node.strMeta) - nReplace;
int nFlushTo = node.nStart;
MCD_STRCLEAR( m_strResult );
if ( bEmptyParentTag )
nFlushTo = ELEM(iPosParent).nStart;
if ( nFlushTo && nNewDocLength > m_pFilePos->m_nBlockSizeBasis )
{
int nDocCapacity = MCD_STRCAPACITY(m_strDoc);
if ( nNewDocLength > nDocCapacity )
{
if ( bEmptyParentTag )
ELEM(iPosParent).nStart = 0;
node.nStart -= nFlushTo;
nInsertAt -= nFlushTo;
m_pFilePos->FileFlush( m_strDoc, nFlushTo );
m_strResult = m_pFilePos->m_strIOResult;
}
}
}
x_DocChange( nInsertAt, nReplace, node.strMeta );
return nReplace;
}
bool CMarkup::x_AddElem( MCD_PCSZ pName, int nValue, int nFlags )
{
// Convert integer to string
MCD_CHAR szVal[25];
MCD_SPRINTF( MCD_SSZ(szVal), MCD_T("%d"), nValue );
return x_AddElem( pName, szVal, nFlags );
}
bool CMarkup::x_AddElem( MCD_PCSZ pName, MCD_PCSZ pValue, int nFlags )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
if ( nFlags & MNF_CHILD )
{
// Adding a child element under main position
if ( ! m_iPos || (m_nDocFlags & MDF_WRITEFILE) )
return false;
}
// Cannot have data in non-ended element
if ( (nFlags&MNF_WITHNOEND) && pValue && pValue[0] )
return false;
// Node and element structures
NodePos node( nFlags );
int iPosParent = 0, iPosBefore = 0;
int iPos = x_GetFreePos();
ElemPos* pElem = &ELEM(iPos);
// Locate where to add element relative to current node
if ( nFlags & MNF_CHILD )
{
iPosParent = m_iPos;
iPosBefore = m_iPosChild;
}
else
{
iPosParent = m_iPosParent;
iPosBefore = m_iPos;
node.nStart = m_nNodeOffset;
node.nLength = m_nNodeLength;
}
// Create string for insert
// If no pValue is specified, an empty element is created
// i.e. either <NAME>value</NAME> or <NAME/>
//
int nLenName = MCD_PSZLEN(pName);
if ( ! pValue || ! pValue[0] )
{
// <NAME/> empty element
MCD_BLDRESERVE( node.strMeta, nLenName + 4 );
MCD_BLDAPPEND1( node.strMeta, '<' );
MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
if ( nFlags & MNF_WITHNOEND )
{
MCD_BLDAPPEND1( node.strMeta, '>' );
}
else
{
if ( nFlags & MNF_WITHXHTMLSPACE )
{
MCD_BLDAPPENDN( node.strMeta, MCD_T(" />"), 3 );
}
else
{
MCD_BLDAPPENDN( node.strMeta, MCD_T("/>"), 2 );
}
}
MCD_BLDRELEASE( node.strMeta );
pElem->nLength = MCD_STRLENGTH( node.strMeta );
pElem->SetStartTagLen( pElem->nLength );
pElem->SetEndTagLen( 0 );
}
else
{
// <NAME>value</NAME>
MCD_STR strValue;
if ( nFlags & MNF_WITHCDATA )
strValue = x_EncodeCDATASection( pValue );
else
strValue = EscapeText( pValue, nFlags );
int nLenValue = MCD_STRLENGTH(strValue);
pElem->nLength = nLenName * 2 + nLenValue + 5;
MCD_BLDRESERVE( node.strMeta, pElem->nLength );
MCD_BLDAPPEND1( node.strMeta, '<' );
MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
MCD_BLDAPPEND1( node.strMeta, '>' );
MCD_BLDAPPENDN( node.strMeta, MCD_2PCSZ(strValue), nLenValue );
MCD_BLDAPPENDN( node.strMeta, MCD_T("</"), 2 );
MCD_BLDAPPENDN( node.strMeta, pName, nLenName );
MCD_BLDAPPEND1( node.strMeta, '>' );
MCD_BLDRELEASE( node.strMeta );
pElem->SetEndTagLen( nLenName + 3 );
pElem->SetStartTagLen( nLenName + 2 );
}
// Insert
int nReplace = x_InsertNew( iPosParent, iPosBefore, node );
pElem->nStart = node.nStart;
pElem->iElemChild = 0;
if ( nFlags & MNF_WITHNOEND )
pElem->nFlags = MNF_NONENDED;
else
pElem->nFlags = 0;
if ( m_nDocFlags & MDF_WRITEFILE )
{
iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, iPos );
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nL = pElem->nStart + 1;
token.m_nR = pElem->nStart + nLenName;
m_pFilePos->m_elemstack.PushTagAndCount( token );
}
else
{
x_LinkElem( iPosParent, iPosBefore, iPos );
x_Adjust( iPos, MCD_STRLENGTH(node.strMeta) - nReplace );
}
if ( nFlags & MNF_CHILD )
x_SetPos( m_iPosParent, iPosParent, iPos );
else
x_SetPos( iPosParent, iPos, 0 );
return true;
}
MCD_STR CMarkup::x_GetSubDoc( int iPos )
{
if ( iPos && ! (m_nDocFlags&MDF_WRITEFILE) )
{
if ( ! (m_nDocFlags&MDF_READFILE) )
{
TokenPos token( m_strDoc, m_nDocFlags );
token.WhitespaceToTag( ELEM(iPos).StartAfter() );
token.m_nL = ELEM(iPos).nStart;
return token.GetTokenText();
}
}
return MCD_T("");
}
bool CMarkup::x_AddSubDoc( MCD_PCSZ pSubDoc, int nFlags )
{
if ( m_nDocFlags & MDF_READFILE || ((nFlags & MNF_CHILD) && (m_nDocFlags & MDF_WRITEFILE)) )
return false;
MCD_STRCLEAR(m_strResult);
NodePos node( nFlags );
int iPosParent, iPosBefore;
if ( nFlags & MNF_CHILD )
{
// Add a subdocument under main position, before or after child
if ( ! m_iPos )
return false;
iPosParent = m_iPos;
iPosBefore = m_iPosChild;
}
else
{
// Add a subdocument under parent position, before or after main
iPosParent = m_iPosParent;
iPosBefore = m_iPos;
node.nStart = m_nNodeOffset;
node.nLength = m_nNodeLength;
}
// Parse subdocument, generating indexes based on the subdocument string to be offset later
bool bWellFormed = true;
TokenPos token( pSubDoc, m_nDocFlags );
int iPosVirtual = x_GetFreePos();
ELEM(iPosVirtual).ClearVirtualParent();
ELEM(iPosVirtual).SetLevel( ELEM(iPosParent).Level() + 1 );
int iPos = x_ParseElem( iPosVirtual, token );
if ( (!iPos) || ELEM(iPosVirtual).nFlags & MNF_ILLFORMED )
bWellFormed = false;
if ( ELEM(iPosVirtual).nFlags & MNF_ILLDATA )
ELEM(iPosParent).nFlags |= MNF_ILLDATA;
// File write mode handling
bool bBypassSubDoc = false;
if ( m_nDocFlags & MDF_WRITEFILE )
{
// Current position will bypass subdoc unless well-formed single element
if ( (! bWellFormed) || ELEM(iPos).iElemChild || ELEM(iPos).iElemNext )
bBypassSubDoc = true;
// Count tag names of top level elements (usually one) in given markup
int iPosTop = iPos;
while ( iPosTop )
{
token.m_nNext = ELEM(iPosTop).nStart + 1;
token.FindName();
m_pFilePos->m_elemstack.PushTagAndCount( token );
iPosTop = ELEM(iPosTop).iElemNext;
}
}
// Extract subdocument without leading/trailing nodes
int nExtractStart = 0;
int iPosLast = ELEM(iPos).iElemPrev;
if ( bWellFormed )
{
nExtractStart = ELEM(iPos).nStart;
int nExtractLength = ELEM(iPos).nLength;
if ( iPos != iPosLast )
{
nExtractLength = ELEM(iPosLast).nStart - nExtractStart + ELEM(iPosLast).nLength;
bWellFormed = false; // treat as subdoc here, but return not well-formed
}
MCD_STRASSIGN(node.strMeta,&pSubDoc[nExtractStart],nExtractLength);
}
else
{
node.strMeta = pSubDoc;
node.nNodeFlags |= MNF_WITHNOLINES;
}
// Insert
int nReplace = x_InsertNew( iPosParent, iPosBefore, node );
// Clean up indexes
if ( m_nDocFlags & MDF_WRITEFILE )
{
if ( bBypassSubDoc )
{
// Release indexes used in parsing the subdocument
m_iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, 0 );
m_iPosFree = 1;
m_iPosDeleted = 0;
m_iPos = 0;
m_nNodeOffset = node.nStart + node.nLength;
m_nNodeLength = 0;
m_nNodeType = 0;
MARKUP_SETDEBUGSTATE;
return bWellFormed;
}
else // single element added
{
m_iPos = iPos;
ElemPos* pElem = &ELEM(iPos);
pElem->nStart = node.nStart;
m_iPosParent = x_UnlinkPrevElem( iPosParent, iPosBefore, iPos );
x_ReleasePos( iPosVirtual );
}
}
else
{
// Adjust and link in the inserted elements
// iPosVirtual will stop it from affecting rest of document
int nAdjust = node.nStart - nExtractStart;
if ( iPos && nAdjust )
{
x_Adjust( iPos, nAdjust );
ELEM(iPos).nStart += nAdjust;
}
int iPosChild = iPos;
while ( iPosChild )
{
int iPosNext = ELEM(iPosChild).iElemNext;
x_LinkElem( iPosParent, iPosBefore, iPosChild );
iPosBefore = iPosChild;
iPosChild = iPosNext;
}
x_ReleasePos( iPosVirtual );
// Now adjust remainder of document
x_Adjust( iPosLast, MCD_STRLENGTH(node.strMeta) - nReplace, true );
}
// Set position to top element of subdocument
if ( nFlags & MNF_CHILD )
x_SetPos( m_iPosParent, iPosParent, iPos );
else // Main
x_SetPos( m_iPosParent, iPos, 0 );
return bWellFormed;
}
int CMarkup::x_RemoveElem( int iPos )
{
// Determine whether any whitespace up to next tag
TokenPos token( m_strDoc, m_nDocFlags );
int nAfterEnd = token.WhitespaceToTag( ELEM(iPos).StartAfter() );
// Remove from document, adjust affected indexes, and unlink
int nLen = nAfterEnd - ELEM(iPos).nStart;
x_DocChange( ELEM(iPos).nStart, nLen, MCD_STR() );
x_Adjust( iPos, - nLen, true );
int iPosPrev = x_UnlinkElem( iPos );
x_CheckSavedPos();
return iPosPrev; // new position
}
void CMarkup::x_LinkElem( int iPosParent, int iPosBefore, int iPos )
{
// Update links between elements and initialize nFlags
ElemPos* pElem = &ELEM(iPos);
if ( m_nDocFlags & MDF_WRITEFILE )
{
// In file write mode, only keep virtual parent 0 plus one element
if ( iPosParent )
x_ReleasePos( iPosParent );
else if ( iPosBefore )
x_ReleasePos( iPosBefore );
iPosParent = 0;
ELEM(iPosParent).iElemChild = iPos;
pElem->iElemParent = iPosParent;
pElem->iElemPrev = iPos;
pElem->iElemNext = 0;
pElem->nFlags |= MNF_FIRST;
}
else
{
pElem->iElemParent = iPosParent;
if ( iPosBefore )
{
// Link in after iPosBefore
pElem->nFlags &= ~MNF_FIRST;
pElem->iElemNext = ELEM(iPosBefore).iElemNext;
if ( pElem->iElemNext )
ELEM(pElem->iElemNext).iElemPrev = iPos;
else
ELEM(ELEM(iPosParent).iElemChild).iElemPrev = iPos;
ELEM(iPosBefore).iElemNext = iPos;
pElem->iElemPrev = iPosBefore;
}
else
{
// Link in as first child
pElem->nFlags |= MNF_FIRST;
if ( ELEM(iPosParent).iElemChild )
{
pElem->iElemNext = ELEM(iPosParent).iElemChild;
pElem->iElemPrev = ELEM(pElem->iElemNext).iElemPrev;
ELEM(pElem->iElemNext).iElemPrev = iPos;
ELEM(pElem->iElemNext).nFlags ^= MNF_FIRST;
}
else
{
pElem->iElemNext = 0;
pElem->iElemPrev = iPos;
}
ELEM(iPosParent).iElemChild = iPos;
}
if ( iPosParent )
pElem->SetLevel( ELEM(iPosParent).Level() + 1 );
}
}
int CMarkup::x_UnlinkElem( int iPos )
{
// Fix links to remove element and mark as deleted
// return previous position or zero if none
ElemPos* pElem = &ELEM(iPos);
// Find previous sibling and bypass removed element
int iPosPrev = 0;
if ( pElem->nFlags & MNF_FIRST )
{
if ( pElem->iElemNext ) // set next as first child
{
ELEM(pElem->iElemParent).iElemChild = pElem->iElemNext;
ELEM(pElem->iElemNext).iElemPrev = pElem->iElemPrev;
ELEM(pElem->iElemNext).nFlags |= MNF_FIRST;
}
else // no children remaining
ELEM(pElem->iElemParent).iElemChild = 0;
}
else
{
iPosPrev = pElem->iElemPrev;
ELEM(iPosPrev).iElemNext = pElem->iElemNext;
if ( pElem->iElemNext )
ELEM(pElem->iElemNext).iElemPrev = iPosPrev;
else
ELEM(ELEM(pElem->iElemParent).iElemChild).iElemPrev = iPosPrev;
}
x_ReleaseSubDoc( iPos );
return iPosPrev;
}
int CMarkup::x_UnlinkPrevElem( int iPosParent, int iPosBefore, int iPos )
{
// In file write mode, only keep virtual parent 0 plus one element if currently at element
if ( iPosParent )
{
x_ReleasePos( iPosParent );
iPosParent = 0;
}
else if ( iPosBefore )
x_ReleasePos( iPosBefore );
ELEM(iPosParent).iElemChild = iPos;
ELEM(iPosParent).nLength = MCD_STRLENGTH(m_strDoc);
if ( iPos )
{
ElemPos* pElem = &ELEM(iPos);
pElem->iElemParent = iPosParent;
pElem->iElemPrev = iPos;
pElem->iElemNext = 0;
pElem->nFlags |= MNF_FIRST;
}
return iPosParent;
}
int CMarkup::x_ReleasePos( int iPos )
{
int iPosNext = ELEM(iPos).iElemNext;
ELEM(iPos).iElemNext = m_iPosDeleted;
ELEM(iPos).nFlags = MNF_DELETED;
m_iPosDeleted = iPos;
return iPosNext;
}
int CMarkup::x_ReleaseSubDoc( int iPos )
{
// Mark position structures as deleted by depth first traversal
// Tricky because iElemNext used in traversal is overwritten for linked list of deleted
// Return value is what iElemNext was before being overwritten
//
int iPosNext = 0, iPosTop = iPos;
while ( 1 )
{
if ( ELEM(iPos).iElemChild )
iPos = ELEM(iPos).iElemChild;
else
{
while ( 1 )
{
iPosNext = x_ReleasePos( iPos );
if ( iPosNext || iPos == iPosTop )
break;
iPos = ELEM(iPos).iElemParent;
}
if ( iPos == iPosTop )
break;
iPos = iPosNext;
}
}
return iPosNext;
}
void CMarkup::x_CheckSavedPos()
{
// Remove any saved positions now pointing to deleted elements
// Must be done as part of element removal before position reassigned
if ( m_pSavedPosMaps->m_pMaps )
{
int nMap = 0;
while ( m_pSavedPosMaps->m_pMaps[nMap] )
{
SavedPosMap* pMap = m_pSavedPosMaps->m_pMaps[nMap];
for ( int nSlot = 0; nSlot < pMap->nMapSize; ++nSlot )
{
SavedPos* pSavedPos = pMap->pTable[nSlot];
if ( pSavedPos )
{
int nOffset = 0;
int nSavedPosCount = 0;
while ( 1 )
{
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_USED )
{
int iPos = pSavedPos[nOffset].iPos;
if ( ! (ELEM(iPos).nFlags & MNF_DELETED) )
{
if ( nSavedPosCount < nOffset )
{
pSavedPos[nSavedPosCount] = pSavedPos[nOffset];
pSavedPos[nSavedPosCount].nSavedPosFlags &= ~SavedPos::SPM_LAST;
}
++nSavedPosCount;
}
}
if ( pSavedPos[nOffset].nSavedPosFlags & SavedPos::SPM_LAST )
{
while ( nSavedPosCount <= nOffset )
pSavedPos[nSavedPosCount++].nSavedPosFlags &= ~SavedPos::SPM_USED;
break;
}
++nOffset;
}
}
}
++nMap;
}
}
}
void CMarkup::x_AdjustForNode( int iPosParent, int iPos, int nShift )
{
// Adjust affected indexes
bool bAfterPos = true;
if ( ! iPos )
{
// Change happened before or at first element under iPosParent
// If there are any children of iPosParent, adjust from there
// otherwise start at parent and adjust from there
iPos = ELEM(iPosParent).iElemChild;
if ( iPos )
{
ELEM(iPos).nStart += nShift;
bAfterPos = false;
}
else
{
iPos = iPosParent;
ELEM(iPos).nLength += nShift;
}
}
x_Adjust( iPos, nShift, bAfterPos );
}
bool CMarkup::x_AddNode( int nNodeType, MCD_PCSZ pText, int nNodeFlags )
{
if ( m_nDocFlags & MDF_READFILE )
return false;
// Comments, DTDs, and processing instructions are followed by CRLF
// Other nodes are usually concerned with mixed content, so no CRLF
if ( ! (nNodeType & (MNT_PROCESSING_INSTRUCTION|MNT_COMMENT|MNT_DOCUMENT_TYPE)) )
nNodeFlags |= MNF_WITHNOLINES;
// Add node of nNodeType after current node position
NodePos node( nNodeFlags );
if ( ! x_CreateNode(node.strMeta, nNodeType, pText) )
return false;
// Insert the new node relative to current node
node.nStart = m_nNodeOffset;
node.nLength = m_nNodeLength;
node.nNodeType = nNodeType;
int iPosBefore = m_iPos;
int nReplace = x_InsertNew( m_iPosParent, iPosBefore, node );
// If its a new element, create an ElemPos
int iPos = iPosBefore;
ElemPos* pElem = NULL;
if ( nNodeType == MNT_ELEMENT )
{
// Set indexes
iPos = x_GetFreePos();
pElem = &ELEM(iPos);
pElem->nStart = node.nStart;
pElem->SetStartTagLen( node.nLength );
pElem->SetEndTagLen( 0 );
pElem->nLength = node.nLength;
node.nStart = 0;
node.nLength = 0;
pElem->iElemChild = 0;
pElem->nFlags = 0;
x_LinkElem( m_iPosParent, iPosBefore, iPos );
}
if ( m_nDocFlags & MDF_WRITEFILE )
{
m_iPosParent = x_UnlinkPrevElem( m_iPosParent, iPosBefore, iPos );
if ( nNodeType == MNT_ELEMENT )
{
TokenPos token( m_strDoc, m_nDocFlags );
token.m_nL = pElem->nStart + 1;
token.m_nR = pElem->nStart + pElem->nLength - 3;
m_pFilePos->m_elemstack.PushTagAndCount( token );
}
}
else // need to adjust element positions after iPos
x_AdjustForNode( m_iPosParent, iPos, MCD_STRLENGTH(node.strMeta) - nReplace );
// Store current position
m_iPos = iPos;
m_iPosChild = 0;
m_nNodeOffset = node.nStart;
m_nNodeLength = node.nLength;
m_nNodeType = nNodeType;
MARKUP_SETDEBUGSTATE;
return true;
}
void CMarkup::x_RemoveNode( int iPosParent, int& iPos, int& nNodeType, int& nNodeOffset, int& nNodeLength )
{
int iPosPrev = iPos;
// Removing an element?
if ( nNodeType == MNT_ELEMENT )
{
nNodeOffset = ELEM(iPos).nStart;
nNodeLength = ELEM(iPos).nLength;
iPosPrev = x_UnlinkElem( iPos );
x_CheckSavedPos();
}
// Find previous node type, offset and length
int nPrevOffset = 0;
if ( iPosPrev )
nPrevOffset = ELEM(iPosPrev).StartAfter();
else if ( iPosParent )
nPrevOffset = ELEM(iPosParent).StartContent();
TokenPos token( m_strDoc, m_nDocFlags );
NodePos node;
token.m_nNext = nPrevOffset;
int nPrevType = 0;
while ( token.m_nNext < nNodeOffset )
{
nPrevOffset = token.m_nNext;
nPrevType = token.ParseNode( node );
}
int nPrevLength = nNodeOffset - nPrevOffset;
if ( ! nPrevLength )
{
// Previous node is iPosPrev element
nPrevOffset = 0;
if ( iPosPrev )
nPrevType = MNT_ELEMENT;
}
// Remove node from document
x_DocChange( nNodeOffset, nNodeLength, MCD_STR() );
x_AdjustForNode( iPosParent, iPosPrev, - nNodeLength );
// Was removed node a lone end tag?
if ( nNodeType == MNT_LONE_END_TAG )
{
// See if we can unset parent MNF_ILLDATA flag
token.m_nNext = ELEM(iPosParent).StartContent();
int nEndOfContent = token.m_nNext + ELEM(iPosParent).ContentLen();
int iPosChild = ELEM(iPosParent).iElemChild;
while ( token.m_nNext < nEndOfContent )
{
if ( token.ParseNode(node) <= 0 )
break;
if ( node.nNodeType == MNT_ELEMENT )
{
token.m_nNext = ELEM(iPosChild).StartAfter();
iPosChild = ELEM(iPosChild).iElemNext;
}
}
if ( token.m_nNext == nEndOfContent )
ELEM(iPosParent).nFlags &= ~MNF_ILLDATA;
}
nNodeType = nPrevType;
nNodeOffset = nPrevOffset;
nNodeLength = nPrevLength;
iPos = iPosPrev;
}
| Bam4d/Neuretix | CMarkup/Markup.cpp | C++ | mit | 172,274 |
<?php
namespace Craft;
use Cake\Utility\Hash as Hash;
class VzAddressFeedMeFieldType extends BaseFeedMeFieldType
{
// Templates
// =========================================================================
public function getMappingTemplate()
{
return 'vzaddresshelper/_integrations/feedme/fields/vzaddress';
}
// Public Methods
// =========================================================================
public function prepFieldData($element, $field, $fieldData, $handle, $options)
{
// Initialize content array
$content = array();
$data = Hash::get($fieldData, 'data');
foreach ($data as $subfieldHandle => $subfieldData) {
// Set value to subfield of correct address array
$content[$subfieldHandle] = Hash::get($subfieldData, 'data');
}
// Return data
return $content;
}
} | engram-design/FeedMe-Helpers | vzaddresshelper/integrations/feedme/fields/VzAddressFeedMeFieldType.php | PHP | mit | 923 |
using AxosoftAPI.NET.Core.Interfaces;
using AxosoftAPI.NET.Models;
namespace AxosoftAPI.NET.Interfaces
{
public interface IFeatures : IItemResource<Item>
{
}
}
| Axosoft/AxosoftAPI.NET | AxosoftAPI.NET/Interfaces/IFeatures.cs | C# | mit | 167 |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# password_digest :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
require 'spec_helper'
describe User do
it "is valid with a username and confirmed password" do
user = User.new(
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
expect(user).to be_valid
end
it "is invalid without a username" do
expect(User.new(name: nil)).to have(1).errors_on(:name)
end
it "is invalid without a password" do
expect(User.new(password: nil)).to have(1).errors_on(:password)
end
it "is invalid without a password confirmation" do
expect(User.new(password_confirmation: nil)).to have(1).errors_on(:password_confirmation)
end
it "is invalid if it is a duplicate" do
user = User.new(
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
user.save
duplicate_user = User.new(
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
expect(duplicate_user).to be_invalid
end
it "always has at least one admin user remaining" do
user1 = User.create(
# create first user
name: 'Username',
password: 'Password',
password_confirmation: 'Password')
# create second user
user2 = User.create(
name: 'Username2',
password: 'Password2',
password_confirmation: 'Password2')
user1.save
user2.save
user1.destroy
expect{ user2.destroy }.to raise_error
end
end
| trackingtrain/spoonfeeder | spec/models/user_spec.rb | Ruby | mit | 1,692 |
using System;
using System.Media;
namespace AnimalHierarchy
{
class Kitten : Cat
{
public Kitten()
{
}
public Kitten(int age, string name)
: base(age,name)
{
this.Sex = "Female";
}
public override void ProduceSound()
{
SoundPlayer Sound = new SoundPlayer(@"../../Files/cat_kitten.wav");
Sound.PlaySync();
}
}
}
| siderisltd/Telerik-Academy | All Courses Homeworks/OOP/4. PrinciplesOne - OOP/AnimalHierarchy/Kitten.cs | C# | mit | 450 |
package com.tyrfing.games.tyrlib3.util;
public interface IErrorHandler {
public void onError();
}
| TyrfingX/TyrLib | com.tyrfing.games.tyrlib3/src/com/tyrfing/games/tyrlib3/util/IErrorHandler.java | Java | mit | 105 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06. RemoveNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. RemoveNumbers")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("21ba0d6d-2b60-47d5-8cd2-04f04492d771")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| niki-funky/Telerik_Academy | Programming/Data Structures and Algorithms/01. Algo/06. RemoveNumbers/Properties/AssemblyInfo.cs | C# | mit | 1,410 |
package com.dpaulenk.webproxy.common;
import com.dpaulenk.webproxy.inbound.InboundHandlerState;
import com.dpaulenk.webproxy.utils.ChannelUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpObject;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
public abstract class AbstractProxyHandler<R extends HttpMessage, S> extends SimpleChannelInboundHandler<Object> {
protected volatile ChannelHandlerContext ctx;
protected volatile Channel channel;
protected S currentState;
protected boolean tunneling = false;
public S getCurrentState() {
return currentState;
}
public void setCurrentState(S currentState) {
this.currentState = currentState;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpObject) {
channelReadHttpObject(ctx, (HttpObject) msg);
} else {
channelReadBytes(ctx, (ByteBuf) msg);
}
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
this.channel = ctx.channel();
super.channelRegistered(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
disconnect();
}
protected abstract void channelReadBytes(ChannelHandlerContext ctx, ByteBuf msg);
protected abstract void channelReadHttpObject(ChannelHandlerContext ctx, HttpObject msg);
public ChannelFuture writeToChannel(Object msg) {
ReferenceCountUtil.retain(msg);
return channel.writeAndFlush(msg);
}
public void disconnect() {
if (channel != null) {
ChannelUtils.closeOnFlush(channel);
}
}
public void stopReading() {
channel.config().setAutoRead(false);
}
public void startReading() {
channel.config().setAutoRead(true);
}
}
| Fantast/simple-web-proxy-server | src/main/java/com/dpaulenk/webproxy/common/AbstractProxyHandler.java | Java | mit | 2,222 |
package com.parikls.movieland.web.dao;
import com.parikls.movieland.web.controller.dto.movie.MovieSearchRequestDTO;
import com.parikls.movieland.web.dao.entity.Movie;
import com.parikls.movieland.web.dao.rowmapper.MovieRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class MovieDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private QueryGenerator queryGenerator;
private RowMapper<Movie> mapper = new MovieRowMapper();
private static final String QUERY_BY_ID = "SELECT * FROM movieland.movie m WHERE id=?";
private static final String QUERY_GENRES_BY_MOVIE_ID = "SELECT genre_id FROM movieland.movie_to_genre where movie_id = ?";
private static final String QUERY_COUNTRIES_BY_MOVIE_ID = "SELECT country_id FROM movieland.movie_to_country where movie_id = ?";
public List<Movie> queryAll(String ratingOrder, String priceOrder, int limitFrom, int limitTo){
return queryAll(queryGenerator.movieSorting(ratingOrder, priceOrder, limitFrom, limitTo));
}
public List<Movie> queryAll(MovieSearchRequestDTO searchRequestDTO){
return queryAll(queryGenerator.movieSearch(searchRequestDTO));
}
public List<Movie> queryAll(String query) {
return jdbcTemplate.query(query, mapper);
}
public Movie queryById(Long id) {
return jdbcTemplate.queryForObject(QUERY_BY_ID, mapper, id);
}
public List<Long> queryGenresByMovieId(Long movieID){
return jdbcTemplate.queryForList(QUERY_GENRES_BY_MOVIE_ID, Long.class, movieID);
}
public List<Long> queryCountryByMovieId(Long movieID){
return jdbcTemplate.queryForList(QUERY_COUNTRIES_BY_MOVIE_ID, Long.class, movieID);
}
}
| parikls/movieland | src/main/java/com/parikls/movieland/web/dao/MovieDAO.java | Java | mit | 1,925 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'http://localhost/hijabaisyahshop/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| http://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = 'joker';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| edisetiawan/hijabaisyahshop | application/config/config.php | PHP | mit | 18,152 |
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$ci =& get_instance();
require_once __DIR__ . '/Validations/Site_validation.php';
/*$config = [
// Users
'user' => [
[
'field' => 'company',
'label' => 'lang:company',
'rules' => 'trim|required'
],
[
'field' => 'first_name',
'label' => 'lang:first_name',
'rules' => 'trim|required'
],
[
'field' => 'last_name',
'label' => 'lang:last_name',
'rules' => 'trim'
],
[
'field' => 'username',
'label' => 'lang:username',
'rules' => 'trim'
],
[
'field' => 'email',
'label' => 'lang:email',
'rules' => 'trim|required|valid_email|is_unique[users.email.'.$ci->uri->segment(4).']'
],
[
'field' => 'password',
'label' => 'lang:password',
'rules' => ($ci->router->fetch_method() == 'create') ? 'trim|required|min_length[6]|max_length[20]' : 'trim|min_length[6]|max_length[20]'
],
[
'field' => 'confirm_password',
'label' => 'lang:confirm_password',
'rules' => 'trim|matches[password]'
]
],
];*/
//require_once __DIR__ . '/Validations/Group_validation.php';
/*$config = [
'site/edit' => [
[
'field' => 'short_name',
'label' => 'Short Name',
'rules' => 'trim|required'
],
[
'field' => 'full_name',
'label' => 'Full Name',
'rules' => 'trim|required'
],
[
'field' => 'logo',
'label' => 'Logo',
'rules' => 'trim'
],
[
'field' => 'website',
'label' => 'Website',
'rules' => 'trim|required|valid_url'
],
[
'field' => 'contact_email',
'label' => 'Contact Email',
'rules' => 'trim|required|valid_email'
]
]
];*/ | normeno/codeigniter-base | application/modules/admin/config/form_validation.php | PHP | mit | 2,111 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 17006 : 17007;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop High5coin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "High5coin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "setmininput", &setmininput, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: high5coin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: high5coin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: high5coin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use high5coind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=high5coinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"High5coin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| high5coin/high5coin | src/bitcoinrpc.cpp | C++ | mit | 48,577 |
/**
* This software is released as part of the Pumpernickel project.
*
* All com.pump resources in the Pumpernickel project are distributed under the
* MIT License:
* https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt
*
* More information about the Pumpernickel project is available here:
* https://mickleness.github.io/pumpernickel/
*/
package com.pump.io.location;
public interface SearchResults {
/** This may return null. */
public IOLocation getSearchDirectory();
/** Return the text the user is searching by. */
public String getSearchText();
} | mickleness/pumpernickel | src/main/java/com/pump/io/location/SearchResults.java | Java | mit | 594 |
var Quad = Class.create(Renderable, {
initialize: function($super, width, height, position) {
this.width = width;
this.height = height;
$super();
if (position) this.orientation.setPosition(position);
},
setWidth: function(width) { this.setSize(width, this.height); },
setHeight: function(height) { this.setSize(this.width, height); },
setSize: function(width, height) {
this.width = width;
this.height = height;
this.rebuildAll();
},
init: function(vertices, colors, textureCoords) {
this.draw_mode = GL_TRIANGLE_STRIP;
var width = this.width, height = this.height;
vertices.push(-width/2, -height/2, 0);
vertices.push(-width/2, height/2, 0);
vertices.push( width/2, -height/2, 0);
vertices.push( width/2, height/2, 0);
textureCoords.push(0, 1);
textureCoords.push(0, 0);
textureCoords.push(1, 1);
textureCoords.push(1, 0);
colors.push(1,1,1,1);
colors.push(1,1,1,1);
colors.push(1,1,1,1);
colors.push(1,1,1,1);
}
});
| sinisterchipmunk/rails-webgl | public/javascripts/objects/quad.js | JavaScript | mit | 1,039 |
<?php
/* EverFailMainBundle:Vendor:edit.html.twig */
class __TwigTemplate_a12efb1d848d1c6d16be064b9c9d634d8c4a329fc5fa3d7cb6d00bf19fafeb3b extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("::base.html.twig");
$this->blocks = array(
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "::base.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_body($context, array $blocks = array())
{
// line 4
echo "<h1>Vendor edit</h1>
";
// line 6
echo $this->env->getExtension('form')->renderer->renderBlock($this->getContext($context, "edit_form"), 'form');
echo "
<ul class=\"record_actions\">
<li>
<a href=\"";
// line 10
echo $this->env->getExtension('routing')->getPath("vendor");
echo "\">
Back to the list
</a>
</li>
<li>";
// line 14
echo $this->env->getExtension('form')->renderer->renderBlock($this->getContext($context, "delete_form"), 'form');
echo "</li>
</ul>
";
}
public function getTemplateName()
{
return "EverFailMainBundle:Vendor:edit.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 49 => 14, 42 => 10, 35 => 6, 31 => 4, 28 => 3,);
}
}
| Bhathiya90/EverfailRepo | app/cache/dev/twig/a1/2e/fb1d848d1c6d16be064b9c9d634d8c4a329fc5fa3d7cb6d00bf19fafeb3b.php | PHP | mit | 1,732 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dbFontAwesome.Test
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmExample());
}
}
}
| diegobittencourt/dbFontAwesome | dbFontAwesome.Test/Program.cs | C# | mit | 524 |
/*
* SpriteContainer
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// namespace:
//this.createjs = this.createjs||{};
(function() {
"use strict";
/**
* A SpriteContainer is a nestable display list that enables aggressively optimized rendering of bitmap content.
* In order to accomplish these optimizations, SpriteContainer enforces a few restrictions on its content.
*
* Restrictions:
* - only Sprite, SpriteContainer, BitmapText and DOMElement are allowed to be added as children.
* - a spriteSheet MUST be either be passed into the constructor or defined on the first child added.
* - all children (with the exception of DOMElement) MUST use the same spriteSheet.
*
* <h4>Example</h4>
*
* var data = {
* images: ["sprites.jpg"],
* frames: {width:50, height:50},
* animations: {run:[0,4], jump:[5,8,"run"]}
* };
* var spriteSheet = new createjs.SpriteSheet(data);
* var container = new createjs.SpriteContainer(spriteSheet);
* container.addChild(spriteInstance, spriteInstance2);
* container.x = 100;
*
* <strong>Note:</strong> SpriteContainer is not included in the minified version of EaselJS.
*
* @class SpriteContainer
* @extends Container
* @constructor
* @param {SpriteSheet} [spriteSheet] The spriteSheet to use for this SpriteContainer and its children.
**/
function SpriteContainer(spriteSheet) {
this.Container_constructor();
// public properties:
/**
* The SpriteSheet that this container enforces use of.
* @property spriteSheet
* @type {SpriteSheet}
* @readonly
**/
this.spriteSheet = spriteSheet;
}
var p = createjs.extend(SpriteContainer, createjs.Container);
/**
* <strong>REMOVED</strong>. Removed in favor of using `MySuperClass_constructor`.
* See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}}
* for details.
*
* There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance.
*
* @method initialize
* @protected
* @deprecated
*/
// p.initialize = function() {}; // searchable for devs wondering where it is.
// public methods:
/**
* Adds a child to the top of the display list.
* Only children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement are allowed.
* The child must have the same spritesheet as this container (unless it's a DOMElement).
* If a spritesheet hasn't been defined, this container uses this child's spritesheet.
*
* <h4>Example</h4>
* container.addChild(bitmapInstance);
*
* You can also add multiple children at once:
*
* container.addChild(bitmapInstance, shapeInstance, textInstance);
*
* @method addChild
* @param {DisplayObject} child The display object to add.
* @return {DisplayObject} The child that was added, or the last child if multiple children were added.
**/
p.addChild = function(child) {
if (child == null) { return child; }
if (arguments.length > 1) {
return this.addChildAt.apply(this, Array.prototype.slice.call(arguments).concat([this.children.length]));
} else {
return this.addChildAt(child, this.children.length);
}
};
/**
* Adds a child to the display list at the specified index, bumping children at equal or greater indexes up one, and
* setting its parent to this Container.
* Only children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement are allowed.
* The child must have the same spritesheet as this container (unless it's a DOMElement).
* If a spritesheet hasn't been defined, this container uses this child's spritesheet.
*
* <h4>Example</h4>
* addChildAt(child1, index);
*
* You can also add multiple children, such as:
*
* addChildAt(child1, child2, ..., index);
*
* The index must be between 0 and numChildren. For example, to add myShape under otherShape in the display list,
* you could use:
*
* container.addChildAt(myShape, container.getChildIndex(otherShape));
*
* This would also bump otherShape's index up by one. Fails silently if the index is out of range.
*
* @method addChildAt
* @param {DisplayObject} child The display object to add.
* @param {Number} index The index to add the child at.
* @return {DisplayObject} Returns the last child that was added, or the last child if multiple children were added.
**/
p.addChildAt = function(child, index) {
var l = arguments.length;
var indx = arguments[l-1]; // can't use the same name as the index param or it replaces arguments[1]
if (indx < 0 || indx > this.children.length) { return arguments[l-2]; }
if (l > 2) {
for (var i=0; i<l-1; i++) { this.addChildAt(arguments[i], indx+i); }
return arguments[l-2];
}
if (child._spritestage_compatibility >= 1) {
// The child is compatible with SpriteStage/SpriteContainer.
} else {
console && console.log("Error: You can only add children of type SpriteContainer, Sprite, BitmapText, or DOMElement [" + child.toString() + "]");
return child;
}
if (child._spritestage_compatibility <= 4) {
var spriteSheet = child.spriteSheet;
if ((!spriteSheet || !spriteSheet._images || spriteSheet._images.length > 1) || (this.spriteSheet && this.spriteSheet !== spriteSheet)) {
console && console.log("Error: A child's spriteSheet must be equal to its parent spriteSheet and only use one image. [" + child.toString() + "]");
return child;
}
this.spriteSheet = spriteSheet;
}
if (child.parent) { child.parent.removeChild(child); }
child.parent = this;
this.children.splice(index, 0, child);
return child;
};
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[SpriteContainer (name="+ this.name +")]";
};
createjs.SpriteContainer = createjs.promote(SpriteContainer, "Container");
}());
| iwangx/createjs | src/easeljs/display/SpriteContainer.js | JavaScript | mit | 7,122 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("QuizFactory.Mvc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuizFactory.Mvc")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97bb970b-ddd4-4a54-be05-eebc21f2bb9e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| dpesheva/QuizFactory | QuizFactory/QuizFactory.MVC/Properties/AssemblyInfo.cs | C# | mit | 1,361 |
package com.reason.ide.highlight;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static com.intellij.psi.TokenType.BAD_CHARACTER;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import com.reason.lang.core.type.ORTypes;
import com.reason.lang.napkin.ResLexer;
import com.reason.lang.napkin.ResTypes;
import com.reason.lang.ocaml.OclLexer;
import com.reason.lang.ocaml.OclTypes;
import com.reason.lang.reason.RmlLexer;
import com.reason.lang.reason.RmlTypes;
import java.util.*;
import org.jetbrains.annotations.NotNull;
public class ORSyntaxHighlighter extends SyntaxHighlighterBase {
private static final Set<IElementType> RML_KEYWORD_TYPES =
of(
RmlTypes.INSTANCE.OPEN,
RmlTypes.INSTANCE.MODULE,
RmlTypes.INSTANCE.FUN,
RmlTypes.INSTANCE.LET,
RmlTypes.INSTANCE.TYPE,
RmlTypes.INSTANCE.INCLUDE,
RmlTypes.INSTANCE.EXTERNAL,
RmlTypes.INSTANCE.IF,
RmlTypes.INSTANCE.ELSE,
RmlTypes.INSTANCE.ENDIF,
RmlTypes.INSTANCE.SWITCH,
RmlTypes.INSTANCE.TRY,
RmlTypes.INSTANCE.RAISE,
RmlTypes.INSTANCE.FOR,
RmlTypes.INSTANCE.IN,
RmlTypes.INSTANCE.TO,
RmlTypes.INSTANCE.BOOL_VALUE,
RmlTypes.INSTANCE.REF,
RmlTypes.INSTANCE.EXCEPTION,
RmlTypes.INSTANCE.WHEN,
RmlTypes.INSTANCE.AND,
RmlTypes.INSTANCE.REC,
RmlTypes.INSTANCE.WHILE,
RmlTypes.INSTANCE.ASR,
RmlTypes.INSTANCE.CLASS,
RmlTypes.INSTANCE.CONSTRAINT,
RmlTypes.INSTANCE.DOWNTO,
RmlTypes.INSTANCE.FUNCTOR,
RmlTypes.INSTANCE.INHERIT,
RmlTypes.INSTANCE.INITIALIZER,
RmlTypes.INSTANCE.LAND,
RmlTypes.INSTANCE.LOR,
RmlTypes.INSTANCE.LSL,
RmlTypes.INSTANCE.LSR,
RmlTypes.INSTANCE.LXOR,
RmlTypes.INSTANCE.METHOD,
RmlTypes.INSTANCE.MOD,
RmlTypes.INSTANCE.NEW,
RmlTypes.INSTANCE.NONREC,
RmlTypes.INSTANCE.OR,
RmlTypes.INSTANCE.PRIVATE,
RmlTypes.INSTANCE.VIRTUAL,
RmlTypes.INSTANCE.VAL,
RmlTypes.INSTANCE.PUB,
RmlTypes.INSTANCE.PRI,
RmlTypes.INSTANCE.OBJECT,
RmlTypes.INSTANCE.MUTABLE,
RmlTypes.INSTANCE.UNIT,
RmlTypes.INSTANCE.WITH,
RmlTypes.INSTANCE.DIRECTIVE_IF,
RmlTypes.INSTANCE.DIRECTIVE_ELSE,
RmlTypes.INSTANCE.DIRECTIVE_ELIF,
RmlTypes.INSTANCE.DIRECTIVE_END,
RmlTypes.INSTANCE.DIRECTIVE_ENDIF);
private static final Set<IElementType> RML_OPERATION_SIGN_TYPES =
of(
RmlTypes.INSTANCE.L_AND,
RmlTypes.INSTANCE.L_OR,
RmlTypes.INSTANCE.SHORTCUT,
RmlTypes.INSTANCE.ARROW,
RmlTypes.INSTANCE.PIPE_FIRST,
RmlTypes.INSTANCE.PIPE_FORWARD,
RmlTypes.INSTANCE.EQEQEQ,
RmlTypes.INSTANCE.EQEQ,
RmlTypes.INSTANCE.EQ,
RmlTypes.INSTANCE.NOT_EQEQ,
RmlTypes.INSTANCE.NOT_EQ,
RmlTypes.INSTANCE.DIFF,
RmlTypes.INSTANCE.COLON,
RmlTypes.INSTANCE.SINGLE_QUOTE,
RmlTypes.INSTANCE.DOUBLE_QUOTE,
RmlTypes.INSTANCE.CARRET,
RmlTypes.INSTANCE.PLUSDOT,
RmlTypes.INSTANCE.MINUSDOT,
RmlTypes.INSTANCE.SLASHDOT,
RmlTypes.INSTANCE.STARDOT,
RmlTypes.INSTANCE.PLUS,
RmlTypes.INSTANCE.MINUS,
RmlTypes.INSTANCE.SLASH,
RmlTypes.INSTANCE.STAR,
RmlTypes.INSTANCE.PERCENT,
RmlTypes.INSTANCE.PIPE,
RmlTypes.INSTANCE.ARROBASE,
RmlTypes.INSTANCE.SHARP,
RmlTypes.INSTANCE.SHARPSHARP,
RmlTypes.INSTANCE.QUESTION_MARK,
RmlTypes.INSTANCE.EXCLAMATION_MARK,
RmlTypes.INSTANCE.LT_OR_EQUAL,
RmlTypes.INSTANCE.GT_OR_EQUAL,
RmlTypes.INSTANCE.AMPERSAND,
RmlTypes.INSTANCE.LEFT_ARROW,
RmlTypes.INSTANCE.RIGHT_ARROW,
RmlTypes.INSTANCE.COLON_EQ,
RmlTypes.INSTANCE.COLON_GT,
RmlTypes.INSTANCE.GT,
RmlTypes.INSTANCE.GT_BRACE,
RmlTypes.INSTANCE.GT_BRACKET,
RmlTypes.INSTANCE.BRACKET_GT,
RmlTypes.INSTANCE.BRACKET_LT,
RmlTypes.INSTANCE.BRACE_LT,
RmlTypes.INSTANCE.DOTDOT);
private static final Set<IElementType> RML_OPTIONS_TYPES =
of(RmlTypes.INSTANCE.NONE, RmlTypes.INSTANCE.SOME);
private static final Set<IElementType> NS_KEYWORD_TYPES =
of(
ResTypes.INSTANCE.OPEN,
ResTypes.INSTANCE.MODULE,
ResTypes.INSTANCE.FUN,
ResTypes.INSTANCE.LET,
ResTypes.INSTANCE.TYPE,
ResTypes.INSTANCE.INCLUDE,
ResTypes.INSTANCE.EXTERNAL,
ResTypes.INSTANCE.IF,
ResTypes.INSTANCE.ELSE,
ResTypes.INSTANCE.ENDIF,
ResTypes.INSTANCE.SWITCH,
ResTypes.INSTANCE.TRY,
ResTypes.INSTANCE.RAISE,
ResTypes.INSTANCE.FOR,
ResTypes.INSTANCE.IN,
ResTypes.INSTANCE.TO,
ResTypes.INSTANCE.BOOL_VALUE,
ResTypes.INSTANCE.REF,
ResTypes.INSTANCE.EXCEPTION,
ResTypes.INSTANCE.WHEN,
ResTypes.INSTANCE.AND,
ResTypes.INSTANCE.REC,
ResTypes.INSTANCE.WHILE,
ResTypes.INSTANCE.ASR,
ResTypes.INSTANCE.CLASS,
ResTypes.INSTANCE.CONSTRAINT,
ResTypes.INSTANCE.DOWNTO,
ResTypes.INSTANCE.FUNCTOR,
ResTypes.INSTANCE.INHERIT,
ResTypes.INSTANCE.INITIALIZER,
ResTypes.INSTANCE.LAND,
ResTypes.INSTANCE.LOR,
ResTypes.INSTANCE.LSL,
ResTypes.INSTANCE.LSR,
ResTypes.INSTANCE.LXOR,
ResTypes.INSTANCE.METHOD,
ResTypes.INSTANCE.MOD,
ResTypes.INSTANCE.NEW,
ResTypes.INSTANCE.NONREC,
ResTypes.INSTANCE.OR,
ResTypes.INSTANCE.PRIVATE,
ResTypes.INSTANCE.VIRTUAL,
ResTypes.INSTANCE.VAL,
ResTypes.INSTANCE.PUB,
ResTypes.INSTANCE.PRI,
ResTypes.INSTANCE.OBJECT,
ResTypes.INSTANCE.MUTABLE,
ResTypes.INSTANCE.UNIT,
ResTypes.INSTANCE.WITH,
ResTypes.INSTANCE.DIRECTIVE_IF,
ResTypes.INSTANCE.DIRECTIVE_ELSE,
ResTypes.INSTANCE.DIRECTIVE_ELIF,
ResTypes.INSTANCE.DIRECTIVE_END,
ResTypes.INSTANCE.DIRECTIVE_ENDIF);
private static final Set<IElementType> NS_OPERATION_SIGN_TYPES =
of(
ResTypes.INSTANCE.L_AND,
ResTypes.INSTANCE.L_OR,
ResTypes.INSTANCE.SHORTCUT,
ResTypes.INSTANCE.ARROW,
ResTypes.INSTANCE.PIPE_FIRST,
ResTypes.INSTANCE.PIPE_FORWARD,
ResTypes.INSTANCE.EQEQEQ,
ResTypes.INSTANCE.EQEQ,
ResTypes.INSTANCE.EQ,
ResTypes.INSTANCE.NOT_EQEQ,
ResTypes.INSTANCE.NOT_EQ,
ResTypes.INSTANCE.DIFF,
ResTypes.INSTANCE.COLON,
ResTypes.INSTANCE.SINGLE_QUOTE,
ResTypes.INSTANCE.DOUBLE_QUOTE,
ResTypes.INSTANCE.CARRET,
ResTypes.INSTANCE.PLUSDOT,
ResTypes.INSTANCE.MINUSDOT,
ResTypes.INSTANCE.SLASHDOT,
ResTypes.INSTANCE.STARDOT,
ResTypes.INSTANCE.PLUS,
ResTypes.INSTANCE.MINUS,
ResTypes.INSTANCE.SLASH,
ResTypes.INSTANCE.STAR,
ResTypes.INSTANCE.PERCENT,
ResTypes.INSTANCE.PIPE,
ResTypes.INSTANCE.ARROBASE,
ResTypes.INSTANCE.SHARP,
ResTypes.INSTANCE.SHARPSHARP,
ResTypes.INSTANCE.QUESTION_MARK,
ResTypes.INSTANCE.EXCLAMATION_MARK,
ResTypes.INSTANCE.LT_OR_EQUAL,
ResTypes.INSTANCE.GT_OR_EQUAL,
ResTypes.INSTANCE.AMPERSAND,
ResTypes.INSTANCE.LEFT_ARROW,
ResTypes.INSTANCE.RIGHT_ARROW,
ResTypes.INSTANCE.COLON_EQ,
ResTypes.INSTANCE.COLON_GT,
ResTypes.INSTANCE.GT,
ResTypes.INSTANCE.GT_BRACE,
ResTypes.INSTANCE.GT_BRACKET,
ResTypes.INSTANCE.BRACKET_GT,
ResTypes.INSTANCE.BRACKET_LT,
ResTypes.INSTANCE.BRACE_LT,
ResTypes.INSTANCE.DOTDOT);
private static final Set<IElementType> NS_OPTIONS_TYPES =
of(ResTypes.INSTANCE.NONE, ResTypes.INSTANCE.SOME);
private static final Set<IElementType> OCL_KEYWORD_TYPES =
of(
OclTypes.INSTANCE.OPEN,
OclTypes.INSTANCE.MODULE,
OclTypes.INSTANCE.FUN,
OclTypes.INSTANCE.LET,
OclTypes.INSTANCE.TYPE,
OclTypes.INSTANCE.INCLUDE,
OclTypes.INSTANCE.EXTERNAL,
OclTypes.INSTANCE.IF,
OclTypes.INSTANCE.ELSE,
OclTypes.INSTANCE.ENDIF,
OclTypes.INSTANCE.SWITCH,
OclTypes.INSTANCE.TRY,
OclTypes.INSTANCE.RAISE,
OclTypes.INSTANCE.FOR,
OclTypes.INSTANCE.IN,
OclTypes.INSTANCE.TO,
OclTypes.INSTANCE.BOOL_VALUE,
OclTypes.INSTANCE.REF,
OclTypes.INSTANCE.EXCEPTION,
OclTypes.INSTANCE.WHEN,
OclTypes.INSTANCE.AND,
OclTypes.INSTANCE.REC,
OclTypes.INSTANCE.WHILE,
OclTypes.INSTANCE.ASR,
OclTypes.INSTANCE.CLASS,
OclTypes.INSTANCE.CONSTRAINT,
OclTypes.INSTANCE.DOWNTO,
OclTypes.INSTANCE.FUNCTOR,
OclTypes.INSTANCE.INHERIT,
OclTypes.INSTANCE.INITIALIZER,
OclTypes.INSTANCE.LAND,
OclTypes.INSTANCE.LOR,
OclTypes.INSTANCE.LSL,
OclTypes.INSTANCE.LSR,
OclTypes.INSTANCE.LXOR,
OclTypes.INSTANCE.METHOD,
OclTypes.INSTANCE.MOD,
OclTypes.INSTANCE.NEW,
OclTypes.INSTANCE.NONREC,
OclTypes.INSTANCE.OR,
OclTypes.INSTANCE.PRIVATE,
OclTypes.INSTANCE.VIRTUAL,
OclTypes.INSTANCE.AS,
OclTypes.INSTANCE.MUTABLE,
OclTypes.INSTANCE.OF,
OclTypes.INSTANCE.VAL,
OclTypes.INSTANCE.PRI,
// OCaml
OclTypes.INSTANCE.MATCH,
OclTypes.INSTANCE.WITH,
OclTypes.INSTANCE.DO,
OclTypes.INSTANCE.DONE,
OclTypes.INSTANCE.RECORD,
OclTypes.INSTANCE.BEGIN,
OclTypes.INSTANCE.END,
OclTypes.INSTANCE.LAZY,
OclTypes.INSTANCE.ASSERT,
OclTypes.INSTANCE.THEN,
OclTypes.INSTANCE.FUNCTION,
OclTypes.INSTANCE.STRUCT,
OclTypes.INSTANCE.SIG,
OclTypes.INSTANCE.OBJECT,
OclTypes.INSTANCE.DIRECTIVE_IF,
OclTypes.INSTANCE.DIRECTIVE_ELSE,
OclTypes.INSTANCE.DIRECTIVE_ELIF,
OclTypes.INSTANCE.DIRECTIVE_END,
OclTypes.INSTANCE.DIRECTIVE_ENDIF);
private static final Set<IElementType> OCL_OPERATION_SIGN_TYPES =
of(
OclTypes.INSTANCE.L_AND,
OclTypes.INSTANCE.L_OR,
OclTypes.INSTANCE.SHORTCUT,
OclTypes.INSTANCE.ARROW,
OclTypes.INSTANCE.PIPE_FIRST,
OclTypes.INSTANCE.PIPE_FORWARD,
OclTypes.INSTANCE.EQEQEQ,
OclTypes.INSTANCE.EQEQ,
OclTypes.INSTANCE.EQ,
OclTypes.INSTANCE.NOT_EQEQ,
OclTypes.INSTANCE.NOT_EQ,
OclTypes.INSTANCE.DIFF,
OclTypes.INSTANCE.COLON,
OclTypes.INSTANCE.SINGLE_QUOTE,
OclTypes.INSTANCE.DOUBLE_QUOTE,
OclTypes.INSTANCE.CARRET,
OclTypes.INSTANCE.PLUSDOT,
OclTypes.INSTANCE.MINUSDOT,
OclTypes.INSTANCE.SLASHDOT,
OclTypes.INSTANCE.STARDOT,
OclTypes.INSTANCE.PLUS,
OclTypes.INSTANCE.MINUS,
OclTypes.INSTANCE.SLASH,
OclTypes.INSTANCE.STAR,
OclTypes.INSTANCE.PERCENT,
OclTypes.INSTANCE.PIPE,
OclTypes.INSTANCE.ARROBASE,
OclTypes.INSTANCE.SHARP,
OclTypes.INSTANCE.SHARPSHARP,
OclTypes.INSTANCE.QUESTION_MARK,
OclTypes.INSTANCE.EXCLAMATION_MARK,
OclTypes.INSTANCE.LT_OR_EQUAL,
OclTypes.INSTANCE.GT_OR_EQUAL,
OclTypes.INSTANCE.AMPERSAND,
OclTypes.INSTANCE.LEFT_ARROW,
OclTypes.INSTANCE.RIGHT_ARROW,
OclTypes.INSTANCE.COLON_EQ,
OclTypes.INSTANCE.COLON_GT,
OclTypes.INSTANCE.GT,
OclTypes.INSTANCE.GT_BRACE,
OclTypes.INSTANCE.GT_BRACKET,
OclTypes.INSTANCE.BRACKET_GT,
OclTypes.INSTANCE.BRACKET_LT,
OclTypes.INSTANCE.BRACE_LT,
OclTypes.INSTANCE.DOTDOT);
private static final Set<IElementType> OCL_OPTIONS_TYPES =
of(OclTypes.INSTANCE.NONE, OclTypes.INSTANCE.SOME);
private static final TextAttributesKey TYPE_ARGUMENT_KEY =
TextAttributesKey.createTextAttributesKey("TYPE_ARGUMENT");
public static final TextAttributesKey ANNOTATION_ =
createTextAttributesKey("REASONML_ANNOTATION", DefaultLanguageHighlighterColors.METADATA);
public static final TextAttributesKey BRACES_ =
createTextAttributesKey("REASONML_BRACES", DefaultLanguageHighlighterColors.BRACES);
public static final TextAttributesKey BRACKETS_ =
createTextAttributesKey("REASONML_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS);
public static final TextAttributesKey CODE_LENS_ =
createTextAttributesKey("REASONML_CODE_LENS", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD_ =
createTextAttributesKey("REASONML_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey MARKUP_TAG_ =
createTextAttributesKey("REASONML_MARKUP_TAG", DefaultLanguageHighlighterColors.MARKUP_TAG);
public static final TextAttributesKey MARKUP_ATTRIBUTE_ =
createTextAttributesKey(
"REASONML_MARKUP_ATTRIBUTE", DefaultLanguageHighlighterColors.MARKUP_ATTRIBUTE);
public static final TextAttributesKey MODULE_NAME_ =
createTextAttributesKey("REASONML_MODULE_NAME", DefaultLanguageHighlighterColors.CLASS_NAME);
public static final TextAttributesKey NUMBER_ =
createTextAttributesKey("REASONML_NUMBER", DefaultLanguageHighlighterColors.NUMBER);
public static final TextAttributesKey OPERATION_SIGN_ =
createTextAttributesKey(
"REASONML_OPERATION_SIGN", DefaultLanguageHighlighterColors.OPERATION_SIGN);
public static final TextAttributesKey OPTION_ =
createTextAttributesKey("REASONML_OPTION", DefaultLanguageHighlighterColors.STATIC_FIELD);
public static final TextAttributesKey PARENS_ =
createTextAttributesKey("REASONML_PARENS", DefaultLanguageHighlighterColors.PARENTHESES);
public static final TextAttributesKey POLY_VARIANT_ =
createTextAttributesKey(
"REASONML_POLY_VARIANT", DefaultLanguageHighlighterColors.STATIC_FIELD);
public static final TextAttributesKey RML_COMMENT_ =
createTextAttributesKey("REASONML_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey SEMICOLON_ =
createTextAttributesKey("REASONML_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON);
public static final TextAttributesKey STRING_ =
createTextAttributesKey("REASONML_STRING", DefaultLanguageHighlighterColors.STRING);
public static final TextAttributesKey TYPE_ARGUMENT_ =
createTextAttributesKey("REASONML_TYPE_ARGUMENT", TYPE_ARGUMENT_KEY);
public static final TextAttributesKey VARIANT_NAME_ =
createTextAttributesKey(
"REASONML_VARIANT_NAME", DefaultLanguageHighlighterColors.STATIC_FIELD);
private static final TextAttributesKey BAD_CHAR_ =
createTextAttributesKey("REASONML_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER);
private static final TextAttributesKey[] NUMBER_KEYS = new TextAttributesKey[]{NUMBER_};
private static final TextAttributesKey[] COMMENT_KEYS = new TextAttributesKey[]{RML_COMMENT_};
private static final TextAttributesKey[] STRING_KEYS = new TextAttributesKey[]{STRING_};
private static final TextAttributesKey[] TYPE_ARGUMENT_KEYS = new TextAttributesKey[]{TYPE_ARGUMENT_};
private static final TextAttributesKey[] POLY_VARIANT_KEYS = new TextAttributesKey[]{POLY_VARIANT_};
private static final TextAttributesKey[] BRACKET_KEYS = new TextAttributesKey[]{BRACKETS_};
private static final TextAttributesKey[] BRACE_KEYS = new TextAttributesKey[]{BRACES_};
private static final TextAttributesKey[] PAREN_KEYS = new TextAttributesKey[]{PARENS_};
private static final TextAttributesKey[] OPTION_KEYS = new TextAttributesKey[]{OPTION_};
private static final TextAttributesKey[] KEYWORD_KEYS = new TextAttributesKey[]{KEYWORD_};
private static final TextAttributesKey[] SEMICOLON_KEYS = new TextAttributesKey[]{SEMICOLON_};
private static final TextAttributesKey[] DOT_KEYS = new TextAttributesKey[]{OPERATION_SIGN_};
private static final TextAttributesKey[] COMMA_KEYS = new TextAttributesKey[]{OPERATION_SIGN_};
private static final TextAttributesKey[] OPERATION_SIGN_KEYS = new TextAttributesKey[]{OPERATION_SIGN_};
private static final TextAttributesKey[] BAD_CHAR_KEYS = new TextAttributesKey[]{BAD_CHAR_};
private static final TextAttributesKey[] EMPTY_KEYS = new TextAttributesKey[0];
private final ORTypes m_types;
public ORSyntaxHighlighter(ORTypes types) {
m_types = types;
}
@Override
public @NotNull Lexer getHighlightingLexer() {
return m_types instanceof RmlTypes
? new RmlLexer()
: m_types instanceof ResTypes ? new ResLexer() : new OclLexer();
}
@Override
public @NotNull TextAttributesKey[] getTokenHighlights(@NotNull IElementType tokenType) {
if (tokenType.equals(m_types.MULTI_COMMENT) || tokenType.equals(m_types.SINGLE_COMMENT)) {
return COMMENT_KEYS;
} else if (tokenType.equals(m_types.LBRACE) || tokenType.equals(m_types.RBRACE)) {
return BRACE_KEYS;
} else if (tokenType.equals(m_types.LBRACKET)
|| tokenType.equals(m_types.RBRACKET)
|| tokenType.equals(m_types.LARRAY)
|| tokenType.equals(m_types.RARRAY)
|| tokenType.equals(m_types.ML_STRING_OPEN)
|| tokenType.equals(m_types.ML_STRING_CLOSE)
|| tokenType.equals(m_types.JS_STRING_OPEN)
|| tokenType.equals(m_types.JS_STRING_CLOSE)) {
return BRACKET_KEYS;
} else if (tokenType.equals(m_types.LPAREN) || tokenType.equals(m_types.RPAREN)) {
return PAREN_KEYS;
} else if (tokenType.equals(m_types.INT_VALUE) || tokenType.equals(m_types.FLOAT_VALUE)) {
return NUMBER_KEYS;
} else if (m_types.DOT.equals(tokenType)) {
return DOT_KEYS;
} else if (m_types.TYPE_ARGUMENT.equals(tokenType)) {
return TYPE_ARGUMENT_KEYS;
} else if (m_types.POLY_VARIANT.equals(tokenType)) {
return POLY_VARIANT_KEYS;
} else if (m_types.COMMA.equals(tokenType)) {
return COMMA_KEYS;
} else if (m_types.SEMI.equals(tokenType) || m_types.SEMISEMI.equals(tokenType)) {
return SEMICOLON_KEYS;
} else if (m_types.STRING_VALUE.equals(tokenType) || m_types.CHAR_VALUE.equals(tokenType)) {
return STRING_KEYS;
} else if (m_types == RmlTypes.INSTANCE) {
if (RML_KEYWORD_TYPES.contains(tokenType)) {
return KEYWORD_KEYS;
} else if (RML_OPERATION_SIGN_TYPES.contains(tokenType)) {
return OPERATION_SIGN_KEYS;
} else if (RML_OPTIONS_TYPES.contains(tokenType)) {
return OPTION_KEYS;
}
} else if (m_types == ResTypes.INSTANCE) {
if (NS_KEYWORD_TYPES.contains(tokenType)) {
return KEYWORD_KEYS;
} else if (NS_OPERATION_SIGN_TYPES.contains(tokenType)) {
return OPERATION_SIGN_KEYS;
} else if (NS_OPTIONS_TYPES.contains(tokenType)) {
return OPTION_KEYS;
}
} else if (m_types == OclTypes.INSTANCE) {
if (OCL_KEYWORD_TYPES.contains(tokenType)) {
return KEYWORD_KEYS;
} else if (OCL_OPERATION_SIGN_TYPES.contains(tokenType)) {
return OPERATION_SIGN_KEYS;
} else if (OCL_OPTIONS_TYPES.contains(tokenType)) {
return OPTION_KEYS;
}
} else if (BAD_CHARACTER.equals(tokenType)) {
return BAD_CHAR_KEYS;
}
return EMPTY_KEYS;
}
@NotNull
private static Set<IElementType> of(IElementType... types) {
Set<IElementType> result = new HashSet<>();
Collections.addAll(result, types);
return result;
}
}
| reasonml-editor/reasonml-idea-plugin | src/com/reason/ide/highlight/ORSyntaxHighlighter.java | Java | mit | 24,489 |
using System;
using System.Reflection;
namespace AssemblyLoader
{
/// <summary>
/// Cross platform AssemblyLoader implementations
/// </summary>
public static class Loader
{
/// <summary>
/// Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly
/// is loaded into the application domain of the caller.
/// </summary>
/// <param name="rawAssembly"></param>
public static Assembly LoadAssembly(byte[] rawAssembly)
{
throw NotImplementedInReferenceAssembly();
}
/// <summary>
/// Returns true if the environment you are running under supports assembly load at runtime.
/// </summary>
public static bool RuntimeLoadAvailable
{
get { return false; }
}
internal static Exception NotImplementedInReferenceAssembly()
{
return new NotImplementedException("The portable implementation of AssemblyLoader was called. Either you are running on a supported platform but haven't installed the AssemblyLoader package into the platform project, or you are trying to use AssemblyLoader on an unsupported (i.e. WinRT) platform.");
}
}
} | rdavisau/loadassembly-for-pcl | AssemblyLoader/AssemblyLoader.Plugin/AssemblyLoader.cs | C# | mit | 1,294 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Response;
use Symfony\Component\HttpClient\Chunk\DataChunk;
use Symfony\Component\HttpClient\Chunk\ErrorChunk;
use Symfony\Component\HttpClient\Chunk\FirstChunk;
use Symfony\Component\HttpClient\Chunk\LastChunk;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpClient\Exception\JsonException;
use Symfony\Component\HttpClient\Exception\RedirectionException;
use Symfony\Component\HttpClient\Exception\ServerException;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\Internal\ClientState;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
* Implements the common logic for response classes.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait ResponseTrait
{
private $logger;
private $headers = [];
/**
* @var callable|null A callback that initializes the two previous properties
*/
private $initializer;
/**
* @var resource A php://temp stream typically
*/
private $content;
private $info = [
'response_headers' => [],
'http_code' => 0,
'error' => null,
'canceled' => false,
];
/** @var resource */
private $handle;
private $id;
private $timeout = 0;
private $finalInfo;
private $offset = 0;
private $jsonData;
/**
* {@inheritdoc}
*/
public function getStatusCode(): int
{
if ($this->initializer) {
($this->initializer)($this);
$this->initializer = null;
}
return $this->info['http_code'];
}
/**
* {@inheritdoc}
*/
public function getHeaders(bool $throw = true): array
{
if ($this->initializer) {
($this->initializer)($this);
$this->initializer = null;
}
if ($throw) {
$this->checkStatusCode();
}
return $this->headers;
}
/**
* {@inheritdoc}
*/
public function getContent(bool $throw = true): string
{
if ($this->initializer) {
($this->initializer)($this);
$this->initializer = null;
}
if ($throw) {
$this->checkStatusCode();
}
if (null === $this->content) {
$content = null;
foreach (self::stream([$this]) as $chunk) {
if (!$chunk->isLast()) {
$content .= $chunk->getContent();
}
}
if (null !== $content) {
return $content;
}
if ('HEAD' === $this->info['http_method'] || \in_array($this->info['http_code'], [204, 304], true)) {
return '';
}
throw new TransportException('Cannot get the content of the response twice: buffering is disabled.');
}
foreach (self::stream([$this]) as $chunk) {
// Chunks are buffered in $this->content already
}
rewind($this->content);
return stream_get_contents($this->content);
}
/**
* {@inheritdoc}
*/
public function toArray(bool $throw = true): array
{
if ('' === $content = $this->getContent($throw)) {
throw new TransportException('Response body is empty.');
}
if (null !== $this->jsonData) {
return $this->jsonData;
}
$contentType = $this->headers['content-type'][0] ?? 'application/json';
if (!preg_match('/\bjson\b/i', $contentType)) {
throw new JsonException(sprintf('Response content-type is "%s" while a JSON-compatible one was expected.', $contentType));
}
try {
$content = json_decode($content, true, 512, JSON_BIGINT_AS_STRING | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0));
} catch (\JsonException $e) {
throw new JsonException($e->getMessage(), $e->getCode());
}
if (\PHP_VERSION_ID < 70300 && JSON_ERROR_NONE !== json_last_error()) {
throw new JsonException(json_last_error_msg(), json_last_error());
}
if (!\is_array($content)) {
throw new JsonException(sprintf('JSON content was expected to decode to an array, %s returned.', \gettype($content)));
}
if (null !== $this->content) {
// Option "buffer" is true
return $this->jsonData = $content;
}
return $content;
}
/**
* {@inheritdoc}
*/
public function cancel(): void
{
$this->info['canceled'] = true;
$this->info['error'] = 'Response has been canceled.';
$this->close();
}
/**
* Casts the response to a PHP stream resource.
*
* @return resource
*
* @throws TransportExceptionInterface When a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function toStream(bool $throw = true)
{
if ($throw) {
// Ensure headers arrived
$this->getHeaders($throw);
}
$stream = StreamWrapper::createResource($this);
stream_get_meta_data($stream)['wrapper_data']
->bindHandles($this->handle, $this->content);
return $stream;
}
/**
* Closes the response and all its network handles.
*/
abstract protected function close(): void;
/**
* Adds pending responses to the activity list.
*/
abstract protected static function schedule(self $response, array &$runningResponses): void;
/**
* Performs all pending non-blocking operations.
*/
abstract protected static function perform(ClientState $multi, array &$responses): void;
/**
* Waits for network activity.
*/
abstract protected static function select(ClientState $multi, float $timeout): int;
private static function addResponseHeaders(array $responseHeaders, array &$info, array &$headers, string &$debug = ''): void
{
foreach ($responseHeaders as $h) {
if (11 <= \strlen($h) && '/' === $h[4] && preg_match('#^HTTP/\d+(?:\.\d+)? ([12345]\d\d) .*#', $h, $m)) {
if ($headers) {
$debug .= "< \r\n";
$headers = [];
}
$info['http_code'] = (int) $m[1];
} elseif (2 === \count($m = explode(':', $h, 2))) {
$headers[strtolower($m[0])][] = ltrim($m[1]);
}
$debug .= "< {$h}\r\n";
$info['response_headers'][] = $h;
}
$debug .= "< \r\n";
if (!$info['http_code']) {
throw new TransportException('Invalid or missing HTTP status line.');
}
}
private function checkStatusCode()
{
if (500 <= $this->info['http_code']) {
throw new ServerException($this);
}
if (400 <= $this->info['http_code']) {
throw new ClientException($this);
}
if (300 <= $this->info['http_code']) {
throw new RedirectionException($this);
}
}
/**
* Ensures the request is always sent and that the response code was checked.
*/
private function doDestruct()
{
if ($this->initializer && null === $this->info['error']) {
($this->initializer)($this);
$this->initializer = null;
$this->checkStatusCode();
}
}
/**
* Implements an event loop based on a buffer activity queue.
*
* @internal
*/
public static function stream(iterable $responses, float $timeout = null): \Generator
{
$runningResponses = [];
foreach ($responses as $response) {
self::schedule($response, $runningResponses);
}
$lastActivity = microtime(true);
$isTimeout = false;
while (true) {
$hasActivity = false;
$timeoutMax = 0;
$timeoutMin = $timeout ?? INF;
/** @var ClientState $multi */
foreach ($runningResponses as $i => [$multi]) {
$responses = &$runningResponses[$i][1];
self::perform($multi, $responses);
foreach ($responses as $j => $response) {
$timeoutMax = $timeout ?? max($timeoutMax, $response->timeout);
$timeoutMin = min($timeoutMin, $response->timeout, 1);
$chunk = false;
if (isset($multi->handlesActivity[$j])) {
// no-op
} elseif (!isset($multi->openHandles[$j])) {
unset($responses[$j]);
continue;
} elseif ($isTimeout) {
$multi->handlesActivity[$j] = [new ErrorChunk($response->offset, sprintf('Idle timeout reached for "%s".', $response->getInfo('url')))];
} else {
continue;
}
while ($multi->handlesActivity[$j] ?? false) {
$hasActivity = true;
$isTimeout = false;
if (\is_string($chunk = array_shift($multi->handlesActivity[$j]))) {
$response->offset += \strlen($chunk);
$chunk = new DataChunk($response->offset, $chunk);
} elseif (null === $chunk) {
$e = $multi->handlesActivity[$j][0];
unset($responses[$j], $multi->handlesActivity[$j]);
$response->close();
if (null !== $e) {
$response->info['error'] = $e->getMessage();
if ($e instanceof \Error) {
throw $e;
}
$chunk = new ErrorChunk($response->offset, $e);
} else {
$chunk = new LastChunk($response->offset);
}
} elseif ($chunk instanceof ErrorChunk) {
unset($responses[$j]);
$isTimeout = true;
} elseif ($chunk instanceof FirstChunk) {
if ($response->logger) {
$info = $response->getInfo();
$response->logger->info(sprintf('Response: "%s %s"', $info['http_code'], $info['url']));
}
yield $response => $chunk;
if ($response->initializer && null === $response->info['error']) {
// Ensure the HTTP status code is always checked
$response->getHeaders(true);
}
continue;
}
yield $response => $chunk;
}
unset($multi->handlesActivity[$j]);
if ($chunk instanceof ErrorChunk && !$chunk->didThrow()) {
// Ensure transport exceptions are always thrown
$chunk->getContent();
}
}
if (!$responses) {
unset($runningResponses[$i]);
}
// Prevent memory leaks
$multi->handlesActivity = $multi->handlesActivity ?: [];
$multi->openHandles = $multi->openHandles ?: [];
}
if (!$runningResponses) {
break;
}
if ($hasActivity) {
$lastActivity = microtime(true);
continue;
}
switch (self::select($multi, $timeoutMin)) {
case -1: usleep(min(500, 1E6 * $timeoutMin)); break;
case 0: $isTimeout = microtime(true) - $lastActivity > $timeoutMax; break;
}
}
}
}
| shieldo/symfony | src/Symfony/Component/HttpClient/Response/ResponseTrait.php | PHP | mit | 12,832 |
module Meta
module Filelib
def self.create_directory(name)
unless name.nil?
if File.directory?(name)
puts "directory already exists".yellow
else
FileUtils.mkdir_p(name)
puts "directory #{name} created".green
end
end
end
def self.create_file( text, filename, ext, dest, overwrite=false )
filename = File.basename( filename, File.extname(filename) ) + ext
filename = dest + SLASH + filename
reply = false
write = false
if File.exists?(filename)
reply = agree("file #{filename} exists, overwrite?".red) {
|q| q.default = "n" } unless overwrite
else
write = true
end
if overwrite or reply or write
f = File.open( filename, "w" )
f.write(text)
f.close
if overwrite or reply
puts "file #{filename} overwritten".green
else
puts "file #{filename} created".green
end
end
end
def self.get_templates(pattern)
return Dir.glob( pattern, File::FNM_CASEFOLD )
end
def self.get_contents
return Dir.glob( Meta::MARKDOWN, File::FNM_CASEFOLD )
end
end
end
| stephenhu/meta | lib/meta/filelib.rb | Ruby | mit | 1,226 |
package org.lff.plugin.dupfinder;
import org.lff.plugin.dupfinder.vo.SourceVO;
import javax.swing.table.AbstractTableModel;
import java.util.*;
/**
* @author Feifei Liu
* @datetime Jul 10 2017 13:54
*/
public class DuplicatesTableModel extends AbstractTableModel {
static final String[] NAMES = new String[]{"Type", "Module", "Library"};
private static final long serialVersionUID = 2834765790738917135L;
private List<Map<Integer, String>> data = new LinkedList<>();
private Map<String, Set<SourceVO>> duplicates = new HashMap<>();
@Override
public String getColumnName(int column) {
return NAMES[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Map<Integer, String> rowData = data.get(rowIndex);
return rowData.get(columnIndex);
}
public void add(SourceVO vo) {
Map<Integer, String> rowData = new HashMap<>();
rowData.put(0, vo.getLibrary());
rowData.put(1, vo.getModule());
rowData.put(2, vo.getUrl());
data.add(rowData);
int index0 = data.size() - 1;
int index1 = index0;
this.fireTableRowsInserted(index0, index1);
}
public void setDependents(String fullName, Set<SourceVO> dependents) {
duplicates.put(fullName, dependents);
}
public void clear() {
int index1 = data.size()-1;
data.clear();
if (index1 >= 0) {
fireTableRowsDeleted(0, index1);
}
}
public void show(String fullname) {
Set<SourceVO> list = duplicates.get(fullname);
for (SourceVO vo : list) {
this.add(vo);
}
}
}
| lff0305/duplicateClassFinder | src/org/lff/plugin/dupfinder/DuplicatesTableModel.java | Java | mit | 1,932 |
using OmniConf.Core.Interfaces;
namespace OmniConf.Web
{
public class SiteSettings : ISiteSettings
{
public int SiteConferenceId { get; set; }
}
}
| ardalis/OmniConf | src/OmniConf.Web/SiteSettings.cs | C# | mit | 171 |
// Simple JavaScript Templating
// Heavily based on: John Resig - http://ejohn.org/blog/javascript-micro-templating/
var argName = 'data';
function getFuncBody(str) {
return argName+"="+argName+"||{};var p=[];p.push('"
+ str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');return p.join('');";
}
function mtmpl(str,data) {
var fn = new Function(argName,getFuncBody(str));
return data ? fn(data) : fn;
}
function precompile(str) {
return "function("+argName+"){"+getFuncBody(str)+"}";
}
module.exports = {
mtmpl:mtmpl,
precompile:precompile
}; | theakman2/node-modules-mtmpl | lib/index.js | JavaScript | mit | 756 |
<?php
/**
* Created by PhpStorm.
* Author: Misha Serenkov
* Email: mi.serenkov@gmail.com
* Date: 30.11.2016 11:39
*/
namespace miserenkov\sms\client;
use miserenkov\sms\exceptions\BalanceException;
use miserenkov\sms\exceptions\Exception;
use miserenkov\sms\exceptions\SendException;
use miserenkov\sms\exceptions\StatusException;
use yii\base\InvalidConfigException;
class SoapClient extends \SoapClient implements ClientInterface
{
/**
* @var string
*/
private $_login = null;
/**
* @var string
*/
private $_password = null;
/**
* @var null|string
*/
private $_senderName = null;
/**
* @var bool
*/
private $_throwExceptions = false;
/**
* @inheritdoc
*/
public function __construct($gateway, $login, $password, $senderName, $options = [])
{
$https = true;
$this->_login = $login;
$this->_password = $password;
$this->_senderName = $senderName;
if (isset($options['throwExceptions'])) {
$this->_throwExceptions = $options['throwExceptions'];
}
if (isset($options['useHttps']) && is_bool($options['useHttps'])) {
$https = $options['useHttps'];
}
parent::__construct($this->getWsdl($gateway, $https), []);
}
private function getWsdl($gateway, $useHttps = true)
{
$httpsWsdl = 'https://' . $gateway . '/sys/soap.php?wsdl';
$httpWsdl = 'http://' . $gateway . '/sys/soap.php?wsdl';
if ($useHttps) {
$ch = curl_init($httpsWsdl);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$errorCode = curl_errno($ch);
curl_close($ch);
if ($errorCode === CURLE_OK && $httpCode === 200) {
return $httpsWsdl;
}
\Yii::warning("Gateway \"$gateway\" doesn't support https connections. Will use http", self::class);
if ($this->_throwExceptions) {
throw new InvalidConfigException("Gateway \"$gateway\" doesn't support https connections. Will use http");
}
}
return $httpWsdl;
}
/**
* @inheritdoc
*/
public function getBalance()
{
$response = $this->get_balance([
'login' => $this->_login,
'psw' => $this->_password,
]);
if ($response->balanceresult->error == BalanceException::NO_ERROR) {
$balance = (double)$response->balanceresult->balance;
if (round($balance) == 0) {
\Yii::warning(BalanceException::getErrorString(BalanceException::ERROR_NOT_MONEY), self::class);
if ($this->_throwExceptions) {
throw new BalanceException(BalanceException::ERROR_NOT_MONEY);
}
}
return $balance;
} else {
\Yii::error(BalanceException::getErrorString((int) $response->balanceresult->error), self::class);
if ($this->_throwExceptions) {
throw new BalanceException((int) $response->balanceresult->error);
}
return false;
}
}
/**
* @inheritdoc
*/
public function sendMessage(array $params)
{
$query = [
'login' => $this->_login,
'psw' => $this->_password,
'sender' => $this->_senderName,
];
if (isset($params['phones']) && isset($params['message'])) {
if (!isset($params['tinyurl']) || ($params['tinyurl'] != 0 && $params['tinyurl'] != 1)) {
$query['tinyurl'] = 1;
} else {
$query['tinyurl'] = $params['tinyurl'];
}
if (is_array($params['phones'])) {
$query['phones'] = implode(';', $params['phones']);
} else {
$query['phones'] = $params['phones'];
}
$query['mes'] = $params['message'];
$query['id'] = $params['id'];
$response = $this->send_sms($query);
$response = (array) $response->sendresult;
if (!isset($response['error']) || $response['error'] === '0') {
return ['id' => $response['id']];
} else {
\Yii::error(SendException::getErrorString((int) $response['error']), self::class);
if ($this->_throwExceptions) {
throw new SendException((int) $response['error']);
}
return ['error' => $response['error']];
}
}
return false;
}
/**
* @inheritdoc
*/
public function getMessageStatus($id, $phone, $all = 2)
{
$response = $this->get_status([
'login' => $this->_login,
'psw' => $this->_password,
'phone' => $phone,
'id' => $id,
'all' => $all,
]);
$response = (array) $response->statusresult;
if (count($response) > 0) {
if ((int) $response['error'] !== StatusException::NO_ERROR) {
\Yii::error(SendException::getErrorString((int) $response['error']), self::class);
if ($this->_throwExceptions) {
throw new StatusException((int) $response['error']);
}
return false;
}
return [
'status' => (int) $response['status'],
'status_message' => $this->getSendStatus((int) $response['status']),
'err' => (int) $response['err'],
'err_message' => $this->getSendStatusError((int) $response['err']),
'send_time' => (int) $response['send_timestamp'],
'cost' => (float) $response['cost'],
'operator' => $response['operator'],
'region' => $response['region'],
];
} else {
\Yii::error(Exception::getErrorString(Exception::EMPTY_RESPONSE), self::class);
if ($this->_throwExceptions) {
throw new Exception(Exception::EMPTY_RESPONSE);
}
return false;
}
}
private function getSendStatus($code)
{
$codes = [
-3 => 'The message is not found',
-1 => 'Waiting to be sent',
0 => 'Transferred to the operator',
1 => 'Delivered',
3 => 'Expired',
20 => 'It is impossible to deliver',
22 => 'Wrong number',
23 => 'Prohibited',
24 => 'Insufficient funds',
25 => 'Unavailable number',
];
if (isset($codes[$code])) {
return $codes[$code];
} else {
return 'Unknown status';
}
}
private function getSendStatusError($error)
{
$errors = [
0 => 'There are no errors',
1 => 'The subscriber does not exist',
6 => 'The subscriber is not online',
11 => 'No SMS',
13 => 'The subscriber is blocked',
21 => 'There is no support for SMS',
200 => 'Virtual dispatch',
220 => 'Queue overflowed from the operator',
240 => 'Subscriber is busy',
241 => 'Error converting audio',
242 => 'Recorded answering machine',
243 => 'Not a contract',
244 => 'Distribution is prohibited',
245 => 'Status is not received',
246 => 'A time limit',
247 => 'Limit exceeded messages',
248 => 'There is no route',
249 => 'Invalid number format',
250 => 'The phone number of prohibited settings',
251 => 'Limit is exceeded on a single number',
252 => 'Phone number is prohibited',
253 => 'Prohibited spam filter',
254 => 'Unregistered sender id',
255 => 'Rejected by the operator',
];
if (isset($errors[$error])) {
return $errors[$error];
} else {
return 'Unknown error';
}
}
}
| miserenkov/yii2-sms | src/client/SoapClient.php | PHP | mit | 8,357 |
/*
Edison is designed to be simpler and more performant unit/integration testing framework.
Copyright (c) 2015, Matthew Kelly (Badgerati)
Company: Cadaeic Studios
License: MIT (see LICENSE for details)
*/
using System;
namespace Edison.Engine.Core.Exceptions
{
public class ParseException : Exception
{
public ParseException(string message)
: base(message) { }
}
}
| Badgerati/Edison | Edison.Engine/Core/Exceptions/ParseException.cs | C# | mit | 406 |
module Bondora
VERSION = "0.2.0"
end
| cschritt/bondora | lib/bondora/version.rb | Ruby | mit | 39 |
#ifndef __tcode_byte_buffer_h__
#define __tcode_byte_buffer_h__
#include <tcode/block.hpp>
namespace tcode {
/*!
@class byte_buffer
@brief memory block Á¶ÀÛ °ü·Ã ÀÎÅÍÆäÀ̽º
@author tk
@detail ¸î¸î ÀÎÅÍÆäÀ̽º ( rd_ptr / wr_ptr / etc ) µîÀº ACE message_block µî¿¡¼ ÂüÁ¶\n
³»°¡ »ç¿ëÇÏ±â ÆíÇϵµ·Ï Á¤¸®ÇÑ class\n
³»ºÎ ¹öÆÛ´Â block ÇÒ´çÀÚ ±¸ÇöÀ» ÀÌ¿ë\n
µû¶ó¼ refrenceCounting À¸·Î µ¿ÀÛÇÑ´Ù.
*/
class byte_buffer {
public:
//! buffer ÀÇ ÇöÀç Á¶ÀÛ À§Ä¡ Á¤º¸ tell / seek À¸·Î Á¶ÀÛ
struct position {
public:
position( void );
position( const position& rhs );
position operator=( const position& rhs );
void set( std::size_t r , std::size_t w);
void swap( position& pos );
public:
std::size_t read;
std::size_t write;
};
byte_buffer( void );
//! sz ¸¸ÅÀÇ ¹öÆÛ ÇÒ´ç
explicit byte_buffer( const std::size_t sz );
//! len ¸¸ÅÀÇ ¹öÆÛ ÇÒ´çÈÄ buf ÀÇ ³»¿ëÀ» internal buffer·Î º¹»ç ó¸®
byte_buffer( uint8_t* buf , const std::size_t len );
byte_buffer( const byte_buffer& rhs );
byte_buffer( byte_buffer&& rhs );
byte_buffer& operator=( const byte_buffer& rhs );
byte_buffer& operator=( byte_buffer&& rhs );
~byte_buffer( void );
void swap( byte_buffer& rhs );
// buffer size
std::size_t capacity( void ) const;
// writable pointer
uint8_t* wr_ptr( void );
int wr_ptr( const int move );
// readable pointer
uint8_t* rd_ptr( void );
int rd_ptr( const int move );
//! fit data
int fit( void );
//! fit data & fit buffer
int shrink_to_fit( void );
//! data size
std::size_t length( void );
//! writable size
std::size_t space( void );
//! data clear
void clear( void );
//! capacity reserve
void reserve( const int sz ) ;
std::size_t read(void* dst , const std::size_t sz );
std::size_t peak(void* dst , const std::size_t sz );
std::size_t write( void* src , const std::size_t sz );
position tell( void ) const;
void seek( const position& p );
std::size_t write_msg( const char* msg );
std::size_t write_msg( const wchar_t* msg );
std::size_t write_fmt( const char* msg , ... );
tcode::byte_buffer sub_buffer( const std::size_t start , const std::size_t len );
//! shallow copy
tcode::byte_buffer duplicate(void);
//! deep copy
tcode::byte_buffer copy(void);
private:
byte_buffer( block::handle handle , const position& pos );
private:
block::handle _block;
position _pos;
};
/*!
@brief POD serialization
*/
template < typename Object >
byte_buffer& operator<<( byte_buffer& buf , const Object& obj ) {
buf.write( const_cast<Object*>( &obj ), sizeof( obj ));
return buf;
}
/*!
@brief POD data deserialization
*/
template < typename Object >
byte_buffer& operator>>( byte_buffer& buf , Object& obj ) {
buf.read( &obj , sizeof( obj ));
return buf;
}
}
#endif
| aoziczero/tcode | include/tcode/byte_buffer.hpp | C++ | mit | 2,754 |
<?php
namespace FromSelect\ServiceProvider;
use FromSelect\Controller\ControllerDecorator;
use FromSelect\DecoratingCallableResolver;
use FromSelect\FromSelect;
class RouteServiceProvider implements ServiceProviderInterface
{
/**
* Provides routes for application.
*
* @param FromSelect $app
*/
public function provide(FromSelect $app)
{
require dirname(dirname(__DIR__)).'/resources/routes.php';
$app->getContainer()['callableResolver'] = function ($c) {
$decorator = new ControllerDecorator($c['view'], $c['router']);
return new DecoratingCallableResolver($c, $decorator);
};
}
}
| Albert221/FromSelect | src/ServiceProvider/RouteServiceProvider.php | PHP | mit | 671 |
<main>
<div class="container1">
<div id="liste" class="row z-depth-1" style="margin-bottom: 80px">
<div class="col s12">
<h2 class="header">Liste des OPR <a href="#importer" class="modal-trigger waves-effect waves-light btn blue">Importer</a> </h2>
<div class="row input-field">
<label for="recherche" class="grey-text">Recherche</label>
<input id="recherche" type="text" class="search col s3" style="margin: 0">
<a href="<?php echo base_url()?>c_parametre/rechercher/opr" style="font-size: 13px;"> <i class="material-icons left" style="margin-right: 3px;font-size: 20px">search</i> Recherche avancée</a>
</div>
<table class="bordered striped">
<thead>
<tr>
<th>Code</th>
<th>Nom</th>
<th>Filières développées</th>
<th>Statut juridique</th>
<th>Formelle</th>
<th>Representant</th>
<th width="10%">Option</th>
</tr>
</thead>
<tbody class="list">
<?php foreach($oprListe as $opr) { ?>
<tr>
<td class="codeOpr"><a href="<?php echo base_url()?>c_parametre/fiche_op/opr/<?php echo $opr->ID_OPR ?>"><?php echo $opr->CODE_OPR ?></a></td>
<td class="nomOpr"><?php echo $opr->NOM_OPR ?></td>
<td class="filiere"><?php echo $opr->FILIERES ?></td>
<td><?php echo $opr->STATUT ?></td>
<td><?php if($opr->FORMELLE == 1) echo 'OUI'; else echo 'NON' ?></td>
<td class="representant"><?php echo $opr->REPRESENTANT ?></td>
<td>
<a href="<?php echo base_url()?>c_parametre/edit_op/opr/<?php echo $opr->ID_OPR ?>" class="waves-effect waves-light green btn edit" data-id="<?php echo $opr->ID_OPR ?>"><i class="material-icons">edit</i></a>
<a href="#delete_opr" class="modal-trigger waves-effect waves-light red btn delete" data-id="<?php echo $opr->ID_OPR ?>"><i class="material-icons">delete</i></a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="pagination">
<p class="left"><b>Total: <?php echo $oprTotal?></b></p>
</div>
<div class="fixed-action-btn">
<a href="<?php echo base_url(); ?>c_parametre/ajout_opr" class="btn-floating btn-large red">
<i class="large material-icons">add</i>
</a>
</div>
</div>
</div>
</div>
<!-- Modal import opr -->
<div id="importer" class="modal" style="width: 50%">
<form method="post" action="<?php echo base_url(); ?>c_parametre/importer_opr" enctype="multipart/form-data">
<div class="modal-content center-align">
<h5 class="green-text"> Importer OPR (CSV)</h5>
<div class="divider"></div>
<div class="file-field input-field">
<div class="btn blue">
<span>File</span>
<input type="file" name="csv">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div class="modal-footer" style="width: 100% !important;">
<button type="button" class="modal-action modal-close red waves-effect waves-light btn">Fermer</button>
<button type="submit" class="waves-effect green waves-light btn">Importer</button>
</div>
</form>
</div>
<!-- Modal delete opr -->
<div id="delete_opr" class="modal" style="width: 25%">
<form method="post" action="<?php echo base_url(); ?>c_parametre/delete_opr" >
<div class="modal-content center-align">
<h5 class="red-text"> Supprimer OPR ?</h5>
<div class="divider"></div>
<input id="id_opr" type="hidden" name="id_opr">
</div>
<div class="modal-footer center-align" style="width: 100%!important;">
<button type="submit" class="waves-effect green waves-light btn" style="float: none">Supprimer</button>
<button type="button" class="modal-action modal-close red waves-effect waves-light btn" style="float: none">Fermer</button>
</div>
</form>
</div>
</main>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/init.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/list.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/materialize-pagination.js"></script>
<script type="text/javascript">
var li = $('a[href="http://localhost/aropa/c_parametre/liste_opr"]').parent();
li.addClass("active");
console.log(window.location.href);
var parentLi = li.parents("li");
parentLi.addClass("active");
$(parentLi).children().first().addClass("active");
$(document).ready(function(){
var options = {
valueNames: [ 'codeOpr', 'nomOpr', 'filiere', 'representant' ]
};
var opbListe = new List('liste', options);
$('#pagination').materializePagination({
align: 'right',
lastPage: <?php echo $oprTotal/20 +1 ?>,
firstPage: 1,
urlParameter: 'page',
useUrlParameter: true,
onClickCallback: function(requestedPage){
window.location.replace('<?php echo base_url() ?>c_parametre/liste_opr?page='+requestedPage);
}
});
$('.pagination').removeClass('right-align');
$('.pagination').addClass('right');
});
$(document).on('click', '.delete', function () {
var id_opr = $(this).attr('data-id');
$('#id_opr').val(id_opr);
});
</script> | raoultahin/aropa | application/views/liste_opr.php | PHP | mit | 6,593 |
using Medallion.Threading.Internal;
using Medallion.Threading.Redis.RedLock;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Medallion.Threading.Redis.Primitives
{
internal class RedisMutexPrimitive : IRedLockAcquirableSynchronizationPrimitive, IRedLockExtensibleSynchronizationPrimitive
{
private readonly RedisKey _key;
private readonly RedisValue _lockId;
private readonly RedLockTimeouts _timeouts;
public RedisMutexPrimitive(RedisKey key, RedisValue lockId, RedLockTimeouts timeouts)
{
this._key = key;
this._lockId = lockId;
this._timeouts = timeouts;
}
public TimeoutValue AcquireTimeout => this._timeouts.AcquireTimeout;
private static readonly RedisScript<RedisMutexPrimitive> ReleaseScript = new RedisScript<RedisMutexPrimitive>(@"
if redis.call('get', @key) == @lockId then
return redis.call('del', @key)
end
return 0",
p => new { key = p._key, lockId = p._lockId }
);
public void Release(IDatabase database, bool fireAndForget) => ReleaseScript.Execute(database, this, fireAndForget);
public Task ReleaseAsync(IDatabaseAsync database, bool fireAndForget) => ReleaseScript.ExecuteAsync(database, this, fireAndForget);
public bool TryAcquire(IDatabase database) =>
database.StringSet(this._key, this._lockId, this._timeouts.Expiry.TimeSpan, When.NotExists, CommandFlags.DemandMaster);
public Task<bool> TryAcquireAsync(IDatabaseAsync database) =>
database.StringSetAsync(this._key, this._lockId, this._timeouts.Expiry.TimeSpan, When.NotExists, CommandFlags.DemandMaster);
private static readonly RedisScript<RedisMutexPrimitive> ExtendScript = new RedisScript<RedisMutexPrimitive>(@"
if redis.call('get', @key) == @lockId then
return redis.call('pexpire', @key, @expiryMillis)
end
return 0",
p => new { key = p._key, lockId = p._lockId, expiryMillis = p._timeouts.Expiry.InMilliseconds }
);
public Task<bool> TryExtendAsync(IDatabaseAsync database) => ExtendScript.ExecuteAsync(database, this).AsBooleanTask();
}
}
| madelson/DistributedLock | DistributedLock.Redis/Primitives/RedisMutexPrimitive.cs | C# | mit | 2,369 |
<?php
/*
* This file is part of the Behat Gherkin.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Gherkin\Node;
/**
* Represents Gherkin Scenario.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class ScenarioNode implements ScenarioInterface
{
/**
* @var string
*/
private $title;
/**
* @var array
*/
private $tags = array();
/**
* @var StepNode[]
*/
private $steps = array();
/**
* @var string
*/
private $keyword;
/**
* @var integer
*/
private $line;
/**
* Initializes scenario.
*
* @param null|string $title
* @param array $tags
* @param StepNode[] $steps
* @param string $keyword
* @param integer $line
*/
public function __construct($title, array $tags, array $steps, $keyword, $line)
{
$this->title = $title;
$this->tags = $tags;
$this->steps = $steps;
$this->keyword = $keyword;
$this->line = $line;
}
/**
* Returns node type string
*
* @return string
*/
public function getNodeType()
{
return 'Scenario';
}
/**
* Returns scenario title.
*
* @return null|string
*/
public function getTitle()
{
return $this->title;
}
/**
* Checks if scenario is tagged with tag.
*
* @param string $tag
*
* @return bool
*/
public function hasTag($tag)
{
return in_array($tag, $this->getTags());
}
/**
* Checks if scenario has tags (both inherited from feature and own).
*
* @return bool
*/
public function hasTags()
{
return 0 < count($this->getTags());
}
/**
* Returns scenario tags (including inherited from feature).
*
* @return array
*/
public function getTags()
{
return $this->tags;
}
/**
* Checks if scenario has steps.
*
* @return bool
*/
public function hasSteps()
{
return 0 < count($this->steps);
}
/**
* Returns scenario steps.
*
* @return StepNode[]
*/
public function getSteps()
{
return $this->steps;
}
/**
* Returns scenario keyword.
*
* @return string
*/
public function getKeyword()
{
return $this->keyword;
}
/**
* Returns scenario declaration line number.
*
* @return integer
*/
public function getLine()
{
return $this->line;
}
}
| Behat/Gherkin | src/Behat/Gherkin/Node/ScenarioNode.php | PHP | mit | 2,730 |
#include "../gc/GC.h"
#include "../misc/Debug.h"
#include "../misc/NativeMethod.h"
#include "../misc/Option.h"
#include "../misc/Utils.h"
#include "../runtime/JavaClass.h"
#include "../runtime/JavaHeap.hpp"
#include "../runtime/MethodArea.h"
#include "../runtime/RuntimeEnv.h"
#include "YVM.h"
YVM::ExecutorThreadPool YVM::executor;
#define FORCE(x) (reinterpret_cast<char*>(x))
// registered java native methods table, it conforms to following rule:
// {class_name,method_name,descriptor_name,function_pointer}
static const char*((nativeFunctionTable[])[4]) = {
{"ydk/lang/IO", "print", "(Ljava/lang/String;)V",
FORCE(ydk_lang_IO_print_str)},
{"ydk/lang/IO", "print", "(I)V", FORCE(ydk_lang_IO_print_I)},
{"ydk/lang/IO", "print", "(C)V", FORCE(ydk_lang_IO_print_C)},
{"java/lang/Math", "random", "()D", FORCE(java_lang_Math_random)},
{"java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_I)},
{"java/lang/StringBuilder", "append", "(C)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_C)},
{"java/lang/StringBuilder", "append", "(D)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_D)},
{"java/lang/StringBuilder", "append",
"(Ljava/lang/String;)Ljava/lang/StringBuilder;",
FORCE(java_lang_stringbuilder_append_str)},
{"java/lang/StringBuilder", "toString", "()Ljava/lang/String;",
FORCE(java_lang_stringbuilder_tostring)},
{"java/lang/Thread", "start", "()V", FORCE(java_lang_thread_start)}
};
YVM::YVM() {
#ifdef YVM_DEBUG_SHOW_SIZEOF_ALL_TYPE
Inspector::printSizeofInternalTypes();
#endif
}
// Load given class into jvm
bool YVM::loadClass(const std::string& name) {
return yrt.ma->loadJavaClass(name);
}
// link given class into jvm. A linkage exception would be occurred if given
// class not existed before linking
bool YVM::linkClass(const std::string& name) {
if (!yrt.ma->findJavaClass(name)) {
// It's not an logical endurable error, so we throw and linkage
// exception to denote it;
throw std::runtime_error(
"LinkageException: Class haven't been loaded into YVM yet!");
}
yrt.ma->linkJavaClass(name);
return true;
}
// Initialize given class.
bool YVM::initClass(Interpreter& exec, const std::string& name) {
if (!yrt.ma->findJavaClass(name)) {
// It's not an logical endurable error, so we throw and linkage
// exception to denote it;
throw std::runtime_error(
"InitializationException: Class haven't been loaded into YVM yet!");
}
yrt.ma->initClassIfAbsent(exec, name);
return true;
}
// Call java's "public static void main(String...)" method in the newly created
// main thread. It also responsible for releasing reousrces and terminating
// virtual machine after main method executing accomplished
void YVM::callMain(const std::string& name) {
executor.initialize(1);
std::future<void> mainFuture = executor.submit([=]() -> void {
#ifdef YVM_DEBUG_SHOW_THREAD_NAME
std::cout << "[Main Executing Thread] ID:" << std::this_thread::get_id()
<< "\n";
#endif
auto* jc = yrt.ma->loadClassIfAbsent(name);
yrt.ma->linkClassIfAbsent(name);
// For each execution thread, we have a code execution engine
Interpreter exec;
yrt.ma->initClassIfAbsent(exec, name);
exec.invokeByName(jc, "main", "([Ljava/lang/String;)V");
});
// Block until all sub threads accomplished its task
for (const auto& start : executor.getTaskFutures()) {
start.get();
}
// Block until main thread accomplished;
mainFuture.get();
// Close garbage collection. This is optional since operation system would
// release all resources when process exited
yrt.gc->terminateGC();
// Terminate virtual machine normally
return;
}
// Warm up yvm. This function would register native methods into jvm before
// actual code execution, and also initialize MethodArea with given java runtime
// paths, which is the core component of this jvm
void YVM::warmUp(const std::vector<std::string>& libPaths) {
int p = sizeof nativeFunctionTable / sizeof nativeFunctionTable[0];
for (int i = 0; i < p; i++) {
registerNativeMethod(
nativeFunctionTable[i][0], nativeFunctionTable[i][1],
nativeFunctionTable[i][2],
reinterpret_cast<JType* (*)(RuntimeEnv*, JType**, int)>(
const_cast<char*>(nativeFunctionTable[i][3])));
}
yrt.ma = new MethodArea(libPaths);
}
| racaljk/yvm | src/vm/YVM.cpp | C++ | mit | 4,611 |
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using PholioVisualisation.DataConstruction;
using PholioVisualisation.DataSorting;
using PholioVisualisation.PholioObjects;
namespace PholioVisualisation.DataConstructionTest
{
[TestClass]
public class ParentChildAreaRelationshipBuilderTest
{
private string parentAreaCode = "Parent";
private int childAreaId = AreaTypeIds.Pct;
private List<IArea> filteredAreas;
private List<IArea> unfilteredAreas;
[TestInitialize]
public void RunBeforeEachTest()
{
filteredAreas = new List<IArea> {
new Area { Code = "z" },
new Area { Code = "y" }
};
unfilteredAreas = new List<IArea>(filteredAreas);
unfilteredAreas.Add(new Area { Code = "a" });
}
[TestMethod]
public void TestBuild()
{
var areaListBuilder = new Mock<AreaListProvider>(MockBehavior.Strict);
areaListBuilder.Setup(x => x.CreateChildAreaList(parentAreaCode, childAreaId));
areaListBuilder.Setup(x => x.SortByOrderOrName());
areaListBuilder.SetupGet(x => x.Areas)
.Returns(unfilteredAreas);
var ignoredAreasFilter = new Mock<IgnoredAreasFilter>(MockBehavior.Strict);
// Get areas
ParentAreaWithChildAreas relationship =
new ParentChildAreaRelationshipBuilder(ignoredAreasFilter.Object, areaListBuilder.Object)
.GetParentAreaWithChildAreas(new Area { Code = parentAreaCode }, childAreaId, true);
// Verify
Assert.AreEqual(3, relationship.Children.Count());
Assert.AreEqual(parentAreaCode, relationship.Parent.Code);
areaListBuilder.VerifyAll();
}
[TestMethod]
public void TestBuild_IgnoredAreasMayBeRemoved()
{
var areaListBuilder = new Mock<AreaListProvider>();
areaListBuilder.SetupGet(x => x.Areas)
.Returns(filteredAreas);
var ignoredAreasFilter = new Mock<IgnoredAreasFilter>(MockBehavior.Strict);
ignoredAreasFilter.Setup(x => x.RemoveAreasIgnoredEverywhere(unfilteredAreas));
// Get areas
ParentAreaWithChildAreas relationship =
new ParentChildAreaRelationshipBuilder(ignoredAreasFilter.Object, areaListBuilder.Object)
.GetParentAreaWithChildAreas(new Area { Code = parentAreaCode }, childAreaId, false);
// Verify
Assert.AreEqual(2, relationship.Children.Count());
areaListBuilder.VerifyAll();
}
}
} | PublicHealthEngland/fingertips-open | PholioVisualisationWS/DataConstructionTest/ParentChildAreaRelationshipBuilderTest.cs | C# | mit | 2,757 |
package rbfs.server;
import java.net.Socket;
import java.util.List;
import com.google.gson.*;
/**
* A thread that handles an incoming connection and responds to the embedded request.
* @author James Hoak
* @version 1.0
*/
final class ConnectionHandler implements Runnable {
// TODO null check, idiot
// TODO put a protocol package with JSON parsing, validation of each message
private Socket connection;
private ConnectionHandler(Socket connection) {
this.connection = connection;
}
static ConnectionHandler make(Socket connection) {
return new ConnectionHandler(connection);
}
public void run() {
try {
// TODO
}
// TODO catch other exceptions
catch (Exception x) {
// TODO
}
}
private void handle(String requestMessage) {
JsonObject convertedMessage = (JsonObject)(new Gson().toJsonTree(requestMessage));
String req = convertedMessage.get("request").getAsString();
if (req.equals("login") || req.equals("register"))
handleLoginRequest(convertedMessage);
else
handleSessionRequest(convertedMessage);
// TODO close connection if not done?
}
private void handleLoginRequest(JsonObject msg) {
String name = msg.get("name").getAsString(),
pwd = msg.get("pwd").getAsString();
if (msg.get("request").getAsString().equals("login")) {
String validUserQuery = String.format(
"select uid from User where name = %s && pwd = %s;",
name,
pwd
);
try {
List<Object[]> userResults = DBUtils.runQuery(validUserQuery, false);
if (userResults.size() != 0) {
int uid = (Integer)(userResults.get(0)[0]);
String existingSessionQuery = String.format(
"select * from Session where uid = %d;",
uid
);
List<Object[]> sessionResults = DBUtils.runQuery(existingSessionQuery, false);
if (sessionResults.size() == 0) {
login(uid);
}
else {
// TODO send message that login failed - user already logged in
}
}
else {
// TODO send message that login failed - bad name/pwd combination
}
}
catch (DBUtils.DBException x) {
// TODO send message that we failed to login, try again later
}
}
else {
// TODO handle registration (don't login yet)
// TODO get email: String email = msg.get("email").getAsString();
}
}
private void login(int uid) throws DBUtils.DBException {
// insert the session record into the db
int[] results = DBUtils.runUpdate(String.format(
"insert into Session (uid, skey) values (%d, %x);",
uid,
DBUtils.generateSessionKey()
));
if (results[0] == 1) {
// TODO send success message with sesh key
}
else {
// TODO send failure message - user already logged in
}
}
private void handleSessionRequest(JsonObject msg) {
}
}
| jhoak/RBFS | src/rbfs/server/ConnectionHandler.java | Java | mit | 3,453 |
"use strict";
const assert = require("assert");
const Message = require("../lib/vehicle-message");
describe("vehicle-message", () => {
it("get MQTT packet and return VehicleMessage data model", () => {
const msg = Message.from({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "2016-04-30T05:41:08.915Z",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.strictEqual(msg.vehicleId, "foo");
assert.strictEqual(msg.timestamp, "2016-04-30T05:41:08.915Z");
assert.strictEqual(msg.longitude, 37.481200);
assert.strictEqual(msg.latitude, 126.948004);
});
it("validate MQTT packet to create VehicleMessage data model", () => {
const bool = Message.validate({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "invalid date",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.strictEqual(bool, false);
});
it("get MQTT packet and return null if it can't be compatible to VehicleMessage", () => {
const msg = Message.from({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "invalid date",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.strictEqual(msg, null);
});
it("JSON.stringify and parse", () => {
const msg = Message.from({
topic: "vehicle/foo",
payload: new Buffer(JSON.stringify({
timestamp: "2016-04-30T05:41:08.915Z",
longitude: 37.481200,
latitude: 126.948004
}))
});
assert.deepEqual(JSON.parse(JSON.stringify(msg)), {
vehicleId: "foo",
timestamp: "2016-04-30T05:41:08.915Z",
longitude: 37.481200,
latitude: 126.948004
});
});
}); | esmusssein/SNU-grad-proj | broker/test/vehicle-message.js | JavaScript | mit | 1,804 |
namespace NwaDg.Web.Areas.HelpPage.ModelDescriptions
{
public class CollectionModelDescription : ModelDescription
{
public ModelDescription ElementDescription { get; set; }
}
} | nwadg/nwadg-website | NwaDg.Web/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs | C# | mit | 196 |
module Memorandom
module Plugins
class URLParams < PluginTemplate
@description = "This plugin looks for interesting URL parameters and POST data"
@confidence = 0.50
# Scan takes a buffer and an offset of where this buffer starts in the source
def scan(buffer, source_offset)
buffer.scan(
/[%a-z0-9_\-=\&]*(?:sid|session|sess|user|usr|login|pass|secret|token)[%a-z0-9_\-=\&]*=[%a-z0-9_\-=&]+/mi
).each do |m|
# This may hit an earlier identical match, but thats ok
last_offset = buffer.index(m)
report_hit(:type => 'URLParams', :data => m, :offset => source_offset + last_offset)
last_offset += m.length
end
end
end
end
end
| kn0/memorandom | lib/memorandom/plugins/url_params.rb | Ruby | mit | 679 |
import re
import struct
from traitlets import Bytes, Unicode, TraitError
# reference to https://stackoverflow.com/a/385597/1338797
float_re = r'''
(?:
[-+]? # optional sign
(?:
(?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc.
|
(?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc.
)
# followed by optional exponent part if desired
(?: [Ee] [+-]? \d+ ) ?
)
'''
stl_re = r'''
solid .* \n # header
(?:
\s* facet \s normal (?: \s ''' + float_re + r''' ){3}
\s* outer \s loop
(?:
\s* vertex (?: \s ''' + float_re + r''' ){3}
){3}
\s* endloop
\s* endfacet
) + # at least 1 facet.
\s* endsolid (?: .*)?
\s* $ # allow trailing WS
'''
ascii_stl = re.compile(stl_re, re.VERBOSE)
class AsciiStlData(Unicode):
def validate(self, owner, stl):
stl = super(AsciiStlData, self).validate(owner, stl)
if ascii_stl.match(stl) is None:
raise TraitError('Given string is not valid ASCII STL data.')
return stl
class BinaryStlData(Bytes):
HEADER = 80
COUNT_SIZE = 4
FACET_SIZE = 50
def validate(self, owner, stl):
stl = super(BinaryStlData, self).validate(owner, stl)
if len(stl) < self.HEADER + self.COUNT_SIZE:
raise TraitError(
'Given bytestring is too short ({}) for Binary STL data.'
.format(len(stl))
)
(num_facets,) = struct.unpack('<I', stl[self.HEADER : self.HEADER + self.COUNT_SIZE])
expected_size = self.HEADER + self.COUNT_SIZE + num_facets * self.FACET_SIZE
if len(stl) != expected_size:
raise TraitError(
'Given bytestring has wrong length ({}) for Binary STL data. '
'For {} facets {} bytes were expected.'
.format(len(stl), num_facets, expected_size)
)
return stl
| K3D-tools/K3D-jupyter | k3d/validation/stl.py | Python | mit | 1,932 |
#ifndef LOCI_CollectionLocus
#define LOCI_CollectionLocus
#include "../core/Locus.hpp"
#include <vector>
class CollectionLocus : public Locus {
private:
protected:
std::vector<boost::any> population;
CollectionLocus();
CollectionLocus(std::vector<boost::any> population);
void setPopulation(std::vector<boost::any> population);
virtual boost::any getIndex(double index);
public:
virtual ~CollectionLocus();
virtual Gene* getGene();
virtual Gene* getGene(double index);
virtual double randomIndex();
virtual double topIndex();
virtual double bottomIndex();
virtual double closestIndex(double index);
virtual bool outOfRange(double index);
virtual bool outOfRange(Gene* index);
virtual std::string toString()=0;
virtual std::string flatten(Gene* index)=0;
virtual boost::any getIndex(Gene* index);
};
#endif
| NGTOne/libHierGA | include/loci/CollectionLocus.hpp | C++ | mit | 833 |
$(function() {
var background = chrome.extension.getBackgroundPage();
var defaultOptions = background.defaultOptions;
var options = {};
function createFrames() {
var frames = options.frames.split('\n');
$('.js-frame').remove();
for (var i = 0; i < frames.length; i++) {
var src = frames[i];
if (!src) {
continue;
}
var $frame = $(
'<div class="frame js-frame">' +
'<div class="frame-iframe-wrapper js-iframe-wrapper">' +
'<iframe frameborder="0" scrolling="no"></iframe>' +
'</div>' +
'<div class="frame-title-container">' +
'<a class="frame-title js-title" ' +
'href="' + src + '" target="_blank">' + src + '</a>' +
'</div>' +
'</div>'
);
$('.js-frames').append($frame);
src += src.indexOf('?') !== -1 ? '&' : '?';
src += 'timestamp=' + (new Date()).getTime();
$frame.find('iframe').attr('src', src);
}
resizeFrames();
}
function resizeFrames() {
var resolutionX = options.resolutionX;
var resolutionY = options.resolutionY;
var gutterWidth = 10;
var frameWidth = (
($(document).width() - options.columns * gutterWidth - gutterWidth) /
options.columns
);
var scale = frameWidth / resolutionX;
$('.js-frame').each(function() {
var $frame = $(this);
var $wrapper = $frame.find('.js-iframe-wrapper');
var $iframe = $wrapper.find('iframe');
$frame.width(frameWidth);
$wrapper.height(frameWidth * (resolutionY / resolutionX));
$iframe.css({
transform: 'scale(' + scale + ')',
});
});
}
$(window).on('resize', resizeFrames);
chrome.storage.sync.get('options', function(result) {
options = result.options || defaultOptions;
createFrames();
});
});
| laurentguilbert/overseer | js/frames.js | JavaScript | mit | 1,827 |
<div class="white-area-content">
<div class="db-header clearfix">
<div class="page-header-title"> <span class="glyphicon glyphicon-user"></span> <?php echo lang("ctn_1") ?></div>
<div class="db-header-extra">
</div>
</div>
<ol class="breadcrumb">
<li><a href="<?php echo site_url("backend/admin") ?>"><?php echo lang("ctn_2") ?></a></li>
<li><a href="<?php echo site_url("backend/admin") ?>"><?php echo lang("ctn_1") ?></a></li>
<li class="active"><?php echo lang("ctn_62") ?></li>
</ol>
<p><?php echo lang("ctn_63") ?></p>
<hr>
<table class="table table-bordered tbl">
<tr class='table-header'><td><?php echo lang("ctn_11") ?></td><td><?php echo lang("ctn_52") ?></td></tr>
<?php foreach($email_templates->result() as $r) : ?>
<tr><td><?php echo $r->title ?></td><td><a href="<?php echo site_url("backend/admin/edit_email_template/" . $r->ID) ?>" class="btn btn-warning btn-xs" title="<?php echo lang("ctn_55") ?>"><span class="glyphicon glyphicon-cog"></span></a></td></tr>
<?php endforeach; ?>
</table>
</div> | dodeagung/KLGH | application/views/admin/email_templates.php | PHP | mit | 1,032 |
class AddInfoFieldsToPhoto < ActiveRecord::Migration
def change
add_column :photos, :year, :string
add_column :photos, :place, :string
add_column :photos, :people, :text
end
end
| macool/antano | db/migrate/20140530001952_add_info_fields_to_photo.rb | Ruby | mit | 194 |
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: '12',
},
},
],
'@babel/preset-react',
],
};
| dannegm/danielgarcia | .babelrc.js | JavaScript | mit | 236 |
/*
* Module dependencies
*/
var conf = module.exports = require('nconf');
/* Last fallback : environment variables */
conf.env().argv();
/* Dev fallback : config.json */
conf.file(__dirname + '/../config.json');
/* Default values */
conf.defaults({
title: 'Meishengo',
debug: false,
port: 8000,
host: 'localhost',
gameTTL: 24 * 3600,
nickTTL: 60
});
| dawicorti/meishengo | lib/conf.js | JavaScript | mit | 372 |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.item.inventory.entity;
import org.spongepowered.api.entity.living.Human;
import org.spongepowered.api.item.inventory.types.CarriedInventory;
/**
* Represents the inventory of a Human or Player. Implementors of this interface
* guarantee that (at a minimum) the following subinventory types can be queried
* for:
*
* <ul><li>
* {@link org.spongepowered.api.item.inventory.crafting.CraftingInventory}
* </li></ul>
*/
public interface HumanInventory extends CarriedInventory<Human> {
/**
* Get the hotbar inventory.
*
* @return the hotbar
*/
Hotbar getHotbar();
}
| frogocomics/SpongeAPI | src/main/java/org/spongepowered/api/item/inventory/entity/HumanInventory.java | Java | mit | 1,889 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Sphinx configuration."""
from __future__ import print_function
import os
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Do not warn on external images.
suppress_warnings = ['image.nonlocal_uri']
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.doctest',
'sphinx.ext.extlinks',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
]
extlinks = {
'source': ('https://github.com/inveniosoftware/invenio-search-ui/tree/master/%s', 'source')
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Invenio-Search-UI'
copyright = u'2015, CERN'
author = u'CERN'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# Get the version string. Cannot be done with import!
g = {}
with open(os.path.join(os.path.dirname(__file__), '..',
'invenio_search_ui', 'version.py'),
'rt') as fp:
exec(fp.read(), g)
version = g['__version__']
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
html_theme = 'alabaster'
html_theme_options = {
'description': 'UI for Invenio-Search.',
'github_user': 'inveniosoftware',
'github_repo': 'invenio-search-ui',
'github_button': False,
'github_banner': True,
'show_powered_by': False,
'extra_nav_links': {
'invenio-search-ui@GitHub': 'https://github.com/inveniosoftware/invenio-search-ui',
'invenio-search-ui@PyPI': 'https://pypi.python.org/pypi/invenio-search-ui/',
}
}
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html',
'searchbox.html',
'donate.html',
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'invenio-search-ui_namedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'invenio-search-ui.tex', u'invenio-search-ui Documentation',
u'CERN', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'invenio-search-ui', u'invenio-search-ui Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'invenio-search-ui', u'Invenio-Search-UI Documentation',
author, 'invenio-search-ui', 'UI for Invenio-Search.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
# Autodoc configuraton.
autoclass_content = 'both'
| inveniosoftware/invenio-search-ui | docs/conf.py | Python | mit | 10,173 |
#!/usr/bin/ruby
# file: xml-to-haml.rb
require 'rexml/document'
class XMLtoHAML
include REXML
def initialize(s)
doc = Document.new(s)
@haml = xml_to_haml(doc)
end
def to_s
@haml
end
def xml_to_haml(nodex, indent ='')
buffer = nodex.elements.map do |node|
attributex = ' '
buffer = "%s" % [indent + '%' + node.name]
if node.attributes.size > 0 then
alist = Array.new(node.attributes.size)
i = 0
node.attributes.each { |x, y|
alist[i] = " :#{x} => '#{y}'"
i += 1
}
attributex = '{' + alist.join(",") + '} '
end
buffer += "%s" % [attributex + node.text] if not node.text.nil?
buffer += "\n"
buffer += xml_to_haml(node, indent + ' ')
buffer
end
buffer.join
end
end
| jrobertson/xml-to-haml | lib/xml-to-haml.rb | Ruby | mit | 832 |
<?php
namespace AppBundle\Service\Crud;
use AppBundle\Service\Crud\Exception\EntityNotFound;
/**
* @author Alexandr Sibov<cyberdelia1987@gmail.com>
*/
interface DeleteInterface
{
/**
* Remove an entity
*
* @param mixed $identity
*
* @throws EntityNotFound
*/
public function delete($identity);
} | Cyberdelia1987/symfony-test | src/AppBundle/Service/Crud/DeleteInterface.php | PHP | mit | 337 |
<?php
namespace CarBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class DefaultController extends Controller
{
/**
* @Route("/our-cars", name="offer")
*/
public function indexAction(Request $request)
{
$carRepository = $this->getDoctrine()->getRepository('CarBundle:Car');
$cars = $carRepository->findCarsWithDetails();
$form = $this->createFormBuilder()
->setMethod('GET')
->add('search', TextType::class, [
'constraints' => [
new NotBlank(),
new Length(['min' => 2])
]
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
die('form submitted');
}
return $this->render('CarBundle:Default:index.html.twig',
[
'cars' => $cars,
'form' => $form->createView()
]
);
}
/**
* @Route("/car/{id}", name="show_car")
* @param $id
* @return \Symfony\Component\HttpFoundation\Response
*/
public function showAction($id)
{
$carRepository = $this->getDoctrine()->getRepository('CarBundle:Car');
$car = $carRepository->findCarWithDetailsById($id);
return $this->render('CarBundle:Default:show.html.twig', ['car' => $car]);
}
}
| aRastini/symfonyExample | src/CarBundle/Controller/DefaultController.php | PHP | mit | 1,759 |
/**
* Author: Carter
*/
#include <iostream>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
cout << "Incorrect number of arguments\nUsage: run.out output_file.png" << endl;
return 1;
}
const int width = 1920;
const int height = 1080;
const char channels = 3;
int index;
unsigned char* data = new unsigned char[width * height * 3];
for (int y = height - 1; y >= 0; y--) {
for (int x = 0; x < width; x++) {
index = ((height - 1 - y) * width * channels) + (x * channels);
data[index] = ((float) y / (float) height) * 255; // Red channel
data[index + 1] = ((float) x / (float) width) * 255; // Green channel
data[index + 2] = 0; // Blue channel
}
}
stbi_write_png(argv[1], width, height, channels, data, width * channels);
delete[] data;
return 0;
}
| clccmh/RayTracingInOneWeekend | Ch1/src/create.cpp | C++ | mit | 921 |
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'image_zoomer'
| vdtejeda/Image_Zoomer | spec/spec_helper.rb | Ruby | mit | 82 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Closest Two Points")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Closest Two Points")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0cd3692f-8de8-4cff-ac89-9111c124369a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mkpetrov/Programming-Fundamentals-SoftUni-Jan2017 | Objects and Simple Classes/Closest Two Points/Properties/AssemblyInfo.cs | C# | mit | 1,412 |
module.exports = {
mixins: [__dirname],
fragmentsFile: '<rootDir>/fragmentTypes.json',
graphqlMockServerPath: '/graphql',
configSchema: {
fragmentsFile: {
type: 'string',
absolutePath: true,
},
graphqlSchemaFile: {
type: 'string',
absolutePath: true,
},
graphqlMockSchemaFile: {
type: 'string',
},
graphqlMockServerPath: {
type: 'string',
},
graphqlMockContextExtenderFile: {
type: 'string',
},
},
};
| xing/hops | packages/apollo-mock-server/preset.js | JavaScript | mit | 493 |
package org.jinstagram.auth.model;
public class Constants {
public static final String INSTAGRAM_OAUTH_URL_BASE = "https://api.instagram.com/oauth";
public static final String ACCESS_TOKEN_ENDPOINT = INSTAGRAM_OAUTH_URL_BASE + "/access_token";
public static final String AUTHORIZE_URL = INSTAGRAM_OAUTH_URL_BASE + "/authorize/?client_id=%s&redirect_uri=%s&response_type=code";
public static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";
}
| thesocialstation/jInstagram | src/main/java/org/jinstagram/auth/model/Constants.java | Java | mit | 470 |
# -*- coding: utf-8 -*-
"""
Send many mails
===============
Send mail to students. The script consider two columns from
one spreadsheets. The first one is about the receivers,
the second one about the customized message for each of them.
"""
#########################################
# logging et import
import os
import warnings
from pyquickhelper.loghelper import fLOG
fLOG(OutputPrint=True)
from ensae_teaching_cs.automation_students import enumerate_feedback, enumerate_send_email
import pymmails
#########################################
# On définit le contenu du mail.
cc = []
sujet = "Question de code - ENSAE 1A - projet de programmation"
col_name = None # "mail"
col_mail = "mail"
columns = ["sujet", "Question de code"]
col_group = "groupe"
delay_sending = False
test_first_mail = False # regarder le premier mail avant de les envoyer
skip = 0 # to start again after a failure
only = None
skiprows = 1
folder = os.path.normpath(os.path.abspath(os.path.join(
*([os.path.dirname(__file__)] + ([".."] * 5) + ["_data", "ecole", "ENSAE", "2017-2018", "1A_projet"]))))
student = os.path.join(folder, "ENSAE 1A - projet python.xlsx")
if not os.path.exists(student):
raise FileNotFoundError(student)
##############################
# début commun
begin = """
Bonjour,
""" + \
"""
Bonjour,
Voici les questions de code. Celles-ci sont
extraites des programmes que vous m'avez transmis.
Les noms de fonctions que j'utilise y font référence
quand je ne recopie pas le code. La réponse est souvent
liée à la performance.
""".replace("\n", " ")
#####################
# fin commune
end = """
""".replace("\n", " ") + \
"""
Xavier
"""
###################################
# Lecture des de la feuille Excel
import pandas
df = pandas.read_excel(student, sheet_name=0,
skiprows=skiprows, engine='openpyxl')
if len(df.columns) < 4:
raise ValueError("Probably an issue while reading the spreadsheet:\n{0}\n{1}".format(
df.columns, df.head()))
if len(" ".join(df.columns).split("Unnamed")) > 4:
raise ValueError("Probably an issue while reading the spreadsheet:\n{0}\n{1}".format(
df.columns, df.head()))
fLOG("shape", df.shape)
fLOG("columns", df.columns)
###################################
# mot de passe
from pyquickhelper.loghelper import get_keyword
user = get_password("gmail", "ensae_teaching_cs,user")
pwd = get_password("gmail", "ensae_teaching_cs,pwd")
###################################
# On envoie les mails.
# Le paramètre delay_sending retourne une fonction qu'il suffit d'exécuter
# pour envoyer le mail.
# Si mailbox est None, la fonction affiche les résultats mais ne fait rien.
fLOG("connect", user)
mailbox = pymmails.sender.create_smtp_server("gmail", user, pwd)
fLOG("send")
# remplacer mailbox par None pour voir le premier mail sans l'envoyer
mails = enumerate_send_email(mailbox if not test_first_mail else None,
sujet, user + "@gmail.com",
df, exc=True, fLOG=fLOG, delay_sending=delay_sending,
begin=begin, end=end, skip=skip,
cc=cc, only=only, col_group=col_group,
col_name=col_name, col_mail=col_mail,
cols=columns)
for i, m in enumerate(mails):
fLOG("------------", m)
###################################
# fin
mailbox.close()
fLOG("Done")
| sdpython/ensae_teaching_cs | _doc/examples/automation/send_mails.py | Python | mit | 3,434 |
package org.mce.teknoservice.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Spring Security success handler, specialized for Ajax requests.
*/
@Component
public class AjaxAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication)
throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
}
}
| MarcoCeccarini/teknoservice | src/main/java/org/mce/teknoservice/security/AjaxAuthenticationSuccessHandler.java | Java | mit | 881 |
from __future__ import unicode_literals
from django import template
from django.utils.html import mark_safe
from .. import conf
from ..models import Icon
register = template.Library()
@register.simple_tag
def svg_icons_icon(name, **kwargs):
filters = {'name__iexact': name}
value = ''
if kwargs.get('group'):
filters['group__name__iexact'] = kwargs.get('group')
try:
icon = Icon.objects.get(**filters)
value = icon.source
except Icon.DoesNotExist:
if conf.settings.DEBUG is True:
value = ('<span class="svg-icon-error">'
'<b>template tag svg_icons_icon: </b>'
'no icon by the name "{0}"</span>').format(name)
else:
value = ''
except Icon.MultipleObjectsReturned:
if conf.settings.DEBUG is True:
value = ('<span class="svg-icon-error">'
'<b>template tag svg_icons_icon: </b>'
'there are more than one '
'icon by the name "{0}" '
'try to use the "group" parameter</span>').format(name)
else:
icon = Icon.objects.filter(**filters)[:1].get()
value = icon.source
return mark_safe(value)
| rouxcode/django-svg-icons | svg_icons/templatetags/svg_icons_tags.py | Python | mit | 1,258 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace SoftJail.Data.Models
{
public class Mail
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string Sender { get; set; }
[Required]
[RegularExpression(@"^[A-Za-z0-9 ]+ str.$")]
public string Address { get; set; }
public int PrisonerId { get; set; }
[Required]
public Prisoner Prisoner { get; set; }
}
}
| Steffkn/SoftUni | 04.CSharpDB/02.EntityFrameworkCore/00.Exams/SoftJail/SoftJail/Data/Models/Mail.cs | C# | mit | 614 |
package com.passwordLib;
import android.content.Context;
import android.os.AsyncTask;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SendPasswordTask extends AsyncTask<Object, Void, Boolean> {
Context context;
String username;
String password;
@Override
protected Boolean doInBackground(Object... params) {
System.out.println("get args " + params[0]);
context = (Context) (params[0]);
System.out.println("get args " + params[1]);
username = (String) (params[1]);
System.out.println("get args " + params[2]);
password = (String) (params[2]);
JSch jsch = new JSch();
Session session = null;
final String SERVER = "app.smartfile.com";
final String USERNAME = PasswordFile.username;
final String PASSWORD = PasswordFile.password;
PasswordFile.saveFile();
String fileName = PasswordFile.fileName;
try {
session = jsch.getSession(USERNAME, SERVER, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(PASSWORD);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put(context.getFilesDir() + "/" + fileName, fileName);
sftpChannel.exit();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
// do nothing
}
}
| aarongolliver/SmartPass | src/com/passwordLib/SendPasswordTask.java | Java | mit | 1,660 |
class ValidateAddReminderDayOfMonthAndDeadlineDayOfMonth < ActiveRecord::Migration[6.1]
def change
validate_check_constraint :partner_groups, name: "deadline_day_of_month_check"
validate_check_constraint :partner_groups, name: "reminder_day_of_month_check"
validate_check_constraint :partner_groups, name: "reminder_day_of_month_and_deadline_day_of_month_check"
end
end
| rubyforgood/diaper | db/migrate/20220103232639_validate_add_reminder_day_of_month_and_deadline_day_of_month.rb | Ruby | mit | 386 |
import {
CHOOSE_MEMORY,
LOAD_PHOTO_ERROR,
LOAD_PHOTO_SUCCESS,
} from './constants';
export function chooseMemory({ id, index }) {
return {
type: CHOOSE_MEMORY,
id,
index,
};
}
export function photoLoadSuccess({
host,
gallery,
setCurrentMemory,
album,
id,
photoLink,
}) {
return {
type: LOAD_PHOTO_SUCCESS,
id,
photoLink,
setCurrentMemory,
host,
gallery,
album,
};
}
export function photoLoadError(error, filename) {
return {
type: LOAD_PHOTO_ERROR,
filename,
error,
};
}
| danactive/history | ui/app/containers/App/actions.js | JavaScript | mit | 556 |
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0xa4d6fc138e2ab2fa649e97472c481009f6761548cbf7d86a14ca0ddc1e74203c"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1479129701, // * UNIX timestamp of last checkpoint block
1, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
120.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0xe900c15110857ca650625825761b00381699ef41451915468b1488644295671a"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1398863062,
1,
960.0
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
| wrapperproject/wrapper | src/checkpoints.cpp | C++ | mit | 5,010 |
function saveUser({state, input}) {
state.set(['user', 'user'], input.user);
state.set(['session', 'jwt'], input.jwt);
}
export default saveUser;
| testpackbin/testpackbin | app/modules/home/actions/saveUser.js | JavaScript | mit | 151 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zm-2 5.79V18h-3.52L12 20.48 9.52 18H6v-3.52L3.52 12 6 9.52V6h3.52L12 3.52 14.48 6H18v3.52L20.48 12 18 14.48zM12 6.5c-3.03 0-5.5 2.47-5.5 5.5s2.47 5.5 5.5 5.5 5.5-2.47 5.5-5.5-2.47-5.5-5.5-5.5zm0 9c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z" /><circle cx="12" cy="12" r="2" /></React.Fragment>
, 'Brightness7Outlined');
| kybarg/material-ui | packages/material-ui-icons/src/Brightness7Outlined.js | JavaScript | mit | 593 |
'use strict';
// Listens for the app launching then creates the window
chrome.app.runtime.onLaunched.addListener(function() {
var width = 600;
var height = 400;
chrome.app.window.create('index.html', {
id: 'main',
bounds: {
width: width,
height: height,
left: Math.round((screen.availWidth - width) / 2),
top: Math.round((screen.availHeight - height)/2)
}
});
});
| yogiekurniawan/JayaMekar-ChromeApp | app/scripts/main.js | JavaScript | mit | 454 |
var lint = require('mocha-eslint');
var paths = [
'src',
];
var options = {
// Note: we saw timeouts with the 2000ms mocha timeout setting,
// thus raised to 5000ms for eslint
timeout: 5000, // Defaults to the global mocha `timeout` option
};
// Run the tests
lint(paths, options); | iulia0103/taste-of-code | linter.js | JavaScript | mit | 293 |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
/// Structure containing callback function pointers for memory allocation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct AllocationCallbacks
{
/// <summary>
/// A value to be interpreted by the implementation of the callbacks.
/// When any of the callbacks in AllocationCallbacks are called, the
/// Vulkan implementation will pass this value as the first parameter
/// to the callback. This value can vary each time an allocator is
/// passed into a command, even when the same object takes an allocator
/// in multiple commands.
/// </summary>
public IntPtr? UserData
{
get;
set;
}
/// <summary>
/// An application-defined memory allocation function of type
/// AllocationFunction.
/// </summary>
public SharpVk.AllocationFunctionDelegate Allocation
{
get;
set;
}
/// <summary>
/// An application-defined memory reallocation function of type
/// ReallocationFunction.
/// </summary>
public SharpVk.ReallocationFunctionDelegate Reallocation
{
get;
set;
}
/// <summary>
/// An application-defined memory free function of type FreeFunction.
/// </summary>
public SharpVk.FreeFunctionDelegate Free
{
get;
set;
}
/// <summary>
/// An application-defined function that is called by the
/// implementation when the implementation makes internal allocations,
/// and it is of type InternalAllocationNotification.
/// </summary>
public SharpVk.InternalAllocationNotificationDelegate InternalAllocation
{
get;
set;
}
/// <summary>
/// An application-defined function that is called by the
/// implementation when the implementation frees internal allocations,
/// and it is of type InternalFreeNotification.
/// </summary>
public SharpVk.InternalFreeNotificationDelegate InternalFree
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.AllocationCallbacks* pointer)
{
if (this.UserData != null)
{
pointer->UserData = this.UserData.Value.ToPointer();
}
else
{
pointer->UserData = default(void*);
}
pointer->Allocation = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.Allocation);
pointer->Reallocation = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.Reallocation);
pointer->Free = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.Free);
pointer->InternalAllocation = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.InternalAllocation);
pointer->InternalFree = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(this.InternalFree);
}
}
}
| FacticiusVir/SharpVk | src/SharpVk/AllocationCallbacks.gen.cs | C# | mit | 4,718 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Urals Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet_ismine.h"
#include "key.h"
#include "keystore.h"
#include "script/script.h"
#include "script/standard.h"
#include "script/sign.h"
#include <boost/foreach.hpp>
using namespace std;
typedef vector<unsigned char> valtype;
unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
{
unsigned int nResult = 0;
BOOST_FOREACH(const valtype& pubkey, pubkeys)
{
CKeyID keyID = CPubKey(pubkey).GetID();
if (keystore.HaveKey(keyID))
++nResult;
}
return nResult;
}
isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
{
CScript script = GetScriptForDestination(dest);
return IsMine(keystore, script);
}
isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions)) {
if (keystore.HaveWatchOnly(scriptPubKey))
return ISMINE_WATCH_UNSOLVABLE;
return ISMINE_NO;
}
CKeyID keyID;
switch (whichType)
{
case TX_NONSTANDARD:
case TX_NULL_DATA:
break;
case TX_PUBKEY:
keyID = CPubKey(vSolutions[0]).GetID();
if (keystore.HaveKey(keyID))
return ISMINE_SPENDABLE;
break;
case TX_PUBKEYHASH:
keyID = CKeyID(uint160(vSolutions[0]));
if (keystore.HaveKey(keyID))
return ISMINE_SPENDABLE;
break;
case TX_SCRIPTHASH:
{
CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
CScript subscript;
if (keystore.GetCScript(scriptID, subscript)) {
isminetype ret = IsMine(keystore, subscript);
if (ret == ISMINE_SPENDABLE)
return ret;
}
break;
}
case TX_MULTISIG:
{
// Only consider transactions "mine" if we own ALL the
// keys involved. Multi-signature transactions that are
// partially owned (somebody else has a key that can spend
// them) enable spend-out-from-under-you attacks, especially
// in shared-wallet situations.
vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
if (HaveKeys(keys, keystore) == keys.size())
return ISMINE_SPENDABLE;
break;
}
}
if (keystore.HaveWatchOnly(scriptPubKey)) {
// TODO: This could be optimized some by doing some work after the above solver
CScript scriptSig;
return ProduceSignature(DummySignatureCreator(&keystore), scriptPubKey, scriptSig) ? ISMINE_WATCH_SOLVABLE : ISMINE_WATCH_UNSOLVABLE;
}
return ISMINE_NO;
}
| JohnMnemonick/UralsCoin | src/wallet/wallet_ismine.cpp | C++ | mit | 2,907 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Identity_service {
private $ci;
public function __construct()
{
// to load ci instance
$this->ci =& get_instance();
}
public function set($User)
{
if(isset($User['id']) && isset($User['role']))
{
$this->ci->session->set_userdata('id', $User['id']);
$this->ci->session->set_userdata('role', $User['role']);
}
}
public function get()
{
}
public function destroy()
{
}
public function get_id()
{
return $this->ci->session->userdata('id');
}
public function get_role()
{
return $this->ci->session->userdata('role');
}
public function validate_role($type)
{
if($this->ci->session->userdata('role') === $type)
{
return true;
}
else
{
redirect('login');
}
}
} | trisetiobr/labscheduler | application/libraries/services/Identity_service.php | PHP | mit | 799 |
using System;
namespace Agiil.Domain
{
public interface IIndictesSuccess
{
bool IsSuccess { get; }
}
}
| csf-dev/agiil | Agiil.Domain/IIndictesSuccess.cs | C# | mit | 116 |
var express = require('express');
var router = express.Router();
var fs = require('fs');
var instasync = require('instasync');
var helpers = instasync.helpers;
var queries = helpers.queries;
//set Content type
router.use(function(req,res,next){
res.header("Content-Type", "text/html");
res.header("X-Frame-Options","DENY");
next();
});
router.param('room_name', function(req,res, next, room_name){
queries.getRoom(room_name).then(function(room){
if (!room){
var error = new Error("Room not found.");
error.status = 404;
throw error;
}
req.room = room;
return req.db("rooms").where("room_id",'=',room.room_id).increment("visits", 1);
}).then(function(){
next();
}).catch(function(err){
return next(err);
});
});
router.get('/:room_name', function(req, res, next) {
res.render('rooms/index', {
title: 'InstaSync - '+req.room.room_name+"'s room!",
room: req.room
}, function(err,html){ //not sure this is needed
if(err) {
next(err);
} else {
res.end(html);
}
});
});
module.exports = router;
| Mewte/InstaSync | web/routes/rooms.js | JavaScript | mit | 1,039 |
<?php
namespace ORM\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* GdConfigurations
*
* @ORM\Table(name="gd_configurations")
* @ORM\Entity
*/
class GdConfigurations
{
/**
* @var integer
*
* @ORM\Column(name="configuration_id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $configurationId;
/**
* @var string
*
* @ORM\Column(name="status", type="string", nullable=false)
*/
private $status;
/**
* @var \DateTime
*
* @ORM\Column(name="date_created", type="datetime", nullable=false)
*/
private $dateCreated;
/**
* @var \DateTime
*
* @ORM\Column(name="last_updated", type="datetime", nullable=false)
*/
private $lastUpdated;
/**
* @var integer
*
* @ORM\Column(name="account_id", type="integer", nullable=false)
*/
private $accountId;
/**
* @var string
*
* @ORM\Column(name="configuration_name", type="string", length=100, nullable=false)
*/
private $configurationName;
/**
* @var string
*
* @ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* @var integer
*
* @ORM\Column(name="num_rows_generated", type="integer", nullable=true)
*/
private $numRowsGenerated = '0';
/**
* Get configurationId
*
* @return integer
*/
public function getConfigurationId()
{
return $this->configurationId;
}
/**
* Set status
*
* @param string $status
* @return GdConfigurations
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set dateCreated
*
* @param \DateTime $dateCreated
* @return GdConfigurations
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* @return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Set lastUpdated
*
* @param \DateTime $lastUpdated
* @return GdConfigurations
*/
public function setLastUpdated($lastUpdated)
{
$this->lastUpdated = $lastUpdated;
return $this;
}
/**
* Get lastUpdated
*
* @return \DateTime
*/
public function getLastUpdated()
{
return $this->lastUpdated;
}
/**
* Set accountId
*
* @param integer $accountId
* @return GdConfigurations
*/
public function setAccountId($accountId)
{
$this->accountId = $accountId;
return $this;
}
/**
* Get accountId
*
* @return integer
*/
public function getAccountId()
{
return $this->accountId;
}
/**
* Set configurationName
*
* @param string $configurationName
* @return GdConfigurations
*/
public function setConfigurationName($configurationName)
{
$this->configurationName = $configurationName;
return $this;
}
/**
* Get configurationName
*
* @return string
*/
public function getConfigurationName()
{
return $this->configurationName;
}
/**
* Set content
*
* @param string $content
* @return GdConfigurations
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set numRowsGenerated
*
* @param integer $numRowsGenerated
* @return GdConfigurations
*/
public function setNumRowsGenerated($numRowsGenerated)
{
$this->numRowsGenerated = $numRowsGenerated;
return $this;
}
/**
* Get numRowsGenerated
*
* @return integer
*/
public function getNumRowsGenerated()
{
return $this->numRowsGenerated;
}
}
| Barbar76/ExpTech-PHP | src/ORM/MainBundle/Entity/GdConfigurations.php | PHP | mit | 4,351 |
#ifndef AWTIMETABLE_HPP
#define AWTIMETABLE_HPP
#include <string>
#include <vector>
#include <SFML/Graphics/Font.hpp>
namespace sf
{
class RenderWindow;
}
namespace aw
{
namespace priv
{
struct Player
{
std::string name;
float time;
sf::Color color;
Player() : Player("", 0, sf::Color::White)
{}
Player(const std::string &pName, float pTime, const sf::Color &pColor):
name(pName), time(pTime), color(pColor)
{
}
};
}
class TimeTable
{
public:
TimeTable();
void addPlayer(const std::string &name, float time, const sf::Color &color);
void removePlayer(const std::string &name);
void removePlayer(std::size_t index);
void addTime(const std::string &name, float time);
void addTime(std::size_t index, float time);
void addLadderTime(const std::string &name, float time);
void clearLadder();
void resetTimes();
void render(sf::RenderWindow &window);
void clear();
std::size_t getPlayerIndex(const std::string &name);
float getTime(std::size_t index);
private:
void orderTimeTable();
private:
std::vector<priv::Player> m_currentHighscore;
std::vector<priv::Player> m_ladder;
sf::Font m_font;
};
}
#endif | AlexAUT/Kroniax_Cpp | include/modules/game/timeTable.hpp | C++ | mit | 1,196 |
package ordering;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class OrderingExamples {
private CidadeByPopulacao cidadeByPopulacao;
private CidadeByImpostos cidadeByImpostos;
@Before
public void setUp() throws Exception {
cidadeByPopulacao = new CidadeByPopulacao();
cidadeByImpostos = new CidadeByImpostos();
}
@Test
public void ordena_pela_populacao_reverse() throws Exception {
Cidade cidade1 = new Cidade(11000, 55.0);
Cidade cidade2 = new Cidade(8000, 45.0);
Cidade cidade3 = new Cidade(10000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> reverse = Ordering.from(cidadeByPopulacao).reverse();
Collections.sort(cidades, reverse);
assertThat(cidades.get(0), is(cidade1));
}
@Test
public void oredenacao_composta() {
Cidade cidade1 = new Cidade(10000, 55.0);
Cidade cidade2 = new Cidade(10000, 45.0);
Cidade cidade3 = new Cidade(10000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> composto = Ordering.from(cidadeByPopulacao).compound(cidadeByImpostos);
Collections.sort(cidades, composto);
assertThat(cidades.get(0), is(cidade3));
}
@Test
public void greatestOf() {
Cidade cidade1 = new Cidade(10000, 55.0);
Cidade cidade2 = new Cidade(9000, 45.0);
Cidade cidade3 = new Cidade(8000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> byPopulation = Ordering.from(cidadeByPopulacao);
List<Cidade> greatestPopulations = byPopulation.greatestOf(cidades, 2);
assertThat(greatestPopulations.size(), is(2));
assertThat(greatestPopulations.get(0), is(cidade1));
assertThat(greatestPopulations.get(1), is(cidade2));
}
@Test
public void leastOf() {
Cidade cidade1 = new Cidade(10000, 55.0);
Cidade cidade2 = new Cidade(9000, 45.0);
Cidade cidade3 = new Cidade(8000, 33.8);
List<Cidade> cidades = Lists.newArrayList(cidade1, cidade2, cidade3);
Ordering<Cidade> byPopulation = Ordering.from(cidadeByPopulacao);
List<Cidade> greatestPopulations = byPopulation.leastOf(cidades, 2);
assertThat(greatestPopulations.size(), is(2));
assertThat(greatestPopulations.get(0), is(cidade3));
assertThat(greatestPopulations.get(1), is(cidade2));
}
}
| alexrios/guava-labs | src/test/java/ordering/OrderingExamples.java | Java | mit | 2,760 |
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '2=ejgw$ytij5oh#i$eeg237okk8m3nkm@5a!j%&1(s2j7yl2xm'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'auth_functional.RequestFixtureMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = ''
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'tests/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'django_paginator_ext',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| anler/django-paginator-ext | tests/settings.py | Python | mit | 5,356 |
/**
* body-checker
* A simple tool to protect your API against bad request parameters
*
* @param {Object} body request body
* @param {Object} options configuration parmaters
* @param {Function} cb callback function
*
*/
var check = require('check-types');
module.exports = function(body, options, cb) {
var valid_keys = Object.keys(options);
// Ensure all passed params are legal
for(var p in body) {
if(valid_keys.indexOf(p) === -1) {
return cb(new Error('Illegal parameter "' + p + '" provided'));
}
}
for(var key in options) {
// Check for Required
if(options[key].required && !body[key]) {
switch(options[key].type) {
case 'number':
case 'integer':
if(check.zero(body[key])) break;
default:
return cb(new Error('Missing required parameter ' + key));
}
}
// Optional default handler
if(!options[key].required && !body[key] && options[key].default) {
body[key] = options[key].default;
}
if (check[options[key].type](body[key]) === false) {
// Check types for all but "any" allow undefined properties when not required
if (body[key] === undefined && !options[key].required) {
// skip when key is not present and is not required
} else {
if(options[key].type !== 'any') {
return cb(new Error('Expected "' + key + '" to be type ' + options[key].type + ', instead found ' + typeof body[key]));
}
}
}
}
// All is good
return cb(null, body);
};
| luceracloud/body-checker | index.js | JavaScript | mit | 1,461 |
using System.Linq;
namespace Powercards.Core.Cards
{
[CardInfo(CardSet.Intrigue, 5, true)]
public class Upgrade : CardBase, IActionCard
{
#region methods
public void Play(TurnContext context)
{
context.ActivePlayer.DrawCards(1, context);
context.RemainingActions += 1;
if (!context.ActivePlayer.Hand.IsEmpty)
{
var trashCard = context.Game.Dialog.Select(context, context.ActivePlayer, context.ActivePlayer.Hand,
new CountValidator<ICard>(1), "Select a card to Upgrade.").Single();
if (trashCard.MoveTo(context.ActivePlayer.Hand, context.Game.TrashZone, CardMovementVerb.Trash, context))
context.Game.Log.LogTrash(context.ActivePlayer, trashCard);
var costOfCardToGain = trashCard.GetCost(context, context.ActivePlayer) + 1;
var pilesToGain = context.Game.Supply.AllPiles.Where(new NonEmptyPileValidator().Then(new CardCostValidator(context, context.ActivePlayer, costOfCardToGain)).Validate).ToArray();
if (pilesToGain.Length > 0)
{
var gainPile = context.Game.Dialog.Select(context, context.ActivePlayer, pilesToGain,
new CountValidator<CardSupplyPile>(1),
string.Format("Select a card to gain of exact cost of {0}", costOfCardToGain)).Single();
if (gainPile.TopCard.MoveTo(gainPile, context.ActivePlayer.DiscardArea, CardMovementVerb.Gain, context))
context.Game.Log.LogGain(context.ActivePlayer, gainPile);
}
else
{
context.Game.Log.LogMessage("{0} could gain no card of appropriate cost", context.ActivePlayer);
}
}
else
{
context.Game.Log.LogMessage(context.ActivePlayer.Name + " did not have any cards to upgrade.");
}
}
#endregion
}
}
| whence/powerlife | csharp/Core/Cards/Upgrade.cs | C# | mit | 2,052 |
require 'spec_helper'
describe Chouette::Exporter, :type => :model do
subject { Chouette::Exporter.new("test") }
describe "#export" do
let(:chouette_command) { double :run! => true }
before(:each) do
allow(subject).to receive_messages :chouette_command => chouette_command
end
it "should use specified file in -outputFile option" do
expect(chouette_command).to receive(:run!).with(hash_including(:output_file => File.expand_path('file')))
subject.export "file"
end
it "should use specified format in -format option" do
expect(chouette_command).to receive(:run!).with(hash_including(:format => 'DUMMY'))
subject.export "file", :format => "dummy"
end
end
end
| afimb/ninoxe | spec/models/chouette/exporter_spec.rb | Ruby | mit | 739 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ServiceFabric::V6_2_0_9
module Models
#
# Describes how the scaling should be performed
#
class ScalingPolicyDescription
include MsRestAzure
# @return [ScalingTriggerDescription] Specifies the trigger associated
# with this scaling policy
attr_accessor :scaling_trigger
# @return [ScalingMechanismDescription] Specifies the mechanism
# associated with this scaling policy
attr_accessor :scaling_mechanism
#
# Mapper for ScalingPolicyDescription class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ScalingPolicyDescription',
type: {
name: 'Composite',
class_name: 'ScalingPolicyDescription',
model_properties: {
scaling_trigger: {
client_side_validation: true,
required: true,
serialized_name: 'ScalingTrigger',
type: {
name: 'Composite',
polymorphic_discriminator: 'Kind',
uber_parent: 'ScalingTriggerDescription',
class_name: 'ScalingTriggerDescription'
}
},
scaling_mechanism: {
client_side_validation: true,
required: true,
serialized_name: 'ScalingMechanism',
type: {
name: 'Composite',
polymorphic_discriminator: 'Kind',
uber_parent: 'ScalingMechanismDescription',
class_name: 'ScalingMechanismDescription'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | data/azure_service_fabric/lib/6.2.0.9/generated/azure_service_fabric/models/scaling_policy_description.rb | Ruby | mit | 2,007 |
/// <reference path="0-bosun.ts" />
bosunApp.directive('tsResults', function() {
return {
templateUrl: '/partials/results.html',
link: (scope: any, elem, attrs) => {
scope.isSeries = v => {
return typeof (v) === 'object';
};
},
};
});
bosunApp.directive('tsComputations', () => {
return {
scope: {
computations: '=tsComputations',
time: '=',
header: '=',
},
templateUrl: '/partials/computations.html',
link: (scope: any, elem: any, attrs: any) => {
if (scope.time) {
var m = moment.utc(scope.time);
scope.timeParam = "&date=" + encodeURIComponent(m.format("YYYY-MM-DD")) + "&time=" + encodeURIComponent(m.format("HH:mm"));
}
scope.btoa = (v: any) => {
return encodeURIComponent(btoa(v));
};
},
};
});
function fmtDuration(v: any) {
var diff = moment.duration(v, 'milliseconds');
var f;
if (Math.abs(v) < 60000) {
return diff.format('ss[s]');
}
return diff.format('d[d]hh[h]mm[m]ss[s]');
}
function fmtTime(v: any) {
var m = moment(v).utc();
var now = moment().utc();
var msdiff = now.diff(m);
var ago = '';
var inn = '';
if (msdiff >= 0) {
ago = ' ago';
} else {
inn = 'in ';
}
return m.format() + ' (' + inn + fmtDuration(msdiff) + ago + ')';
}
function parseDuration(v: string) {
var pattern = /(\d+)(d|y|n|h|m|s)-ago/;
var m = pattern.exec(v);
return moment.duration(parseInt(m[1]), m[2].replace('n', 'M'))
}
interface ITimeScope extends IBosunScope {
noLink: string;
}
bosunApp.directive("tsTime", function() {
return {
link: function(scope: ITimeScope, elem: any, attrs: any) {
scope.$watch(attrs.tsTime, (v: any) => {
var m = moment(v).utc();
var text = fmtTime(v);
if (attrs.tsEndTime) {
var diff = moment(scope.$eval(attrs.tsEndTime)).diff(m);
var duration = fmtDuration(diff);
text += " for " + duration;
}
if (attrs.noLink) {
elem.text(text);
} else {
var el = document.createElement('a');
el.text = text;
el.href = 'http://www.timeanddate.com/worldclock/converted.html?iso=';
el.href += m.format('YYYYMMDDTHHmm');
el.href += '&p1=0';
angular.forEach(scope.timeanddate, (v, k) => {
el.href += '&p' + (k + 2) + '=' + v;
});
elem.html(el);
}
});
},
};
});
bosunApp.directive("tsTimeUnix", function() {
return {
link: function(scope: ITimeScope, elem: any, attrs: any) {
scope.$watch(attrs.tsTimeUnix, (v: any) => {
var m = moment(v * 1000).utc();
var text = fmtTime(m);
if (attrs.tsEndTime) {
var diff = moment(scope.$eval(attrs.tsEndTime)).diff(m);
var duration = fmtDuration(diff);
text += " for " + duration;
}
if (attrs.noLink) {
elem.text(text);
} else {
var el = document.createElement('a');
el.text = text;
el.href = 'http://www.timeanddate.com/worldclock/converted.html?iso=';
el.href += m.format('YYYYMMDDTHHmm');
el.href += '&p1=0';
angular.forEach(scope.timeanddate, (v, k) => {
el.href += '&p' + (k + 2) + '=' + v;
});
elem.html(el);
}
});
},
};
});
bosunApp.directive("tsSince", function() {
return {
link: function(scope: IBosunScope, elem: any, attrs: any) {
scope.$watch(attrs.tsSince, (v: any) => {
var m = moment(v).utc();
elem.text(m.fromNow());
});
},
};
});
bosunApp.directive("tooltip", function() {
return {
link: function(scope: IGraphScope, elem: any, attrs: any) {
angular.element(elem[0]).tooltip({ placement: "bottom" });
},
};
});
bosunApp.directive('tsTab', () => {
return {
link: (scope: any, elem: any, attrs: any) => {
var ta = elem[0];
elem.keydown(evt => {
if (evt.ctrlKey) {
return;
}
// This is so shift-enter can be caught to run a rule when tsTab is called from
// the rule page
if (evt.keyCode == 13 && evt.shiftKey) {
return;
}
switch (evt.keyCode) {
case 9: // tab
evt.preventDefault();
var v = ta.value;
var start = ta.selectionStart;
ta.value = v.substr(0, start) + "\t" + v.substr(start);
ta.selectionStart = ta.selectionEnd = start + 1;
return;
case 13: // enter
if (ta.selectionStart != ta.selectionEnd) {
return;
}
evt.preventDefault();
var v = ta.value;
var start = ta.selectionStart;
var sub = v.substr(0, start);
var last = sub.lastIndexOf("\n") + 1
for (var i = last; i < sub.length && /[ \t]/.test(sub[i]); i++)
;
var ws = sub.substr(last, i - last);
ta.value = v.substr(0, start) + "\n" + ws + v.substr(start);
ta.selectionStart = ta.selectionEnd = start + 1 + ws.length;
}
});
},
};
});
interface JQuery {
tablesorter(v: any): JQuery;
linedtextarea(): void;
}
bosunApp.directive('tsresizable', () => {
return {
restrict: 'A',
scope: {
callback: '&onResize'
},
link: function postLink(scope: any, elem: any, attrs) {
elem.resizable();
elem.on('resizestop', function(evt, ui) {
if (scope.callback) { scope.callback(); }
});
}
};
});
bosunApp.directive('tsTableSort', ['$timeout', ($timeout: ng.ITimeoutService) => {
return {
link: (scope: ng.IScope, elem: any, attrs: any) => {
$timeout(() => {
$(elem).tablesorter({
sortList: scope.$eval(attrs.tsTableSort),
});
});
},
};
}]);
// https://gist.github.com/mlynch/dd407b93ed288d499778
bosunApp.directive('autofocus', ['$timeout', function($timeout) {
return {
restrict: 'A',
link : function($scope, $element) {
$timeout(function() {
$element[0].focus();
});
}
}
}]);
bosunApp.directive('tsTimeLine', () => {
var tsdbFormat = d3.time.format.utc("%Y/%m/%d-%X");
function parseDate(s: any) {
return moment.utc(s).toDate();
}
var margin = {
top: 10,
right: 10,
bottom: 30,
left: 250,
};
return {
link: (scope: any, elem: any, attrs: any) => {
scope.shown = {};
scope.collapse = (i: any, entry: any, v: any) => {
scope.shown[i] = !scope.shown[i];
if (scope.loadTimelinePanel && entry && scope.shown[i]) {
scope.loadTimelinePanel(entry, v);
}
};
scope.$watch('alert_history', update);
function update(history: any) {
if (!history) {
return;
}
var entries = d3.entries(history);
if (!entries.length) {
return;
}
entries.sort((a, b) => {
return a.key.localeCompare(b.key);
});
scope.entries = entries;
var values = entries.map(v => { return v.value });
var keys = entries.map(v => { return v.key });
var barheight = 500 / values.length;
barheight = Math.min(barheight, 45);
barheight = Math.max(barheight, 15);
var svgHeight = values.length * barheight + margin.top + margin.bottom;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth = elem.width();
var width = svgWidth - margin.left - margin.right;
var xScale = d3.time.scale.utc().range([0, width]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom');
elem.empty();
var svg = d3.select(elem[0])
.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.append('g')
.attr('class', 'x axis tl-axis')
.attr('transform', 'translate(0,' + height + ')');
xScale.domain([
d3.min(values, (d: any) => { return d3.min(d.History, (c: any) => { return parseDate(c.Time); }); }),
d3.max(values, (d: any) => { return d3.max(d.History, (c: any) => { return parseDate(c.EndTime); }); }),
]);
var legend = d3.select(elem[0])
.append('div')
.attr('class', 'tl-legend');
var time_legend = legend
.append('div')
.text(values[0].History[0].Time);
var alert_legend = legend
.append('div')
.text(keys[0]);
svg.select('.x.axis')
.transition()
.call(xAxis);
var chart = svg.append('g');
angular.forEach(entries, function(entry: any, i: number) {
chart.selectAll('.bars')
.data(entry.value.History)
.enter()
.append('rect')
.attr('class', (d: any) => { return 'tl-' + d.Status; })
.attr('x', (d: any) => { return xScale(parseDate(d.Time)); })
.attr('y', i * barheight)
.attr('height', barheight)
.attr('width', (d: any) => {
return xScale(parseDate(d.EndTime)) - xScale(parseDate(d.Time));
})
.on('mousemove.x', mousemove_x)
.on('mousemove.y', function(d) {
alert_legend.text(entry.key);
})
.on('click', function(d, j) {
var id = 'panel' + i + '-' + j;
scope.shown['group' + i] = true;
scope.shown[id] = true;
if (scope.loadTimelinePanel) {
scope.loadTimelinePanel(entry, d);
}
scope.$apply();
setTimeout(() => {
var e = $("#" + id);
if (!e) {
console.log('no', id, e);
return;
}
$('html, body').scrollTop(e.offset().top);
});
});
});
chart.selectAll('.labels')
.data(keys)
.enter()
.append('text')
.attr('text-anchor', 'end')
.attr('x', 0)
.attr('dx', '-.5em')
.attr('dy', '.25em')
.attr('y', function(d: any, i: number) { return (i + .5) * barheight; })
.text(function(d: any) { return d; });
chart.selectAll('.sep')
.data(values)
.enter()
.append('rect')
.attr('y', function(d: any, i: number) { return (i + 1) * barheight })
.attr('height', 1)
.attr('x', 0)
.attr('width', width)
.on('mousemove.x', mousemove_x);
function mousemove_x() {
var x = xScale.invert(d3.mouse(this)[0]);
time_legend
.text(tsdbFormat(x));
}
};
},
};
});
var fmtUnits = ['', 'k', 'M', 'G', 'T', 'P', 'E'];
function nfmt(s: any, mult: number, suffix: string, opts: any) {
opts = opts || {};
var n = parseFloat(s);
if (isNaN(n) && typeof s === 'string') {
return s;
}
if (opts.round) n = Math.round(n);
if (!n) return suffix ? '0 ' + suffix : '0';
if (isNaN(n) || !isFinite(n)) return '-';
var a = Math.abs(n);
if (a >= 1) {
var number = Math.floor(Math.log(a) / Math.log(mult));
a /= Math.pow(mult, Math.floor(number));
if (fmtUnits[number]) {
suffix = fmtUnits[number] + suffix;
}
}
var r = a.toFixed(5);
if (a < 1e-5) {
r = a.toString();
}
var neg = n < 0 ? '-' : '';
return neg + (+r) + suffix;
}
bosunApp.filter('nfmt', function() {
return function(s: any) {
return nfmt(s, 1000, '', {});
}
});
bosunApp.filter('bytes', function() {
return function(s: any) {
return nfmt(s, 1024, 'B', { round: true });
}
});
bosunApp.filter('bits', function() {
return function(s: any) {
return nfmt(s, 1024, 'b', { round: true });
}
});
bosunApp.directive('elastic', [
'$timeout',
function($timeout) {
return {
restrict: 'A',
link: function($scope, element) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function() {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);
bosunApp.directive('tsBar', ['$window', 'nfmtFilter', function($window: ng.IWindowService, fmtfilter: any) {
var margin = {
top: 20,
right: 20,
bottom: 0,
left: 200,
};
return {
scope: {
data: '=',
height: '=',
},
link: (scope: any, elem: any, attrs: any) => {
var svgHeight = +scope.height || 150;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth: number;
var width: number;
var xScale = d3.scale.linear();
var yScale = d3.scale.ordinal()
var top = d3.select(elem[0])
.append('svg')
.attr('height', svgHeight)
.attr('width', '100%');
var svg = top
.append('g')
//.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("top")
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
scope.$watch('data', update);
var w = angular.element($window);
scope.$watch(() => {
return w.width();
}, resize, true);
w.bind('resize', () => {
scope.$apply();
});
function resize() {
if (!scope.data) {
return;
}
svgWidth = elem.width();
if (svgWidth <= 0) {
return;
}
margin.left = d3.max(scope.data, (d: any) => { return d.name.length * 8 })
width = svgWidth - margin.left - margin.right;
svgHeight = scope.data.length * 15;
height = svgHeight - margin.top - margin.bottom;
xScale.range([0, width]);
yScale.rangeRoundBands([0, height], .1);
yAxis.scale(yScale);
svg.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.attr('width', svgWidth);
svg.attr('height', height);
top.attr('height', svgHeight);
xAxis.ticks(width / 60);
draw();
}
function update(v: any) {
if (!angular.isArray(v) || v.length == 0) {
return;
}
resize();
}
function draw() {
if (!scope.data) {
return;
}
yScale.domain(scope.data.map((d: any) => { return d.name }));
xScale.domain([0, d3.max(scope.data, (d: any) => { return d.Value })]);
svg.selectAll('g.axis').remove();
//X axis
svg.append("g")
.attr("class", "x axis")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll("text")
.style("text-anchor", "end")
var bars = svg.selectAll(".bar").data(scope.data);
bars.enter()
.append("rect")
.attr("class", "bar")
.attr("y", function(d) { return yScale(d.name); })
.attr("height", yScale.rangeBand())
.attr('width', (d: any) => { return xScale(d.Value); })
};
},
};
}]);
bosunApp.directive('tsGraph', ['$window', 'nfmtFilter', function($window: ng.IWindowService, fmtfilter: any) {
var margin = {
top: 10,
right: 10,
bottom: 30,
left: 80,
};
return {
scope: {
data: '=',
annotations: '=',
height: '=',
generator: '=',
brushStart: '=bstart',
brushEnd: '=bend',
enableBrush: '@',
max: '=',
min: '=',
normalize: '=',
annotation: '=',
annotateEnabled: '=',
showAnnotations: '=',
},
template: '<div class="row"></div>' + // chartElemt
'<div class="row col-lg-12"></div>' + // timeElem
'<div class"row">' + // legendAnnContainer
'<div class="col-lg-6"></div>' + // legendElem
'<div class="col-lg-6"></div>' + // annElem
'</div>',
link: (scope: any, elem: any, attrs: any, $compile: any) => {
var chartElem = d3.select(elem.children()[0]);
var timeElem = d3.select(elem.children()[1]);
var legendAnnContainer = angular.element(elem.children()[2]);
var legendElem = d3.select(legendAnnContainer.children()[0]);
if (scope.annotateEnabled) {
var annElem = d3.select(legendAnnContainer.children()[1]);
}
var valueIdx = 1;
if (scope.normalize) {
valueIdx = 2;
}
var svgHeight = +scope.height || 150;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth: number;
var width: number;
var yScale = d3.scale.linear().range([height, 0]);
var xScale = d3.time.scale.utc();
var xAxis = d3.svg.axis()
.orient('bottom');
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(Math.min(10, height / 20))
.tickFormat(fmtfilter);
var line: any;
switch (scope.generator) {
case 'area':
line = d3.svg.area();
break;
default:
line = d3.svg.line();
}
var brush = d3.svg.brush()
.x(xScale)
.on('brush', brushed)
.on('brushend', annotateBrushed);
var top = chartElem
.append('svg')
.attr('height', svgHeight)
.attr('width', '100%');
var svg = top
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var defs = svg.append('defs')
.append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('height', height);
var chart = svg.append('g')
.attr('pointer-events', 'all')
.attr('clip-path', 'url(#clip)');
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')');
svg.append('g')
.attr('class', 'y axis');
var paths = chart.append('g');
chart.append('g')
.attr('class', 'x brush');
if (scope.annotateEnabled) {
var ann = chart.append('g');
}
top.append('rect')
.style('opacity', 0)
.attr('x', 0)
.attr('y', 0)
.attr('height', height)
.attr('width', margin.left)
.style('cursor', 'pointer')
.on('click', yaxisToggle);
var xloc = timeElem.append('div').attr("class", "col-lg-6");
xloc.style('float', 'left');
var brushText = timeElem.append('div').attr("class", "col-lg-6").append('p').attr("class", "text-right")
var legend = legendElem;
var aLegend = annElem;
var color = d3.scale.ordinal().range([
'#e41a1c',
'#377eb8',
'#4daf4a',
'#984ea3',
'#ff7f00',
'#a65628',
'#f781bf',
'#999999',
]);
var annColor = d3.scale.ordinal().range([
'#e41a1c',
'#377eb8',
'#4daf4a',
'#984ea3',
'#ff7f00',
'#a65628',
'#f781bf',
'#999999',
]);
var mousex = 0;
var mousey = 0;
var oldx = 0;
var hover = svg.append('g')
.attr('class', 'hover')
.style('pointer-events', 'none')
.style('display', 'none');
var hoverPoint = hover.append('svg:circle')
.attr('r', 5);
var hoverRect = hover.append('svg:rect')
.attr('fill', 'white');
var hoverText = hover.append('svg:text')
.style('font-size', '12px');
var focus = svg.append('g')
.attr('class', 'focus')
.style('pointer-events', 'none');
focus.append('line');
var yaxisZero = false;
function yaxisToggle() {
yaxisZero = !yaxisZero;
draw();
}
var drawAnnLegend = () => {
if (scope.annotation) {
aLegend.html('')
var a = scope.annotation;
//var table = aLegend.append('table').attr("class", "table table-condensed")
var table = aLegend.append("div")
var row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("CreationUser")
row.append("div").attr("class", "col-lg-10").text(a.CreationUser)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Owner")
row.append("div").attr("class", "col-lg-10").text(a.Owner)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Url")
row.append("div").attr("class", "col-lg-10").append('a')
.attr("xlink:href", a.Url).text(a.Url).on("click", (d) => {
window.open(a.Url, "_blank");
});
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Category")
row.append("div").attr("class", "col-lg-10").text(a.Category)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Host")
row.append("div").attr("class", "col-lg-10").text(a.Host)
row = table.append("div").attr("class", "row")
row.append("div").attr("class", "col-lg-2").text("Message")
row.append("div").attr("class", "col-lg-10").text(a.Message)
}//
};
var drawLegend = _.throttle((normalizeIdx: any) => {
var names = legend.selectAll('.series')
.data(scope.data, (d) => { return d.Name; });
names.enter()
.append('div')
.attr('class', 'series');
names.exit()
.remove();
var xi = xScale.invert(mousex);
xloc.text('Time: ' + fmtTime(xi));
var t = xi.getTime() / 1000;
var minDist = width + height;
var minName: string, minColor: string;
var minX: number, minY: number;
names
.each(function(d: any) {
var idx = bisect(d.Data, t);
if (idx >= d.Data.length) {
idx = d.Data.length - 1;
}
var e = d3.select(this);
var pt = d.Data[idx];
if (pt) {
e.attr('title', pt[normalizeIdx]);
e.text(d.Name + ': ' + fmtfilter(pt[1]));
var ptx = xScale(pt[0] * 1000);
var pty = yScale(pt[normalizeIdx]);
var ptd = Math.sqrt(
Math.pow(ptx - mousex, 2) +
Math.pow(pty - mousey, 2)
);
if (ptd < minDist) {
minDist = ptd;
minX = ptx;
minY = pty;
minName = d.Name + ': ' + pt[1];
minColor = color(d.Name);
}
}
})
.style('color', (d: any) => { return color(d.Name); });
hover
.attr('transform', 'translate(' + minX + ',' + minY + ')');
hoverPoint.style('fill', minColor);
hoverText
.text(minName)
.style('fill', minColor);
var isRight = minX > width / 2;
var isBottom = minY > height / 2;
hoverText
.attr('x', isRight ? -5 : 5)
.attr('y', isBottom ? -8 : 15)
.attr('text-anchor', isRight ? 'end' : 'start');
var node: any = hoverText.node();
var bb = node.getBBox();
hoverRect
.attr('x', bb.x - 1)
.attr('y', bb.y - 1)
.attr('height', bb.height + 2)
.attr('width', bb.width + 2);
var x = mousex;
if (x > width) {
x = 0;
}
focus.select('line')
.attr('x1', x)
.attr('x2', x)
.attr('y1', 0)
.attr('y2', height);
if (extentStart) {
var s = extentStart;
if (extentEnd != extentStart) {
s += ' - ' + extentEnd;
s += ' (' + extentDiff + ')'
}
brushText.text(s);
}
}, 50);
scope.$watchCollection('[data, annotations, showAnnotations]', update);
var showAnnotations = (show: boolean) => {
if (show) {
ann.attr("visibility", "visible");
return;
}
ann.attr("visibility", "hidden");
aLegend.html('');
}
var w = angular.element($window);
scope.$watch(() => {
return w.width();
}, resize, true);
w.bind('resize', () => {
scope.$apply();
});
function resize() {
svgWidth = elem.width();
if (svgWidth <= 0) {
return;
}
width = svgWidth - margin.left - margin.right;
xScale.range([0, width]);
xAxis.scale(xScale);
if (!mousex) {
mousex = width + 1;
}
svg.attr('width', svgWidth);
defs.attr('width', width);
xAxis.ticks(width / 60);
draw();
}
var oldx = 0;
var bisect = d3.bisector((d) => { return d[0]; }).left;
var bisectA = d3.bisector((d) => { return moment(d.StartDate).unix(); }).left;
function update(v: any) {
if (!angular.isArray(v) || v.length == 0) {
return;
}
d3.selectAll(".x.brush").call(brush.clear());
if (scope.annotateEnabled) {
showAnnotations(scope.showAnnotations);
}
resize();
}
function draw() {
if (!scope.data) {
return;
}
if (scope.normalize) {
valueIdx = 2;
}
function mousemove() {
var pt = d3.mouse(this);
mousex = pt[0];
mousey = pt[1];
drawLegend(valueIdx);
}
scope.data.map((data: any, i: any) => {
var max = d3.max(data.Data, (d: any) => { return d[1]; });
data.Data.map((d: any, j: any) => {
d.push(d[1] / max * 100 || 0)
});
});
line.y((d: any) => { return yScale(d[valueIdx]); });
line.x((d: any) => { return xScale(d[0] * 1000); });
var xdomain = [
d3.min(scope.data, (d: any) => { return d3.min(d.Data, (c: any) => { return c[0]; }); }) * 1000,
d3.max(scope.data, (d: any) => { return d3.max(d.Data, (c: any) => { return c[0]; }); }) * 1000,
];
if (!oldx) {
oldx = xdomain[1];
}
xScale.domain(xdomain);
var ymin = d3.min(scope.data, (d: any) => { return d3.min(d.Data, (c: any) => { return c[1]; }); });
var ymax = d3.max(scope.data, (d: any) => { return d3.max(d.Data, (c: any) => { return c[valueIdx]; }); });
var diff = (ymax - ymin) / 50;
if (!diff) {
diff = 1;
}
ymin -= diff;
ymax += diff;
if (yaxisZero) {
if (ymin > 0) {
ymin = 0;
} else if (ymax < 0) {
ymax = 0;
}
}
var ydomain = [ymin, ymax];
if (angular.isNumber(scope.min)) {
ydomain[0] = +scope.min;
}
if (angular.isNumber(scope.max)) {
ydomain[valueIdx] = +scope.max;
}
yScale.domain(ydomain);
if (scope.generator == 'area') {
line.y0(yScale(0));
}
svg.select('.x.axis')
.transition()
.call(xAxis);
svg.select('.y.axis')
.transition()
.call(yAxis);
svg.append('text')
.attr("class", "ylabel")
.attr("transform", "rotate(-90)")
.attr("y", -margin.left)
.attr("x", - (height / 2))
.attr("dy", "1em")
.text(_.uniq(scope.data.map(v => { return v.Unit })).join("; "));
if (scope.annotateEnabled) {
var rowId = {}; // annotation Id -> rowId
var rowEndDate = {}; // rowId -> EndDate
var maxRow = 0;
for (var i = 0; i < scope.annotations.length; i++) {
if (i == 0) {
rowId[scope.annotations[i].Id] = 0;
rowEndDate[0] = scope.annotations[0].EndDate;
continue;
}
for (var row = 0; row <= maxRow + 1; row++) {
if (row == maxRow + 1) {
rowId[scope.annotations[i].Id] = row;
rowEndDate[row] = scope.annotations[i].EndDate;
maxRow += 1
break;
}
if (rowEndDate[row] < scope.annotations[i].StartDate) {
rowId[scope.annotations[i].Id] = row;
rowEndDate[row] = scope.annotations[i].EndDate;
break;
}
}
}
var annotations = ann.selectAll('.annotation')
.data(scope.annotations, (d) => { return d.Id; });
annotations.enter()
.append("svg:a")
.append('rect')
.attr('visilibity', () => {
if (scope.showAnnotations) {
return "visible";
}
return "hidden";
})
.attr("y", (d) => { return rowId[d.Id] * ((height * .05) + 2) })
.attr("height", height * .05)
.attr("class", "annotation")
.attr("stroke", (d) => { return annColor(d.Id) })
.attr("stroke-opacity", .5)
.attr("fill", (d) => { return annColor(d.Id) })
.attr("fill-opacity", 0.1)
.attr("stroke-width", 1)
.attr("x", (d: any) => { return xScale(moment(d.StartDate).utc().unix() * 1000); })
.attr("width", (d: any) => {
var startT = moment(d.StartDate).utc().unix() * 1000
var endT = moment(d.EndDate).utc().unix() * 1000
if (startT == endT) {
return 3
}
return xScale(endT) - xScale(startT)
})
.on("mouseenter", (ann) => {
if (!scope.showAnnotations) {
return;
}
if (ann) {
scope.annotation = ann;
drawAnnLegend();
}
scope.$apply();
})
.on("click", () => {
if (!scope.showAnnotations) {
return;
}
angular.element('#modalShower').trigger('click');
});
annotations.exit().remove();
}
var queries = paths.selectAll('.line')
.data(scope.data, (d) => { return d.Name; });
switch (scope.generator) {
case 'area':
queries.enter()
.append('path')
.attr('stroke', (d: any) => { return color(d.Name); })
.attr('class', 'line')
.style('fill', (d: any) => { return color(d.Name); });
break;
default:
queries.enter()
.append('path')
.attr('stroke', (d: any) => { return color(d.Name); })
.attr('class', 'line');
}
queries.exit()
.remove();
queries
.attr('d', (d: any) => { return line(d.Data); })
.attr('transform', null)
.transition()
.ease('linear')
.attr('transform', 'translate(' + (xScale(oldx) - xScale(xdomain[1])) + ')');
chart.select('.x.brush')
.call(brush)
.selectAll('rect')
.attr('height', height)
.on('mouseover', () => {
hover.style('display', 'block');
})
.on('mouseout', () => {
hover.style('display', 'none');
})
.on('mousemove', mousemove);
chart.select('.x.brush .extent')
.style('stroke', '#fff')
.style('fill-opacity', '.125')
.style('shape-rendering', 'crispEdges');
oldx = xdomain[1];
drawLegend(valueIdx);
};
var extentStart: string;
var extentEnd: string;
var extentDiff: string;
function brushed() {
var e: any;
e = d3.event.sourceEvent;
if (e.shiftKey) {
return;
}
var extent = brush.extent();
extentStart = datefmt(extent[0]);
extentEnd = datefmt(extent[1]);
extentDiff = fmtDuration(moment(extent[1]).diff(moment(extent[0])));
drawLegend(valueIdx);
if (scope.enableBrush && extentEnd != extentStart) {
scope.brushStart = extentStart;
scope.brushEnd = extentEnd;
scope.$apply();
}
}
function annotateBrushed() {
if (!scope.annotateEnabled) {
return;
}
var e: any
e = d3.event.sourceEvent;
if (!e.shiftKey) {
return;
}
var extent = brush.extent();
scope.annotation = new Annotation();
scope.annotation.StartDate = moment(extent[0]).utc().format(timeFormat);
scope.annotation.EndDate = moment(extent[1]).utc().format(timeFormat);
scope.$apply(); // This logs a console type error, but also works .. odd.
angular.element('#modalShower').trigger('click');
}
var mfmt = 'YYYY/MM/DD-HH:mm:ss';
function datefmt(d: any) {
return moment(d).utc().format(mfmt);
}
},
};
}]);
| seekingalpha/bosun | cmd/bosun/web/static/js/directives.ts | TypeScript | mit | 41,222 |
require "rdg/analysis/propagater"
module RDG
module Control
class Case < Analysis::Propagater
register_analyser :case
def prepare
@expression, *@consequences = nodes
end
def internal_flow_edges
nodes.each_cons(2).to_a
end
def start_node
@expression
end
def end_nodes
@consequences
end
end
end
end
| mutiny/rdg | lib/rdg/control/case.rb | Ruby | mit | 400 |
import * as React from "react";
import * as ReactDOM from "react-dom";
import Start from "./awesome-sec-audit.tsx";
// Dedicating a file to this basic call allows us to import all major modules
// into test suites.
const item = document.getElementById("content");
if (item == null) {
console.log("Render container missing");
}
else {
ReactDOM.render(
<Start />,
item
);
}
| technion/awesome-sec-audit | assets/awesome-sec-audit-run.tsx | TypeScript | mit | 402 |
'use strict';
/* Services */
angular.module('nhsApp.services', [])
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
})
.factory('nhsApiService', function($http) {
var nhsAPI = {};
nhsAPI.getLetters = function() {
return $http({
method: 'POST',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/atoz.json"
});
};
nhsAPI.getLetter = function(letter) {
return $http({
method: 'POST',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/atoz/"+ letter + ".json"
});
};
nhsAPI.getCondition = function(condition) {
return $http({
method: 'GET',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/"+ condition + ".json"
});
};
nhsAPI.getDetail = function(condition, detail) {
return $http({
method: 'GET',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/" + condition + "/" + detail + ".html"
});
};
/* Useful to avoid all the extra mark-up in the Html version */
nhsAPI.getXmlDetail = function(condition, detail) {
return $http({
method: 'GET',
url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/" + condition + "/" + detail + ".xml"
});
};
return nhsAPI;
}); | denniskenny/Nhs-Choices-Angular | app/js/services.js | JavaScript | mit | 1,529 |
<?php
namespace Analatica\ForfaitBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('AnalaticaForfaitBundle:Default:index.html.twig', array('name' => $name));
}
}
| portalsway2/AnalaticaV2 | src/Analatica/ForfaitBundle/Controller/DefaultController.php | PHP | mit | 317 |
import * as decimal from 'break_infinity.js';
declare global {
interface Decimal {
cos(): Decimal
lessThanOrEqualTo(other: decimal.Decimal): boolean
lessThan(other: decimal.Decimal): boolean
greaterThan(other: decimal.Decimal): boolean
greaterThanOrEqualTo(other: decimal.Decimal): boolean
}
}
| scorzy/IdleAnt | src/index.d.ts | TypeScript | mit | 321 |
export { default } from 'ember-disqus/components/disqus-comment-count'; | sir-dunxalot/ember-disqus | app/components/disqus-comment-count.js | JavaScript | mit | 71 |
import re, sys, os
from gunicorn.app.wsgiapp import run
if __name__ == '__main__':
sys.argv[0] = __file__
sys.exit(run())
| commitmachine/pg-hoffserver | pghoffserver/gunicorn_python.py | Python | mit | 131 |
/**
* Created by peter on 9/19/16.
*/
// ==UserScript==
// @name Super Rookie
// @namespace http://v.numag.net/grease/
// @description locate new posts on piratebay
// @include https://thepiratebay.org/top/*
// ==/UserScript==
(function () {
function $x() {
var x='';
var node=document;
var type=0;
var fix=true;
var i=0;
var cur;
function toArray(xp) {
var final=[], next;
while (next=xp.iterateNext()) {
final.push(next);
}
return final;
}
while (cur=arguments[i++]) {
switch (typeof cur) {
case "string": x+=(x=='') ? cur : " | " + cur; continue;
case "number": type=cur; continue;
case "object": node=cur; continue;
case "boolean": fix=cur; continue;
}
}
if (fix) {
if (type==6) type=4;
if (type==7) type=5;
}
// selection mistake helper
if (!/^\//.test(x)) x="//"+x;
// context mistake helper
if (node!=document && !/^\./.test(x)) x="."+x;
var result=document.evaluate(x, node, null, type, null);
if (fix) {
// automatically return special type
switch (type) {
case 1: return result.numberValue;
case 2: return result.stringValue;
case 3: return result.booleanValue;
case 8:
case 9: return result.singleNodeValue;
}
}
return fix ? toArray(result) : result;
};
$x("/html/body/div[@id='main-content']/table[@id='searchResult']/tbody/tr/td[2]/a").map(function (element) {
if (localStorage.getItem(element.href) == undefined){
localStorage.setItem(element.href,1);
element.parentNode.style= 'background: darkorange;';
}
else {
localStorage.setItem(element.href,parseInt(localStorage.getItem(element.href))+1);
};
});
})();
| motord/elbowgrease | grease/superrookie.user.js | JavaScript | mit | 2,103 |
/* @flow */
const babelJest = require('babel-jest');
module.exports = babelJest.createTransformer({
presets: [
[
'env',
{
targets: {
ie: 11,
edge: 14,
firefox: 45,
chrome: 49,
safari: 10,
node: '6.11',
},
modules: 'commonjs',
},
],
'react',
],
plugins: [
'transform-flow-strip-types',
'transform-class-properties',
'transform-object-rest-spread',
],
});
| boldr/boldr-ui | internal/jest/transform.js | JavaScript | mit | 489 |
import { name, autoService } from 'knifecycle';
import type { LogService } from 'common-services';
import type { JsonValue } from 'type-fest';
export type APMService<T = string> = (type: T, data: JsonValue) => void;
export default name('apm', autoService(initAPM));
const noop = () => undefined;
/**
* Application monitoring service that simply log stringified contents.
* @function
* @param {Object} services
* The services to inject
* @param {Function} [services.log]
* A logging function
* @return {Promise<Object>}
* A promise of the apm service.
*/
async function initAPM<T = string>({
log = noop,
}: {
log: LogService;
}): Promise<APMService<T>> {
log('debug', '❤️ - Initializing the APM service.');
return (type, data) => log('info', type, JSON.stringify(data));
}
| nfroidure/whook | packages/whook-http-transaction/src/services/apm.ts | TypeScript | mit | 806 |
//******************************************************************************************************
// Serialization.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 06/08/2006 - Pinal C. Patel
// Original version of source code generated.
// 09/09/2008 - J. Ritchie Carroll
// Converted to C#.
// 09/09/2008 - J. Ritchie Carroll
// Added TryGetObject overloads.
// 02/16/2009 - Josh L. Patterson
// Edited Code Comments.
// 08/4/2009 - Josh L. Patterson
// Edited Code Comments.
// 09/14/2009 - Stephen C. Wills
// Added new header and license agreement.
// 04/06/2011 - Pinal C. Patel
// Modified GetString() method to not check for the presence of Serializable attribute on the
// object being serialized since this is not required by the XmlSerializer.
// 04/08/2011 - Pinal C. Patel
// Moved Serialize() and Deserialize() methods from GSF.Services.ServiceModel.Serialization class
// in GSF.Services.dll to consolidate serialization methods.
// 12/14/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Xml.Serialization;
using GSF.IO;
using GSF.Reflection;
namespace GSF
{
#region [ Enumerations ]
/// <summary>
/// Indicates the format of <see cref="object"/> serialization or deserialization.
/// </summary>
public enum SerializationFormat
{
/// <summary>
/// <see cref="object"/> is serialized or deserialized using <see cref="DataContractSerializer"/> to XML (eXtensible Markup Language) format.
/// </summary>
/// <remarks>
/// <see cref="object"/> can be serialized or deserialized using <see cref="XmlSerializer"/> by adding the <see cref="XmlSerializerFormatAttribute"/> to the <see cref="object"/>.
/// </remarks>
Xml,
/// <summary>
/// <see cref="object"/> is serialized or deserialized using <see cref="DataContractJsonSerializer"/> to JSON (JavaScript Object Notation) format.
/// </summary>
Json,
/// <summary>
/// <see cref="object"/> is serialized or deserialized using <see cref="BinaryFormatter"/> to binary format.
/// </summary>
Binary
}
#endregion
/// <summary>
/// Common serialization related functions.
/// </summary>
public static class Serialization
{
#region [ Obsolete ]
/// <summary>
/// Creates a clone of a serializable object.
/// </summary>
/// <typeparam name="T">The type of the cloned object.</typeparam>
/// <param name="sourceObject">The type source to be cloned.</param>
/// <returns>A clone of <paramref name="sourceObject"/>.</returns>
[Obsolete("This method will be removed in future builds.")]
public static T CloneObject<T>(T sourceObject)
{
return Deserialize<T>(Serialize(sourceObject, SerializationFormat.Binary), SerializationFormat.Binary);
}
/// <summary>
/// Performs XML deserialization on the XML string and returns the typed object for it.
/// </summary>
/// <remarks>
/// This function will throw an error during deserialization if the input data is invalid,
/// consider using TryGetObject to prevent needing to implement exception handling.
/// </remarks>
/// <exception cref="System.InvalidOperationException">
/// An error occurred during deserialization. The original exception is available using
/// the InnerException property.
/// </exception>
/// <typeparam name="T">The type of the object to create from the serialized string <paramref name="serializedObject"/>.</typeparam>
/// <param name="serializedObject">A <see cref="string"/> representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <returns>A type T based on <paramref name="serializedObject"/>.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static T GetObject<T>(string serializedObject)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(serializedObject));
}
/// <summary>
/// Attempts XML deserialization on the XML string and returns the typed object for it.
/// </summary>
/// <typeparam name="T">The generic type T that is to be deserialized.</typeparam>
/// <param name="serializedObject"><see cref="string"/> that contains the serialized representation of the object.</param>
/// <param name="deserializedObject">An object of type T that is passed in as the container to hold the deserialized object from the string <paramref name="serializedObject"/>.</param>
/// <returns><see cref="bool"/> value indicating if the deserialization was successful.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static bool TryGetObject<T>(string serializedObject, out T deserializedObject)
{
try
{
deserializedObject = GetObject<T>(serializedObject);
return true;
}
catch
{
deserializedObject = default(T);
return false;
}
}
/// <summary>
/// Performs binary deserialization on the byte array and returns the typed object for it.
/// </summary>
/// <remarks>
/// This function will throw an error during deserialization if the input data is invalid,
/// consider using TryGetObject to prevent needing to implement exception handling.
/// </remarks>
/// <exception cref="System.Runtime.Serialization.SerializationException">Serialized object data is invalid or length is 0.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission. </exception>
/// <typeparam name="T">The type of the object to create from the serialized byte array <paramref name="serializedObject"/>.</typeparam>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <returns>A type T based on <paramref name="serializedObject"/>.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static T GetObject<T>(byte[] serializedObject)
{
BinaryFormatter serializer = new BinaryFormatter();
return (T)serializer.Deserialize(new MemoryStream(serializedObject));
}
/// <summary>
/// Attempts binary deserialization on the byte array and returns the typed object for it.
/// </summary>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <param name="deserializedObject">A type T object, passed by reference, that is used to be hold the deserialized object.</param>
/// <typeparam name="T">The generic type T that is to be deserialized.</typeparam>
/// <returns>A <see cref="bool"/> which indicates whether the deserialization process was successful.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static bool TryGetObject<T>(byte[] serializedObject, out T deserializedObject)
{
try
{
deserializedObject = GetObject<T>(serializedObject);
return true;
}
catch
{
deserializedObject = default(T);
return false;
}
}
/// <summary>
/// Performs binary deserialization on the byte array and returns the object for it.
/// </summary>
/// <remarks>
/// This function will throw an error during deserialization if the input data is invalid,
/// consider using TryGetObject to prevent needing to implement exception handling.
/// </remarks>
/// <exception cref="System.Runtime.Serialization.SerializationException">Serialized object data is invalid or length is 0.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission. </exception>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <returns>An <see cref="object"/> based on <paramref name="serializedObject"/>.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static object GetObject(byte[] serializedObject)
{
BinaryFormatter serializer = new BinaryFormatter();
return serializer.Deserialize(new MemoryStream(serializedObject));
}
/// <summary>
/// Attempts binary deserialization on the byte array and returns the typed object for it.
/// </summary>
/// <param name="serializedObject">A <see cref="byte"/> array representing the object (<paramref name="serializedObject"/>) to deserialize.</param>
/// <param name="deserializedObject">An <see cref="object"/>, passed by reference, that is used to be hold the deserialized object.</param>
/// <returns>A <see cref="bool"/> which indicates whether the deserialization process was successful.</returns>
[Obsolete("This method will be removed in future builds, use the Deserialize() method instead.")]
public static bool TryGetObject(byte[] serializedObject, out object deserializedObject)
{
try
{
deserializedObject = GetObject(serializedObject);
return true;
}
catch
{
deserializedObject = null;
return false;
}
}
/// <summary>
/// Performs XML serialization on the serializable object and returns the output as string.
/// </summary>
/// <param name="serializableObject">The serializable object.</param>
/// <returns>An XML representation of the object if the specified object can be serialized; otherwise an empty string.</returns>
[Obsolete("This method will be removed in future builds, use the Serialize() method instead.")]
public static string GetString(object serializableObject)
{
StringWriter serializedObject = new StringWriter();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
serializer.Serialize(serializedObject, serializableObject);
return serializedObject.ToString();
}
/// <summary>
/// Performs binary serialization on the serializable object and returns the output as byte array.
/// </summary>
/// <param name="serializableObject">The serializable object.</param>
/// <returns>A byte array representation of the object if the specified object can be serialized; otherwise an empty array.</returns>
[Obsolete("This method will be removed in future builds, use the Serialize() method instead.")]
public static byte[] GetBytes(object serializableObject)
{
return GetStream(serializableObject).ToArray();
}
/// <summary>
/// Performs binary serialization on the serializable object and returns the serialized object as a stream.
/// </summary>
/// <param name="serializableObject">The serializable object.</param>
/// <returns>A memory stream representation of the object if the specified object can be serialized; otherwise an empty stream.</returns>
[Obsolete("This method will be removed in future builds, use the Serialize() method instead.")]
public static MemoryStream GetStream(object serializableObject)
{
MemoryStream dataStream = new MemoryStream();
if (serializableObject.GetType().IsSerializable)
{
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(dataStream, serializableObject);
}
return dataStream;
}
#endregion
#region [ Legacy ]
/// <summary>
/// Serialization binder used to deserialize files that were serialized using the old library frameworks
/// (TVA Code Library, Time Series Framework, TVA.PhasorProtocols, and PMU Connection Tester) into classes
/// in the Grid Solutions Framework.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly SerializationBinder LegacyBinder = new LegacySerializationBinder();
// Serialization binder used to deserialize files that were serialized using the old library frameworks.
private class LegacySerializationBinder : SerializationBinder
{
/// <summary>
/// Controls the binding of a serialized object to a type.
/// </summary>
/// <param name="assemblyName">Specifies the <see cref="Assembly"/> name of the serialized object.</param>
/// <param name="typeName">Specifies the <see cref="Type"/> name of the serialized object.</param>
/// <returns>The type of the object the formatter creates a new instance of.</returns>
public override Type BindToType(string assemblyName, string typeName)
{
Type newType;
string newTypeName;
// Perform namespace transformations that occurred when migrating to the Grid Solutions Framework
// from various older versions of code with different namespaces
newTypeName = typeName
.Replace("TVA.", "GSF.")
.Replace("TimeSeriesFramework.", "GSF.TimeSeries.")
.Replace("ConnectionTester.", "GSF.PhasorProtocols.") // PMU Connection Tester namespace
.Replace("TVA.Phasors.", "GSF.PhasorProtocols.") // 2007 TVA Code Library namespace
.Replace("Tva.Phasors.", "GSF.PhasorProtocols.") // 2008 TVA Code Library namespace
.Replace("BpaPdcStream", "BPAPDCstream") // 2013 GSF uppercase phasor protocol namespace
.Replace("FNet", "FNET") // 2013 GSF uppercase phasor protocol namespace
.Replace("Iec61850_90_5", "IEC61850_90_5") // 2013 GSF uppercase phasor protocol namespace
.Replace("Ieee1344", "IEEE1344") // 2013 GSF uppercase phasor protocol namespace
.Replace("IeeeC37_118", "IEEEC37_118"); // 2013 GSF uppercase phasor protocol namespace
// Check for 2009 TVA Code Library namespace
if (newTypeName.StartsWith("PhasorProtocols", StringComparison.Ordinal))
newTypeName = "GSF." + newTypeName;
// Check for 2014 LineFrequency type in the GSF phasor protocol namespace
if (newTypeName.Equals("GSF.PhasorProtocols.LineFrequency", StringComparison.Ordinal))
newTypeName = "GSF.Units.EE.LineFrequency";
try
{
// Search each assembly in the current application domain for the type with the transformed name
return AssemblyInfo.FindType(newTypeName);
}
catch
{
// Fall back on more brute force search when simple search fails
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
newType = assembly.GetType(newTypeName);
if ((object)newType != null)
return newType;
}
catch
{
// Ignore errors that occur when attempting to load
// types from assemblies as we may still be able to
// load the type from a different assembly
}
}
}
// No type found; return null
return null;
}
}
#endregion
/// <summary>
/// Serializes an <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the <paramref name="serializableObject"/>.</typeparam>
/// <param name="serializableObject"><see cref="Object"/> to be serialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializableObject"/> is to be serialized.</param>
/// <returns>An <see cref="Array"/> of <see cref="Byte"/> of the serialized <see cref="Object"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="serializableObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static byte[] Serialize<T>(T serializableObject, SerializationFormat serializationFormat)
{
// FYI, using statement will not work here as this creates a read-only variable that cannot be passed by reference
Stream stream = null;
try
{
stream = new BlockAllocatedMemoryStream();
Serialize(serializableObject, serializationFormat, stream);
return ((BlockAllocatedMemoryStream)stream).ToArray();
}
finally
{
if ((object)stream != null)
stream.Dispose();
}
}
/// <summary>
/// Serializes an <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the <paramref name="serializableObject"/>.</typeparam>
/// <param name="serializableObject"><see cref="Object"/> to be serialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializableObject"/> is to be serialized.</param>
/// <param name="serializedOutput"><see cref="Stream"/> where the <paramref name="serializableObject"/> is to be serialized.</param>
/// <exception cref="ArgumentNullException"><paramref name="serializedOutput"/> or <paramref name="serializableObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static void Serialize<T>(T serializableObject, SerializationFormat serializationFormat, Stream serializedOutput)
{
if ((object)serializedOutput == null)
throw new ArgumentNullException(nameof(serializedOutput));
if ((object)serializableObject == null)
throw new ArgumentNullException(nameof(serializableObject));
// Serialize object to the provided stream.
if (serializationFormat == SerializationFormat.Xml)
{
if (typeof(T).GetCustomAttributes(typeof(XmlSerializerFormatAttribute), false).Length > 0)
{
// Serialize to XML format using XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(serializedOutput, serializableObject);
}
else
{
// Serialize to XML format using DataContractSerializer.
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(serializedOutput, serializableObject);
}
}
else if (serializationFormat == SerializationFormat.Json)
{
// Serialize to JSON format.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(serializedOutput, serializableObject);
}
else if (serializationFormat == SerializationFormat.Binary)
{
// Serialize to binary format.
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(serializedOutput, serializableObject);
}
else
{
// Serialization format is not supported.
throw new NotSupportedException(string.Format("{0} serialization is not supported", serializationFormat));
}
// Seek to the beginning of the serialized output stream.
serializedOutput.Position = 0;
}
/// <summary>
/// Deserializes a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Array"/> of <see cref="Byte"/>s containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <returns>The deserialized <see cref="Object"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="serializedObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static T Deserialize<T>(byte[] serializedObject, SerializationFormat serializationFormat)
{
if ((object)serializedObject == null)
throw new ArgumentNullException(nameof(serializedObject));
using (MemoryStream stream = new MemoryStream(serializedObject))
{
return Deserialize<T>(stream, serializationFormat);
}
}
/// <summary>
/// Deserializes a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Stream"/> containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <returns>The deserialized <see cref="Object"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="serializedObject"/> is null.</exception>
/// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
public static T Deserialize<T>(Stream serializedObject, SerializationFormat serializationFormat)
{
if ((object)serializedObject == null)
throw new ArgumentNullException(nameof(serializedObject));
// Deserialize the serialized object.
T deserializedObject;
if (serializationFormat == SerializationFormat.Xml)
{
if (typeof(T).GetCustomAttributes(typeof(XmlSerializerFormatAttribute), false).Length > 0)
{
// Deserialize from XML format using XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(T));
deserializedObject = (T)serializer.Deserialize(serializedObject);
}
else
{
// Deserialize from XML format using DataContractSerializer.
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
deserializedObject = (T)serializer.ReadObject(serializedObject);
}
}
else if (serializationFormat == SerializationFormat.Json)
{
// Deserialize from JSON format.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
deserializedObject = (T)serializer.ReadObject(serializedObject);
}
else if (serializationFormat == SerializationFormat.Binary)
{
// Deserialize from binary format.
BinaryFormatter serializer = new BinaryFormatter();
serializer.Binder = LegacyBinder;
deserializedObject = (T)serializer.Deserialize(serializedObject);
}
else
{
// Serialization format is not supported.
throw new NotSupportedException(string.Format("{0} serialization is not supported", serializationFormat));
}
return deserializedObject;
}
/// <summary>
/// Attempts to deserialize a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Array"/> of <see cref="Byte"/>s containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <param name="deserializedObject">Deserialized <see cref="Object"/>.</param>
/// <returns><c>true</c>if deserialization succeeded; otherwise <c>false</c>.</returns>
public static bool TryDeserialize<T>(byte[] serializedObject, SerializationFormat serializationFormat, out T deserializedObject)
{
deserializedObject = default(T);
try
{
deserializedObject = Deserialize<T>(serializedObject, serializationFormat);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Attempts to deserialize a serialized <see cref="Object"/>.
/// </summary>
/// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
/// <param name="serializedObject"><see cref="Stream"/> containing the serialized <see cref="Object"/> that is to be deserialized.</param>
/// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
/// <param name="deserializedObject">Deserialized <see cref="Object"/>.</param>
/// <returns><c>true</c>if deserialization succeeded; otherwise <c>false</c>.</returns>
public static bool TryDeserialize<T>(Stream serializedObject, SerializationFormat serializationFormat, out T deserializedObject)
{
deserializedObject = default(T);
try
{
deserializedObject = Deserialize<T>(serializedObject, serializationFormat);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Gets <see cref="SerializationInfo"/> value for specified <paramref name="name"/>; otherwise <paramref name="defaultValue"/>.
/// </summary>
/// <typeparam name="T">Type of parameter to get from <see cref="SerializationInfo"/>.</typeparam>
/// <param name="info"><see cref="SerializationInfo"/> object that contains deserialized values.</param>
/// <param name="name">Name of deserialized parameter to retrieve.</param>
/// <param name="defaultValue">Default value to return if <paramref name="name"/> does not exist or cannot be deserialized.</param>
/// <returns>Value for specified <paramref name="name"/>; otherwise <paramref name="defaultValue"/></returns>
/// <remarks>
/// <see cref="SerializationInfo"/> do not have a direct way of determining if an item with a specified name exists, so when calling
/// one of the Get(n) functions you will simply get a <see cref="SerializationException"/> if the parameter does not exist; similarly
/// you will receive this exception if the parameter fails to properly deserialize. This extension method protects against both of
/// these failures and returns a default value if the named parameter does not exist or cannot be deserialized.
/// </remarks>
public static T GetOrDefault<T>(this SerializationInfo info, string name, T defaultValue)
{
try
{
return (T)info.GetValue(name, typeof(T));
}
catch (SerializationException)
{
return defaultValue;
}
}
}
} | rmc00/gsf | Source/Libraries/GSF.Core/Serialization.cs | C# | mit | 30,963 |