text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
package com.google.cloud.resourcemanager.v3.samples; // [START cloudresourcemanager_v3_generated_TagValuesSettings_GetTagValue_sync] import com.google.cloud.resourcemanager.v3.TagValuesSettings; import java.time.Duration; public class SyncGetTagValue { public static void main(String[] args) throws Exception { syncGetTagValue(); } public static void syncGetTagValue() throws Exception { // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library TagValuesSettings.Builder tagValuesSettingsBuilder = TagValuesSettings.newBuilder(); tagValuesSettingsBuilder .getTagValueSettings() .setRetrySettings( tagValuesSettingsBuilder.getTagValueSettings().getRetrySettings().toBuilder() .setTotalTimeout(Duration.ofSeconds(30)) .build()); TagValuesSettings tagValuesSettings = tagValuesSettingsBuilder.build(); } } // [END cloudresourcemanager_v3_generated_TagValuesSettings_GetTagValue_sync]
{'content_hash': '833ec22440066f5c5dafb7a349d47bd2', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 100, 'avg_line_length': 42.806451612903224, 'alnum_prop': 0.7550866616428034, 'repo_name': 'googleapis/google-cloud-java', 'id': 'ea1e9e42c96dd58cbd5ddf466800e5f454236899', 'size': '1922', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'java-resourcemanager/samples/snippets/generated/com/google/cloud/resourcemanager/v3/tagvaluessettings/gettagvalue/SyncGetTagValue.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2614'}, {'name': 'HCL', 'bytes': '28592'}, {'name': 'Java', 'bytes': '826434232'}, {'name': 'Jinja', 'bytes': '2292'}, {'name': 'Python', 'bytes': '200408'}, {'name': 'Shell', 'bytes': '97954'}]}
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {% block page_content %} <div> {{ wtf.quick_form(form) }} </div> <div class="text-center"> <br> <table class="table-bordered table-hover"> <thead> <tr> <th style="text-align:center">#</th> {% for date_tmp in date_range_response %} <th style="text-align:center">{{ date_tmp.strftime( '%m-%d' ) }}<br>{{ date_tmp.strftime( '%a' ) }}</th> {% endfor %} <th>SUM</th> </tr> </thead> <tbody> {% for teacher in teacher_sum_response_data%} <tr> <td><strong>{{ teacher}}</strong></td> {% for date_tmp in date_range_response %} {% if teacher_sum_response_data[teacher][date_tmp] %} <td><a href="/get_teacher_one_day_sum_detail?teacher_name={{ teacher }}&date={{ date_tmp }}" target="_blank">{{ teacher_sum_response_data[teacher][date_tmp].total_seconds()/3600 }}</a></td> {% else %} <td></td> {% endif %} {% endfor %} <td>{{ teacher_sum_response_data[teacher]['total_classes_time'].total_seconds()/3600 }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} {% block scripts %} {{ super() }} {{ pagedown.include_pagedown() }} {% endblock %}
{'content_hash': '8badc6e348235cedb484327ffd9fd265', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 217, 'avg_line_length': 24.242424242424242, 'alnum_prop': 0.446875, 'repo_name': 'phillinzzz/flasky', 'id': 'a4e9af2dfae3a02f8147746149befd42794468ec', 'size': '1600', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/templates/generate_sum_teacher_classes.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1855'}, {'name': 'HTML', 'bytes': '64919'}, {'name': 'Mako', 'bytes': '412'}, {'name': 'Python', 'bytes': '134813'}]}
<select> <option value="FR">Française</option> <option value="CH">Suisse</option> <option value="BE">Belge</option> <option value="DE">Allemande</option> <option value="IT">Italienne</option> <option value="AF">Afghane</option> <option value="AL">Albanaise</option> <option value="DZ">Algerienne</option> <option value="US">Americaine</option> <option value="AD">Andorrane</option> <option value="AO">Angolaise</option> <option value="AG">Antiguaise et barbudienne</option> <option value="AR">Argentine</option> <option value="AM">Armenienne</option> <option value="AU">Australienne</option> <option value="AT">Autrichienne</option> <option value="AZ">Azerbaïdjanaise</option> <option value="BS">Bahamienne</option> <option value="BH">Bahreinienne</option> <option value="BD">Bangladaise</option> <option value="BB">Barbadienne</option> <option value="BZ">Belizienne</option> <option value="BJ">Beninoise</option> <option value="BT">Bhoutanaise</option> <option value="BY">Bielorusse</option> <option value="MM">Birmane</option> <option value="GW">Bissau-Guinéenne</option> <option value="BO">Bolivienne</option> <option value="BA">Bosnienne</option> <option value="BW">Botswanaise</option> <option value="BR">Bresilienne</option> <option value="GB">Britannique</option> <option value="BN">Bruneienne</option> <option value="BG">Bulgare</option> <option value="BF">Burkinabe</option> <option value="BI">Burundaise</option> <option value="KH">Cambodgienne</option> <option value="CM">Camerounaise</option> <option value="CA">Canadienne</option> <option value="CV">Cap-verdienne</option> <option value="CF">Centrafricaine</option> <option value="CL">Chilienne</option> <option value="CN">Chinoise</option> <option value="CY">Chypriote</option> <option value="CO">Colombienne</option> <option value="KM">Comorienne</option> <option value="CG">Congolaise</option> <option value="CR">Costaricaine</option> <option value="HR">Croate</option> <option value="CU">Cubaine</option> <option value="DK">Danoise</option> <option value="DJ">Djiboutienne</option> <option value="DO">Dominicaine</option> <option value="DM">Dominiquaise</option> <option value="EG">Egyptienne</option> <option value="AE">Emirienne</option> <option value="GQ">Equato-guineenne</option> <option value="EC">Equatorienne</option> <option value="ER">Erythreenne</option> <option value="ES">Espagnole</option> <option value="TL">Est-timoraise</option> <option value="EE">Estonienne</option> <option value="ET">Ethiopienne</option> <option value="FJ">Fidjienne</option> <option value="FI">Finlandaise</option> <option value="GA">Gabonaise</option> <option value="GM">Gambienne</option> <option value="GE">Georgienne</option> <option value="GH">Ghaneenne</option> <option value="GD">Grenadienne</option> <option value="GT">Guatemalteque</option> <option value="GN">Guineenne</option> <option value="GF">Guyanienne</option> <option value="HT">Haïtienne</option> <option value="GR">Hellenique</option> <option value="HN">Hondurienne</option> <option value="HU">Hongroise</option> <option value="IN">Indienne</option> <option value="ID">Indonesienne</option> <option value="IQ">Irakienne</option> <option value="IE">Irlandaise</option> <option value="IS">Islandaise</option> <option value="IL">Israélienne</option> <option value="CI">Ivoirienne</option> <option value="JM">Jamaïcaine</option> <option value="JP">Japonaise</option> <option value="JO">Jordanienne</option> <option value="KZ">Kazakhstanaise</option> <option value="KE">Kenyane</option> <option value="KG">Kirghize</option> <option value="KI">Kiribatienne</option> <option value="KN">Kittitienne-et-nevicienne</option> <option value="KW">Koweitienne</option> <option value="LA">Laotienne</option> <option value="LS">Lesothane</option> <option value="LV">Lettone</option> <option value="LB">Libanaise</option> <option value="LR">Liberienne</option> <option value="LY">Libyenne</option> <option value="LI">Liechtensteinoise</option> <option value="LT">Lituanienne</option> <option value="LU">Luxembourgeoise</option> <option value="MK">Macedonienne</option> <option value="MY">Malaisienne</option> <option value="MW">Malawienne</option> <option value="MV">Maldivienne</option> <option value="MG">Malgache</option> <option value="ML">Malienne</option> <option value="MT">Maltaise</option> <option value="MA">Marocaine</option> <option value="MH">Marshallaise</option> <option value="MU">Mauricienne</option> <option value="MR">Mauritanienne</option> <option value="MX">Mexicaine</option> <option value="FM">Micronesienne</option> <option value="MD">Moldave</option> <option value="MC">Monegasque</option> <option value="MN">Mongole</option> <option value="ME">Montenegrine</option> <option value="MZ">Mozambicaine</option> <option value="NA">Namibienne</option> <option value="NR">Nauruane</option> <option value="NL">Neerlandaise</option> <option value="NZ">Neo-zelandaise</option> <option value="NP">Nepalaise</option> <option value="NI">Nicaraguayenne</option> <option value="NG">Nigeriane</option> <option value="NE">Nigerienne</option> <option value="KP">Nord-coréenne</option> <option value="NO">Norvegienne</option> <option value="OM">Omanaise</option> <option value="UG">Ougandaise</option> <option value="UZ">Ouzbeke</option> <option value="PK">Pakistanaise</option> <option value="PW">Palau</option> <option value="PS">Palestinienne</option> <option value="PA">Panameenne</option> <option value="PG">Papouane-neoguineenne</option> <option value="PY">Paraguayenne</option> <option value="PE">Peruvienne</option> <option value="PH">Philippine</option> <option value="PL">Polonaise</option> <option value="PR">Portoricaine</option> <option value="PT">Portugaise</option> <option value="QA">Qatarienne</option> <option value="RO">Roumaine</option> <option value="RU">Russe</option> <option value="RW">Rwandaise</option> <option value="LC">Saint-Lucienne</option> <option value="SM">Saint-Marinaise</option> <option value="VC">Saint-Vincentaise-et-Grenadine</option> <option value="SB">Salomonaise</option> <option value="SV">Salvadorienne</option> <option value="WS">Samoane</option> <option value="ST">Santomeenne</option> <option value="SA">Saoudienne</option> <option value="SN">Senegalaise</option> <option value="RS">Serbe</option> <option value="SC">Seychelloise</option> <option value="SL">Sierra-leonaise</option> <option value="SG">Singapourienne</option> <option value="SK">Slovaque</option> <option value="SI">Slovene</option> <option value="SO">Somalienne</option> <option value="SD">Soudanaise</option> <option value="LK">Sri-lankaise</option> <option value="ZA">Sud-africaine</option> <option value="KR">Sud-coréenne</option> <option value="SE">Suedoise</option> <option value="SR">Surinamaise</option> <option value="SZ">Swazie</option> <option value="SY">Syrienne</option> <option value="TJ">Tadjike</option> <option value="TW">Taiwanaise</option> <option value="TZ">Tanzanienne</option> <option value="TD">Tchadienne</option> <option value="CZ">Tcheque</option> <option value="TH">Thaïlandaise</option> <option value="TG">Tonguienne</option> <option value="TT">Trinidadienne</option> <option value="TN">Tunisienne</option> <option value="TM">Turkmene</option> <option value="TR">Turque</option> <option value="TV">Tuvaluane</option> <option value="UA">Ukrainienne</option> <option value="UY">Uruguayenne</option> <option value="VU">Vanuatuane</option> <option value="VE">Venezuelienne</option> <option value="VN">Vietnamienne</option> <option value="YE">Yemenite</option> <option value="ZM">Zambienne</option> <option value="ZW">Zimbabweenne</option> </select>
{'content_hash': '901da9e709d0010b5d0bcb5cce18571f', 'timestamp': '', 'source': 'github', 'line_count': 194, 'max_line_length': 59, 'avg_line_length': 40.16494845360825, 'alnum_prop': 0.7254876796714579, 'repo_name': 'nicolanrizzo/nationalitylist', 'id': '6d6f933730fc0ddd971e1ce1f1233d49581a257d', 'size': '7801', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'HTMLdropdown/fr.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '16790'}]}
package com.june.dto.back.demo; import java.io.Serializable; import java.util.List; import com.june.common.PageDTO; public class TreeGridDto extends PageDTO<TreeGridDto> implements Serializable{ /** * long serialVersionUID */ private static final long serialVersionUID = 4936747688639597710L; private String id; //节点id private String pid;//父节点id private String name; private String persons; private String begin; private String end; private List<TreeGridDto> children; private String iconCls;//节点的图标 private String state; //节点的状态,展开(open)还是闭合(closed), public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPersons() { return persons; } public void setPersons(String persons) { this.persons = persons; } public String getBegin() { return begin; } public void setBegin(String begin) { this.begin = begin; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public List<TreeGridDto> getChildren() { return children; } public void setChildren(List<TreeGridDto> children) { this.children = children; } public String getIconCls() { return iconCls; } public void setIconCls(String iconCls) { this.iconCls = iconCls; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } @Override protected String getDtoName() { return "TreeGridDto"; } }
{'content_hash': '17b9633ac5cab6e196f0418cd3455537', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 78, 'avg_line_length': 20.182926829268293, 'alnum_prop': 0.7087613293051359, 'repo_name': 'junehappylove/june_web_new', 'id': '1636c9f674bd5ebcc2c7442302d4e13c5dd56ea2', 'size': '2024', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/june/dto/back/demo/TreeGridDto.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '256048'}, {'name': 'FreeMarker', 'bytes': '74'}, {'name': 'HTML', 'bytes': '18205'}, {'name': 'Java', 'bytes': '582281'}, {'name': 'JavaScript', 'bytes': '883753'}, {'name': 'PHP', 'bytes': '178445'}]}
@implementation MoodMessageCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{ if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { self.tagImageView = [[UIImageView alloc] initWithFrame:CGRectZero]; //self.tagImageView.backgroundColor = [UIColor redColor]; [self.contentView addSubview:self.tagImageView]; self.backImageView = [[UIImageView alloc] initWithFrame:CGRectZero]; [self.contentView addSubview:self.backImageView]; self.emptyImageView = [[UIImageView alloc] initWithFrame:CGRectZero]; [self.contentView addSubview:self.emptyImageView]; self.tagLabel = [[UILabel alloc] initWithFrame:CGRectZero]; self.tagLabel.textColor = [UIColor whiteColor]; [self.contentView addSubview:self.tagLabel]; self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectZero]; self.descriptionLabel.numberOfLines = 0; self.descriptionLabel.textColor = [UIColor colorWithWhite:0.510 alpha:1.000]; [self.contentView addSubview:self.descriptionLabel]; self.timeThread = [[UIImageView alloc] initWithFrame:CGRectZero]; self.timeThread.backgroundColor = [UIColor grayColor]; [self.contentView addSubview:self.timeThread]; } return self; } - (void)setValueWithModel:(dayModel *)model{ //标记图片 self.tagImageView.frame = CGRectMake(15, 2, 20, 20); self.tagImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld", model.moodDay]]; //标记背景 self.backImageView.frame = CGRectMake(CGRectGetMaxX(self.tagImageView.frame), self.tagImageView.frame.origin.y, jjScreenWidth - 70, 100); //背景图片处理 UIImage *backImage = [UIImage imageNamed:@"background"]; UIEdgeInsets edgeInsets = UIEdgeInsetsMake(5, 15, 0, 5); // 拉伸图片 UIImage *newImage = [backImage resizableImageWithCapInsets:edgeInsets resizingMode:UIImageResizingModeStretch]; self.backImageView.image = newImage; //标记内容 self.tagLabel.frame = CGRectMake(self.backImageView.frame.origin.x+15, self.backImageView.frame.origin.y + 8, self.backImageView.frame.size.width - 5, 30); self.tagLabel.font = [UIFont systemFontOfSize:17 weight:10]; self.tagLabel.text = [NSString getTagStringTag:model.tagDay]; //记录内容 self.descriptionLabel.text = [NSString stringWithFormat:@"%@\n%@",[NSString getDateStringFromDate:model.dateDay],model.content]; self.descriptionLabel.font = [UIFont systemFontOfSize:14]; CGFloat labelHeight = [GetHeightTool getHeightForText:self.descriptionLabel.text font:[UIFont systemFontOfSize:14] width:jjScreenWidth - 100]; self.descriptionLabel.frame = CGRectMake(CGRectGetMinX(self.backImageView.frame) + 15, CGRectGetMaxY(self.tagLabel.frame)+ 5, self.backImageView.frame.size.width - 20, labelHeight); self.emptyImageView.frame = CGRectMake(self.backImageView.frame.origin.x + 7, CGRectGetMaxY(self.tagLabel.frame), self.backImageView.frame.size.width - 8, self.descriptionLabel.frame.size.height + 10); //背景图片处理 UIImage *image = [UIImage imageNamed:@"empty"]; //上, 左, 下, 右部分不可拉伸的区域 UIEdgeInsets edgeInsets1 = UIEdgeInsetsMake(0, 10, 10, 10); UIImage *newimage = [image resizableImageWithCapInsets:edgeInsets1 resizingMode:UIImageResizingModeStretch]; self.emptyImageView.image = newimage; //时间轴 self.timeThread.frame = CGRectMake(self.tagImageView.center.x - 1, CGRectGetMaxY(self.tagImageView.frame)+1, 2, self.descriptionLabel.frame.size.height + 33); } - (void)awakeFromNib { // Initialization code } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // Configure the view for the selected state } @end
{'content_hash': '896a8222b5596bd706c245acc79ac0f6', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 205, 'avg_line_length': 42.68478260869565, 'alnum_prop': 0.7119938884644768, 'repo_name': 'YunZhiJunXiPeng/ShreddedBread', 'id': '5c6850e14e4f8d181c1e31cd4918254cbdcc5286', 'size': '4247', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ShreddedBread/Scenes/JJStatistics/CustomView/MoodMessageCell.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '260862'}, {'name': 'Ruby', 'bytes': '159'}]}
package org.eclipse.rdf4j.rio.hdt; import java.io.IOException; import java.io.InputStream; import java.util.zip.CheckedInputStream; import org.eclipse.rdf4j.common.io.UncloseableInputStream; /** * Log64 * * It contains the data part of the {@link HDTArray}, followed by the 32-bit CRC calculated over this data. * * Data structure: * * <pre> * ...+---------+-------+ * | entries | CRC32 | * ...+---------+-------+ * </pre> * * Entries are stored little-endian, with each entry using <code>nrbits</code> bits * * @author Bart Hanssens */ class HDTArrayLog64 extends HDTArray { private byte buffer[]; @Override protected int getType() { return HDTArray.Type.LOG64.getValue(); } @Override protected int get(int i) { // start byte of the value, and start bit in that start byte int bytePos = (i * nrbits) / 8; int bitPos = (i * nrbits) % 8; // value bits may be encoded across boundaries of bytes int tmplen = (bitPos + nrbits + 7) / 8; long val = 0L; // little-endian to big-endian for (int j = 0; j < tmplen; j++) { val |= (buffer[bytePos + j] & 0xFFL) << (j * 8); } val >>= bitPos; val &= 0xFFFFFFFFFFFFFFFFL >>> (64 - nrbits); return (int) val; } @Override protected void parse(InputStream is) throws IOException { super.parse(is); // don't close CheckedInputStream, as it will close the underlying inputstream try (UncloseableInputStream uis = new UncloseableInputStream(is); CheckedInputStream cis = new CheckedInputStream(uis, new CRC32())) { // read bytes, minimum 1 long bytes = (nrbits * entries + 7) / 8; if (bytes > Integer.MAX_VALUE) { throw new UnsupportedOperationException("Maximum number of bytes in array exceeded: " + bytes); } buffer = new byte[(int) bytes]; cis.read(buffer); checkCRC(cis, is, 4); } } }
{'content_hash': 'b1116b8f592c0b17f9ca3a314d25a6b9', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 107, 'avg_line_length': 24.4, 'alnum_prop': 0.6513661202185792, 'repo_name': 'eclipse/rdf4j', 'id': 'a571f89d1475b121f9881d7849e470c3c4ee2969', 'size': '2349', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayLog64.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '23587'}, {'name': 'Dockerfile', 'bytes': '791'}, {'name': 'HTML', 'bytes': '70935'}, {'name': 'Java', 'bytes': '15830881'}, {'name': 'JavaScript', 'bytes': '375102'}, {'name': 'Ruby', 'bytes': '36145'}, {'name': 'Shell', 'bytes': '23631'}, {'name': 'TypeScript', 'bytes': '52940'}, {'name': 'XSLT', 'bytes': '144185'}]}
package com.thoughtworks.go.util; import com.thoughtworks.go.agent.ServerUrlGenerator; import com.thoughtworks.go.domain.JobIdentifier; import org.springframework.stereotype.Component; import java.net.URI; import java.net.URISyntaxException; import static java.lang.String.format; @Component public class URLService implements ServerUrlGenerator{ private String baseRemotingURL; public URLService() { String url = new SystemEnvironment().getServiceUrl(); if (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } baseRemotingURL = url; } public URLService(String baseRemotingURL) { this.baseRemotingURL = baseRemotingURL; } public String baseRemoteURL() { return baseRemotingURL; } public String getBuildRepositoryURL() { return baseRemotingURL + "/remoting/remoteBuildRepository"; } public String getAgentRegistrationURL() { return baseRemotingURL + "/admin/agent"; } public String getAgentLatestStatusUrl() { return baseRemotingURL + "/admin/latest-agent.status"; } public String getUploadUrlOfAgent(JobIdentifier jobIdentifier, String filePath) { return getUploadUrlOfAgent(jobIdentifier, filePath, 1); } public String getComponentVersionsOnServerUrl() { return String.format("%s/%s", baseRemotingURL, "admin/component-versions-on-server"); } // TODO - keep buildId for now because currently we do not support 'jobcounter' // and therefore cannot locate job correctly when it is rescheduled public String getUploadUrlOfAgent(JobIdentifier jobIdentifier, String filePath, int attempt) { return format("%s/%s/%s/%s?attempt=%d&buildId=%d", baseRemotingURL, "remoting", "files", jobIdentifier.artifactLocator(filePath), attempt, jobIdentifier.getBuildId()); } /* * Server will use this method, the base url is in the request. */ public String getRestfulArtifactUrl(JobIdentifier jobIdentifier, String filePath) { return format("/%s/%s", "files", jobIdentifier.artifactLocator(filePath)); } public String getUploadBaseUrlOfAgent(JobIdentifier jobIdentifier) { return format("%s/%s/%s/%s", baseRemotingURL, "remoting", "files", jobIdentifier.artifactLocator("")); } /* * Agent will use this method, the baseUrl will be injected from config xml in agent side. * This is used to fix security issues with the agent uploading artifacts when security is enabled. */ public String getPropertiesUrl(JobIdentifier jobIdentifier, String propertyName) { return format("%s/%s/%s/%s", baseRemotingURL, "remoting", "properties", jobIdentifier.propertyLocator(propertyName)); } public String serverUrlFor(String subPath) { return format("%s/%s", baseRemotingURL, subPath); } public String serverSslBaseUrl(int serverHttpsPort) { return baseRemotingURL; } public String getAgentRemoteWebSocketUrl() { return format("%s/%s", getWebSocketBaseUrl(), "agent-websocket"); } public String getWebSocketBaseUrl() { try { URI uri = new URI(baseRemotingURL); StringBuffer ret = new StringBuffer("wss://"); ret.append(uri.getHost()).append(":").append(uri.getPort()); if (uri.getPath() != null) { ret.append(uri.getPath()); } return ret.toString(); } catch (URISyntaxException e) { throw new RuntimeException("Invalid Go Server url", e); } } public String prefixPartialUrl(String url) { if(url.startsWith("/")) { return format("%s%s", baseRemoteURL(), url); } return url; } }
{'content_hash': '093951f53db590dc065c8ab7abe36e5a', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 175, 'avg_line_length': 33.61946902654867, 'alnum_prop': 0.6635956830744932, 'repo_name': 'VibyJocke/gocd', 'id': '7a35ec79a46b08e4c52e08741ac03af6ad8a4b8e', 'size': '4545', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'common/src/com/thoughtworks/go/util/URLService.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '8248'}, {'name': 'CSS', 'bytes': '502291'}, {'name': 'FreeMarker', 'bytes': '182'}, {'name': 'HTML', 'bytes': '647411'}, {'name': 'Java', 'bytes': '16221590'}, {'name': 'JavaScript', 'bytes': '2878258'}, {'name': 'NSIS', 'bytes': '19386'}, {'name': 'PowerShell', 'bytes': '743'}, {'name': 'Ruby', 'bytes': '2954955'}, {'name': 'SQLPL', 'bytes': '9050'}, {'name': 'Shell', 'bytes': '240291'}, {'name': 'XSLT', 'bytes': '153049'}]}
'use strict'; module.exports = function () { this.alert = function () { throw 'Doh! You used a real notifier rather than a test double!'; }; };
{'content_hash': 'df60aba531d968f6828a52645e113116', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 69, 'avg_line_length': 21.857142857142858, 'alnum_prop': 0.6274509803921569, 'repo_name': 'dwhelan/training', 'id': 'b619376c1ad029817c41c04ba5a8fa1d345467a2', 'size': '153', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/bartender/notifier.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '12876'}, {'name': 'Java', 'bytes': '8799'}, {'name': 'JavaScript', 'bytes': '7733'}, {'name': 'Ruby', 'bytes': '987'}, {'name': 'Shell', 'bytes': '131'}]}
package rest import ( "fmt" "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" extensionsapiv1beta1 "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" extensionsclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion" "k8s.io/kubernetes/pkg/genericapiserver" horizontalpodautoscaleretcd "k8s.io/kubernetes/pkg/registry/autoscaling/horizontalpodautoscaler/etcd" jobetcd "k8s.io/kubernetes/pkg/registry/batch/job/etcd" expcontrolleretcd "k8s.io/kubernetes/pkg/registry/extensions/controller/etcd" daemonetcd "k8s.io/kubernetes/pkg/registry/extensions/daemonset/etcd" deploymentetcd "k8s.io/kubernetes/pkg/registry/extensions/deployment/etcd" ingressetcd "k8s.io/kubernetes/pkg/registry/extensions/ingress/etcd" networkpolicyetcd "k8s.io/kubernetes/pkg/registry/extensions/networkpolicy/etcd" pspetcd "k8s.io/kubernetes/pkg/registry/extensions/podsecuritypolicy/etcd" replicasetetcd "k8s.io/kubernetes/pkg/registry/extensions/replicaset/etcd" thirdpartyresourceetcd "k8s.io/kubernetes/pkg/registry/extensions/thirdpartyresource/etcd" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/wait" ) type RESTStorageProvider struct { ResourceInterface ResourceInterface } var _ genericapiserver.RESTStorageProvider = &RESTStorageProvider{} func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter genericapiserver.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(extensions.GroupName) if apiResourceConfigSource.AnyResourcesForVersionEnabled(extensionsapiv1beta1.SchemeGroupVersion) { apiGroupInfo.VersionedResourcesStorageMap[extensionsapiv1beta1.SchemeGroupVersion.Version] = p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter) apiGroupInfo.GroupMeta.GroupVersion = extensionsapiv1beta1.SchemeGroupVersion } return apiGroupInfo, true } func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter genericapiserver.RESTOptionsGetter) map[string]rest.Storage { version := extensionsapiv1beta1.SchemeGroupVersion storage := map[string]rest.Storage{} if apiResourceConfigSource.ResourceEnabled(version.WithResource("horizontalpodautoscalers")) { hpaStorage, hpaStatusStorage := horizontalpodautoscaleretcd.NewREST(restOptionsGetter(extensions.Resource("horizontalpodautoscalers"))) storage["horizontalpodautoscalers"] = hpaStorage storage["horizontalpodautoscalers/status"] = hpaStatusStorage controllerStorage := expcontrolleretcd.NewStorage(restOptionsGetter(api.Resource("replicationControllers"))) storage["replicationcontrollers"] = controllerStorage.ReplicationController storage["replicationcontrollers/scale"] = controllerStorage.Scale } if apiResourceConfigSource.ResourceEnabled(version.WithResource("thirdpartyresources")) { thirdPartyResourceStorage := thirdpartyresourceetcd.NewREST(restOptionsGetter(extensions.Resource("thirdpartyresources"))) storage["thirdpartyresources"] = thirdPartyResourceStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("daemonsets")) { daemonSetStorage, daemonSetStatusStorage := daemonetcd.NewREST(restOptionsGetter(extensions.Resource("daemonsets"))) storage["daemonsets"] = daemonSetStorage storage["daemonsets/status"] = daemonSetStatusStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("deployments")) { deploymentStorage := deploymentetcd.NewStorage(restOptionsGetter(extensions.Resource("deployments"))) storage["deployments"] = deploymentStorage.Deployment storage["deployments/status"] = deploymentStorage.Status storage["deployments/rollback"] = deploymentStorage.Rollback storage["deployments/scale"] = deploymentStorage.Scale } if apiResourceConfigSource.ResourceEnabled(version.WithResource("jobs")) { jobsStorage, jobsStatusStorage := jobetcd.NewREST(restOptionsGetter(extensions.Resource("jobs"))) storage["jobs"] = jobsStorage storage["jobs/status"] = jobsStatusStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("ingresses")) { ingressStorage, ingressStatusStorage := ingressetcd.NewREST(restOptionsGetter(extensions.Resource("ingresses"))) storage["ingresses"] = ingressStorage storage["ingresses/status"] = ingressStatusStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("podsecuritypolicy")) { podSecurityExtensionsStorage := pspetcd.NewREST(restOptionsGetter(extensions.Resource("podsecuritypolicy"))) storage["podSecurityPolicies"] = podSecurityExtensionsStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("replicasets")) { replicaSetStorage := replicasetetcd.NewStorage(restOptionsGetter(extensions.Resource("replicasets"))) storage["replicasets"] = replicaSetStorage.ReplicaSet storage["replicasets/status"] = replicaSetStorage.Status storage["replicasets/scale"] = replicaSetStorage.Scale } if apiResourceConfigSource.ResourceEnabled(version.WithResource("networkpolicies")) { networkExtensionsStorage := networkpolicyetcd.NewREST(restOptionsGetter(extensions.Resource("networkpolicies"))) storage["networkpolicies"] = networkExtensionsStorage } return storage } func (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error) { return "extensions/third-party-resources", p.postStartHookFunc, nil } func (p RESTStorageProvider) postStartHookFunc(hookContext genericapiserver.PostStartHookContext) error { clientset, err := extensionsclient.NewForConfig(hookContext.LoopbackClientConfig) if err != nil { utilruntime.HandleError(fmt.Errorf("unable to initialize clusterroles: %v", err)) return nil } thirdPartyControl := ThirdPartyController{ master: p.ResourceInterface, client: clientset, } go wait.Forever(func() { if err := thirdPartyControl.SyncResources(); err != nil { glog.Warningf("third party resource sync failed: %v", err) } }, 10*time.Second) return nil }
{'content_hash': '8b3f61eaebe03acd27711fe244102bd2', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 203, 'avg_line_length': 48.390625, 'alnum_prop': 0.8224087826929286, 'repo_name': 'linearregression/kubernetes', 'id': 'f7e4497b5edcd195cb2915bd1158290f75fed077', 'size': '6763', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pkg/registry/extensions/rest/storage_extensions.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '978'}, {'name': 'Go', 'bytes': '44736541'}, {'name': 'HTML', 'bytes': '2530253'}, {'name': 'Makefile', 'bytes': '72431'}, {'name': 'Nginx', 'bytes': '1013'}, {'name': 'Protocol Buffer', 'bytes': '580076'}, {'name': 'Python', 'bytes': '918751'}, {'name': 'SaltStack', 'bytes': '54088'}, {'name': 'Shell', 'bytes': '1542252'}]}
/* * Copyright 2005 Jenia org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fckfaces.util; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author srecinto */ public class Servlet extends HttpServlet { private static final long serialVersionUID = 7260045528613530636L; private static final String modify=calcModify(); private volatile String customResourcePath; private static final String calcModify() { Date mod = new Date(System.currentTimeMillis()); SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z",Locale.ENGLISH); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf.format(mod); } public void init(ServletConfig config) throws ServletException { super.init(config); setCustomResourcePath(config.getInitParameter("customResourcePath")); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // search the resource in classloader ClassLoader cl = this.getClass().getClassLoader(); String uri = request.getRequestURI(); String path = uri.substring(uri.indexOf(Util.FCK_FACES_RESOURCE_PREFIX)+Util.FCK_FACES_RESOURCE_PREFIX.length()+1); if(getCustomResourcePath() != null) { //Use custom path to FCKeditor this.getServletContext().getRequestDispatcher(getCustomResourcePath() + path).forward(request,response); } else { //Use default FCKeditor bundled up in the jar if (uri.endsWith(".jsf") || uri.endsWith(".html")) { response.setContentType("text/html;charset=UTF-8"); } else { response.setHeader("Cache-Control", "public"); response.setHeader("Last-Modified", modify); } if (uri.endsWith(".css")) { response.setContentType("text/css;charset=UTF-8"); } else if (uri.endsWith(".js")) { response.setContentType("text/javascript;charset=UTF-8"); } else if (uri.endsWith(".gif")) { response.setContentType("image/gif;"); } else if (uri.endsWith(".xml")) { response.setContentType("text/xml;charset=UTF-8"); } InputStream is = cl.getResourceAsStream(path); // if no resource found in classloader return nothing if (is==null) return; // resource found, copying on output stream OutputStream out = response.getOutputStream(); byte[] buffer = new byte[2048]; BufferedInputStream bis = new BufferedInputStream(is); try { int read = 0; read = bis.read(buffer); while (read!=-1) { out.write(buffer,0,read); read = bis.read(buffer); } } finally { bis.close(); } out.flush(); out.close(); } } public String getCustomResourcePath() { return customResourcePath; } public void setCustomResourcePath(String customResourcePath) { synchronized (this) { this.customResourcePath = customResourcePath; } } }
{'content_hash': '6ed42d7c56e7b81ce6d2b58bc6d4a0ab', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 123, 'avg_line_length': 35.44827586206897, 'alnum_prop': 0.6551556420233463, 'repo_name': 'GIP-RECIA/esco-grouper-ui', 'id': '27e498d6a8afc95cc0fca7adba5b38bfd7c7dc9d', 'size': '4898', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ext/esup-commons/src/main/java/org/fckfaces/util/Servlet.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '218175'}, {'name': 'Java', 'bytes': '6786611'}, {'name': 'JavaScript', 'bytes': '1616913'}, {'name': 'Shell', 'bytes': '3445'}, {'name': 'XSLT', 'bytes': '3601'}]}
namespace performance_manager { NodeAttachedData::NodeAttachedData() = default; NodeAttachedData::~NodeAttachedData() = default; // static void NodeAttachedDataMapHelper::AttachInMap( const Node* node, std::unique_ptr<NodeAttachedData> data) { GraphImpl* graph = GraphImpl::FromGraph(node->GetGraph()); DCHECK_CALLED_ON_VALID_SEQUENCE(graph->sequence_checker_); const NodeBase* node_base = NodeBase::FromNode(node); DCHECK(graph->NodeInGraph(node_base)); GraphImpl::NodeAttachedDataKey data_key = std::make_pair(node, data->GetKey()); auto& map = graph->node_attached_data_map_; DCHECK(!base::Contains(map, data_key)); map[data_key] = std::move(data); } // static NodeAttachedData* NodeAttachedDataMapHelper::GetFromMap(const Node* node, const void* key) { GraphImpl* graph = GraphImpl::FromGraph(node->GetGraph()); DCHECK_CALLED_ON_VALID_SEQUENCE(graph->sequence_checker_); const NodeBase* node_base = NodeBase::FromNode(node); DCHECK(graph->NodeInGraph(node_base)); GraphImpl::NodeAttachedDataKey data_key = std::make_pair(node, key); auto& map = graph->node_attached_data_map_; auto it = map.find(data_key); if (it == map.end()) return nullptr; DCHECK_EQ(key, it->second->GetKey()); return it->second.get(); } // static std::unique_ptr<NodeAttachedData> NodeAttachedDataMapHelper::DetachFromMap( const Node* node, const void* key) { GraphImpl* graph = GraphImpl::FromGraph(node->GetGraph()); DCHECK_CALLED_ON_VALID_SEQUENCE(graph->sequence_checker_); const NodeBase* node_base = NodeBase::FromNode(node); DCHECK(graph->NodeInGraph(node_base)); GraphImpl::NodeAttachedDataKey data_key = std::make_pair(node, key); auto& map = graph->node_attached_data_map_; auto it = map.find(data_key); std::unique_ptr<NodeAttachedData> data; if (it != map.end()) { data = std::move(it->second); map.erase(it); } return data; } } // namespace performance_manager
{'content_hash': 'd91851c7c5cd4f0c2fd415f222c6fd67', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 75, 'avg_line_length': 34.016949152542374, 'alnum_prop': 0.6885899352267065, 'repo_name': 'scheib/chromium', 'id': '666e7ba3a732469d807ea3b7ac06677e581efc11', 'size': '2452', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'components/performance_manager/graph/node_attached_data.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-comp-4914', templateUrl: './comp-4914.component.html', styleUrls: ['./comp-4914.component.css'] }) export class Comp4914Component implements OnInit { constructor() { } ngOnInit() { } }
{'content_hash': 'a64eea122cb5b0989b2721b78d29778c', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 50, 'avg_line_length': 16.58823529411765, 'alnum_prop': 0.6666666666666666, 'repo_name': 'angular/angular-cli-stress-test', 'id': '12ea09fdbaa297c871b09ec8014594b826b15282', 'size': '484', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/app/components/comp-4914/comp-4914.component.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1040888'}, {'name': 'HTML', 'bytes': '300322'}, {'name': 'JavaScript', 'bytes': '2404'}, {'name': 'TypeScript', 'bytes': '8535506'}]}
package org.apache.flink.runtime.webmonitor; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.time.Time; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.runtime.checkpoint.CompletedCheckpoint; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.executiongraph.AccessExecutionGraph; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobmaster.JobResult; import org.apache.flink.runtime.jobmaster.RescalingBehaviour; import org.apache.flink.runtime.messages.Acknowledge; import org.apache.flink.runtime.messages.FlinkJobNotFoundException; import org.apache.flink.runtime.messages.webmonitor.ClusterOverview; import org.apache.flink.runtime.messages.webmonitor.MultipleJobsDetails; import org.apache.flink.runtime.metrics.dump.MetricQueryService; import org.apache.flink.runtime.rest.handler.legacy.backpressure.OperatorBackPressureStatsResponse; import org.apache.flink.runtime.rpc.RpcEndpoint; import org.apache.flink.runtime.rpc.RpcGateway; import org.apache.flink.runtime.rpc.RpcTimeout; import java.util.Collection; import java.util.concurrent.CompletableFuture; /** * Gateway for restful endpoints. * * <p>Gateways which implement this method run a REST endpoint which is reachable * under the returned address. */ public interface RestfulGateway extends RpcGateway { /** * Cancel the given job. * * @param jobId identifying the job to cancel * @param timeout of the operation * @return A future acknowledge if the cancellation succeeded */ CompletableFuture<Acknowledge> cancelJob(JobID jobId, @RpcTimeout Time timeout); /** * Stop the given job. * * @param jobId identifying the job to stop * @param timeout of the operation * @return A future acknowledge if the stopping succeeded */ CompletableFuture<Acknowledge> stopJob(JobID jobId, @RpcTimeout Time timeout); /** * Requests the REST address of this {@link RpcEndpoint}. * * @param timeout for this operation * @return Future REST endpoint address */ CompletableFuture<String> requestRestAddress(@RpcTimeout Time timeout); /** * Requests the {@link AccessExecutionGraph} for the given jobId. If there is no such graph, then * the future is completed with a {@link FlinkJobNotFoundException}. * * @param jobId identifying the job whose AccessExecutionGraph is requested * @param timeout for the asynchronous operation * @return Future containing the AccessExecutionGraph for the given jobId, otherwise {@link FlinkJobNotFoundException} */ CompletableFuture<? extends AccessExecutionGraph> requestJob(JobID jobId, @RpcTimeout Time timeout); /** * Requests the {@link JobResult} of a job specified by the given jobId. * * @param jobId identifying the job for which to retrieve the {@link JobResult}. * @param timeout for the asynchronous operation * @return Future which is completed with the job's {@link JobResult} once the job has finished */ CompletableFuture<JobResult> requestJobResult(JobID jobId, @RpcTimeout Time timeout); /** * Requests job details currently being executed on the Flink cluster. * * @param timeout for the asynchronous operation * @return Future containing the job details */ CompletableFuture<MultipleJobsDetails> requestMultipleJobDetails( @RpcTimeout Time timeout); /** * Requests the cluster status overview. * * @param timeout for the asynchronous operation * @return Future containing the status overview */ CompletableFuture<ClusterOverview> requestClusterOverview(@RpcTimeout Time timeout); /** * Requests the paths for the {@link MetricQueryService} to query. * * @param timeout for the asynchronous operation * @return Future containing the collection of metric query service paths to query */ CompletableFuture<Collection<String>> requestMetricQueryServicePaths(@RpcTimeout Time timeout); /** * Requests the paths for the TaskManager's {@link MetricQueryService} to query. * * @param timeout for the asynchronous operation * @return Future containing the collection of instance ids and the corresponding metric query service path */ CompletableFuture<Collection<Tuple2<ResourceID, String>>> requestTaskManagerMetricQueryServicePaths(@RpcTimeout Time timeout); /** * Triggers a savepoint with the given savepoint directory as a target. * * @param jobId ID of the job for which the savepoint should be triggered. * @param targetDirectory Target directory for the savepoint. * @param timeout Timeout for the asynchronous operation * @return A future to the {@link CompletedCheckpoint#getExternalPointer() external pointer} of * the savepoint. */ default CompletableFuture<String> triggerSavepoint( JobID jobId, String targetDirectory, boolean cancelJob, @RpcTimeout Time timeout) { throw new UnsupportedOperationException(); } /** * Dispose the given savepoint. * * @param savepointPath identifying the savepoint to dispose * @param timeout RPC timeout * @return A future acknowledge if the disposal succeeded */ default CompletableFuture<Acknowledge> disposeSavepoint( final String savepointPath, @RpcTimeout final Time timeout) { throw new UnsupportedOperationException(); } /** * Request the {@link JobStatus} of the given job. * * @param jobId identifying the job for which to retrieve the JobStatus * @param timeout for the asynchronous operation * @return A future to the {@link JobStatus} of the given job */ default CompletableFuture<JobStatus> requestJobStatus( JobID jobId, @RpcTimeout Time timeout) { throw new UnsupportedOperationException(); } /** * Requests the statistics on operator back pressure. * * @param jobId Job for which the stats are requested. * @param jobVertexId JobVertex for which the stats are requested. * @return A Future to the {@link OperatorBackPressureStatsResponse} or {@code null} if the stats are * not available (yet). */ default CompletableFuture<OperatorBackPressureStatsResponse> requestOperatorBackPressureStats( JobID jobId, JobVertexID jobVertexId) { throw new UnsupportedOperationException(); } /** * Trigger rescaling of the given job. * * @param jobId specifying the job to rescale * @param newParallelism new parallelism of the job * @param rescalingBehaviour defining how strict the rescaling has to be executed * @param timeout of this operation * @return Future which is completed with {@link Acknowledge} once the rescaling was successful */ default CompletableFuture<Acknowledge> rescaleJob( JobID jobId, int newParallelism, RescalingBehaviour rescalingBehaviour, @RpcTimeout Time timeout) { throw new UnsupportedOperationException(); } default CompletableFuture<Acknowledge> shutDownCluster() { throw new UnsupportedOperationException(); } }
{'content_hash': '5bf4160c1bf25c03ed67dd1d109e915f', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 127, 'avg_line_length': 36.58115183246073, 'alnum_prop': 0.7688564476885644, 'repo_name': 'zhangminglei/flink', 'id': '6a6c34b90db227e5e19f530d1f253b8ddc8af25c', 'size': '7792', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'flink-runtime/src/main/java/org/apache/flink/runtime/webmonitor/RestfulGateway.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5666'}, {'name': 'CSS', 'bytes': '18100'}, {'name': 'Clojure', 'bytes': '63105'}, {'name': 'CoffeeScript', 'bytes': '91220'}, {'name': 'Dockerfile', 'bytes': '3528'}, {'name': 'HTML', 'bytes': '86821'}, {'name': 'Java', 'bytes': '39364056'}, {'name': 'JavaScript', 'bytes': '8267'}, {'name': 'Python', 'bytes': '249644'}, {'name': 'Scala', 'bytes': '7201411'}, {'name': 'Shell', 'bytes': '282124'}]}
# Kinvey GeoTag This is a Kinvey sample app, to location-based search, 3rd-Party location services, Push notifications, and Business Logic with Collection Hooks and Custom Endpoints. In particular in addition to showing location-based data, this app allows user actions to trigger push notifications to other users that are near new notes and are interested in certain tags. For more details about location, see the blog post at http://goo.gl/9dyMm. For more details about business logic, see http://devcenter.kinvey.com/ios/guides/business-logic. ## Using the App The app shows a map highlighting the user's current location. The map is annotated with nearby hotels (from the 3rd-paty location service) as well as yours and other user's notes that match your selected tags. Tap the "page curl" button to see a list of nearby tags. Selecting a tag will cause the user to subscribe to be notified for new notes with that tag as well as display those notes on the map. To enter a new note, type in the text field. Any word preceded by a `#` will be added as a tag. ## Set-up ### Set up the App in Xcode Also, you have to update `app-key` and `app-secret` in the file `KGAAppDelegate.m` to your app-key and app-secret from the Kinvey console. To enable push, you need a push certificate from the Apple developer portal. Upload to Kinvey (under the push configuration) and enter the `Push Key` and `Push Secret` in the file `KGAAppDelegate.m. ### Set up Locations services To enable Data Integration with this app, just * Go to the **Locations** Add-On and select a provider. For example, choose "FourSquare" ![Enable Data Integration](https://github.com/KinveyApps/GeoTag-iOS/raw/master/Screenshots/Enable.png "Enable Data Integration") * Name the endpoint `hotels` and enter your foursquare credentials. Then press `Create Configuration`. ![Enter Credentials](https://github.com/KinveyApps/GeoTag-iOS/raw/master/Screenshots/Active.png "Enter Credentials") ### Set up Collection Hook To Automatically Push to Nearby users 1. From the `Addons` -> `Data & Storage` -> `Data Store` menu, add a new collection and call it `mapNotes`. 2. From the `Addons` -> `Business Logic` -> `Collection Hooks` menu, select the `mapNotes` collection in the left menu. 3. Select __`After` every `Save` run this function__ from the javascript area. 4. Enter the code from [`after_save_mapnotes.js`](https://github.com/KinveyApps/GeoTag-iOS/raw/master/after_save_mapnotes.js) in the code window: ``` function onPostSave(request, response, modules){ var push = modules.push, collectionAccess = modules.collectionAccess, logger = modules.logger; var userCollection = collectionAccess.collection('user'); var body = request.body; if (body.tags && body._geoloc) { logger.info("added map note with tags: " + body.tags +", location: "+ body._geoloc); var distanceInMiles = 5.0 /*5 mi radius*/ / 3963.192; var query = {"tags": {"$in":body.tags}, "_geoloc":{"$nearSphere": body._geoloc,"$maxDistance":distanceInMiles}}; userCollection.find(query, function (err, userColl) { logger.info("got " + userColl.length + " users with matching tags."); if (err) { logger.error('Query failed: '+ err); } else { userColl.forEach(function (user) { logger.info('Pushing message to ' + user.username); push.send(user, "New notes for tag(s): " + body.tags); }); } response.continue(); }); } else { logger.info("no tags in " + body); response.continue(); } } ``` This code does the following: 1. Extracts any tags and location from the just saved `MapNote` object. 2. Searches the user collection for users that are (a) last within 5 miles of the note, and (b) have subscribed at least of the new note's tags in it's `tags` field. 3. For each of the users that satisfy these requirements, send a push notification letting them know a new note is available for those tags. 4. __Next Step:__ An even better form of the push notification would be include the note's `_id` and just reload that note. Right now the app just displays an alert and reloads all the notes. ### Set up Custom Endpoint 1. From the `Addons` -> `Business Logic` -> `Custom Endpoints` menu, create a new endpoint called `tagsNearMe`. 2. Enter the code from [`tagsNearMe.js`](https://github.com/KinveyApps/GeoTag-iOS/raw/master/tagsNearMe.js) in the code window: ``` function getTags(request,response,modules,user) { var headers = {"Authorization":request.headers.authorization}; //re-use the current user's ACLs rather than master secret var loc = user._geoloc; var qs = '{"_geoloc":{"$nearSphere":['+loc+'],"$maxDistance":"10"}}'; //find notes within 10 miles var uri = 'https://' + request.headers.host + '/appdata/'+request.appKey+'/mapNotes/?query='+qs; //build the request modules.request.get({uri: uri, headers: headers}, function(error, res, body){ if (error){ modules.logger.error(error); response.body = {error: error.message}; response.complete(res.status); } else { //iterate through all the notes and count the tags var elements = JSON.parse(body); var tags = {}; elements.forEach(function(doc){ doc.tags.forEach(function(tagar) { if (tags[tagar]) { tags[tagar]++; } else { tags[tagar] = 1; } }); }); response.body = tags; //return all the tags with their count, could create a count threshold in the future response.complete(200); } }); } function onRequest(request, response, modules){ var collectionAccess = modules.collectionAccess; //find the current user in the user collection collectionAccess.collection('user').find({"username": request.username}, function (err, userColl) { if (err) { response.body = {error: error.message}; response.complete(434); } else { getTags(request,response,modules,userColl[0]); } }); } ``` This code does the following: 1. The `onRequest` method is called when the request comes in. 2. This method looks up the user using `collectionAccess`. The user object is needed to obtain the user's location. 3. In `getTags()` a call is made "as the user" using the user's `Authorization` header to `mapNotes` collection. This is done in order to respect the user's ACLs (as collectionAccess is done as the "master secret"). For GeoTag, this should not make a difference since `mapNotes` is globally readable by default. 4. If the response is successful, it will be an array of `MapNotes` objects. This array is iterated over and the each of the tags is counted in a running total. 5. After all the notes are counted, the totals object is returned to the app. 6. __Next Step:__ A good next step is to limit the tags to the 20 most popular, or only display tags that have been used 5 or more times in order to limit the noisiness of the data. __NOTE:__ it is important to `complete()` the response in all terminal branches, or the client will timeout waiting for a response. ## System Requirements * Xcode 4.5+ * iPad/iPhone/iPod Touch * iOS 6+ * KinveyKit 1.17.0+ ## Contact Website: [www.kinvey.com](http://www.kinvey.com) Support: [[email protected]](http://docs.kinvey.com/mailto:[email protected]) ## License Copyright (c) 2013 Kinvey, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
{'content_hash': 'ddb5b564568a45b03101ca899f155f7f', 'timestamp': '', 'source': 'github', 'line_count': 157, 'max_line_length': 311, 'avg_line_length': 49.67515923566879, 'alnum_prop': 0.7218874214642903, 'repo_name': 'hraschke/spotl_kinvstart_loc', 'id': '1e02cb366a1543528b77a0dd1b5ca6e4a0583b67', 'size': '7799', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1050'}, {'name': 'C++', 'bytes': '1771'}, {'name': 'JavaScript', 'bytes': '2531'}, {'name': 'Objective-C', 'bytes': '261794'}, {'name': 'Shell', 'bytes': '1993'}]}
#ifndef __parserclass__ #define __parserclass__ #include <pelet/LexicalAnalyzerClass.h> #include <pelet/TokenClass.h> #include <pelet/ParserTypeClass.h> #include <unicode/unistr.h> #include <pelet/Api.h> /** \mainpage pelet: Php Easy LanguagE Toolkit. A C++ library for analyzing PHP source code \section Overview This doc briefly describes the major design of the pelet parser library. pelet has the folowing major components: - Parser - Lexer - Parser Implementation \section Parser The pelet::ParserClass, along with pelet::ClassObserverClass, pelet::ClassMemberObserverClass, pelet::FunctionObserverClass, pelet::VariableObserverClass, and pelet::ExpressionObserverClass, make up the "driver" (or main entry point) to pelet. ParserClass takes as input a string (or file) of PHP source code and extracts artifacts from it (classes, functions, methods, etc..). To use the parser, a user will create a class that defines the callbacks for each PHP artifact (class, function, method, etc). The user will register these callbacks with the parser. When pelet::ParserClass::ScanFile is called, the bison parser rules start looking for syntax rules. The parser will ask the lexer for tokens. As soon as a specific rule is hit, then the proper parser observer callback gets called. For example, when the parser hits the "class" rule (ie "class MyClass {") then the class observer will get called; and the observer will get the identifer ("MyClass") along with other info (signature, comment). The important thing to note here is that the callbacks happen while ParserClass::ScanFile still has control. ParserClass::ScanFile does not return control until the entire file has been parsed; multiple callbacks will have been called before ParserClass::ScanFile returns. For this reason, it is important that ParserClass::ScanFile should not be called within any of the observers. A word on concurrency: The pelet parser does not keep global state (it is a "pure" bison parser), but the pelet parser is not thread-safe. If pelet is used on a multi-threaded app, each thread should have its own instance of pelet::ParserClass. \section Lexer The pelet::LexicalAnalyzerClass is used to tokenize the source code (turn strings into tokens). The details of the implementation can be found in the \ref LexerDetailsPage page. \section ParserImplementation Parser Implementation This is a parser generated with the help of Bison. This used to follow the PHP rules; for example after "function" comes the function name; after "if" comes a "(" and so on...) When the syntax rules hit an artifact (for example a class) the syntax rules will call the proper observer. The details of the implementation can be found in the \ref ParserImplementationDetailsPage page. */ namespace pelet { /** * Holds the results of the lint check. Currently lint check will stop when * the first error is encountered. */ class PELET_API LintResultsClass { public: /** * A short description of the error; this is generated by the bison parser and is * not the most user-friendly but it is exactly what PHP displays; might as well * keep it consistant. */ UnicodeString Error; /** * Path to the file in which the error ocurred. * This is what was given to the LintFile() method or ScanFile(std::string, LintResultsClass&) method. * For LintString() results this will be the empty string. */ std::string File; /** * Path to the file in which the error ocurred. * This is what was given to the LintFile() or ScanFile(FILE*, UnicodeString, LintResultsClass&) method. * For LintString() results this will be the empty string. */ UnicodeString UnicodeFilename; /** * If the parser encountered a syntax error, then this object will be filled with * the last known class/method/function where the error occurred. */ pelet::ScopeClass Scope; /** * The line in which the error ocurred. This is 1-based. */ int LineNumber; /** * The character offset in which the error ocurred (with regargs to the start of * the file). This is 0-based. */ int CharacterPosition; LintResultsClass(); /** * copy the attributes from src to this object. */ void Copy(const LintResultsClass& src); /** * remove any error string */ void Clear(); }; /** * The parser class is designed in a way that can utilized by different pieces of code. The parser will analyze * given code and make calls to the different registered observers. There are observers for classes, functions, and * methods. Not all observers have to be set; for example if a FunctionObserverClass is never registered then the * parser will not notify when a function has been found in a piece of code. * * @code * class EchoAndObserverClass : public ClassObserverClass { * * virtual void ClassFound(const UnicodeString& className, const UnicodeString& signature, * const UnicodeString& comment) { * printf("Found Class %s\n", (const char*)className.ToUTF8()); * } * } * * EchoAndObserverClass echoObserver; * ParserClass parser; * parser.SetClassObserver(&echoObserver); * wxString someFileName = wxT("/some/file.php"); * if (!parser.ScanFile(someFileName)) { * puts("Could not find file to parse!"); * } * @endcode * * Observers follow the PHP parsing rules to the letter. If source code is not valid; then observers may not * get called. * * Lint functionality * * The parser class has the ability to check PHP code for syntax errors. This is done via the LintXXX() methods. * * @code * ParserClass parser; * std::string file = "/path/to/phpfile.php"; * LintResultsClass lintResults; * if (parser.LintFile(file, parserResults)) { * printf("No syntax errors in file %s", (const char*)file.c_str()); * } * else { * printf("%s. Error found in file %s on line %d.\n", parserResults.Error, file.c_str(), parserResults.LineNumber); * } * @endcode */ class PELET_API ParserClass { public: ParserClass(); /** * Opens and scans the given file; This function will return once the entire * file has been parsed; it will call the proper observers when it encounters * a class, function, or variable declaration. This means that this * parser should not be modified in the observer calls. * * This is a convenience method, it does no handle unicode file names. For that, * see ScanFile(FILE*, UnicodeString, LintResultsClass) * * @param file the file to parse. Must be a full path. * @param LintResultsClass& results any error message will be populated here * @return bool if file was found and could be parsed successfully */ bool ScanFile(const std::string& file, LintResultsClass& results); /** * Opens and scans the given file; This function will return once the entire * file has been parsed; it will call the proper observers when it encounters * a class, function, or variable declaration. This means that this * parser should not be modified in the observer calls. * This method is given a file pointer, it is useful for example when a file * with a unicode filename is opened by the caller. * * @param file the file to parse, this class will NOT own the file pointer * @param fileName this is the name that will be set in results.UnicodeFilename when an error happens * @param LintResultsClass& results any error message will be populated here * @return bool if file was found and could be parsed successfully */ bool ScanFile(FILE* file, const UnicodeString& fileName, LintResultsClass& results); /** * Scans the given string. This function will return once the entire * string has been parsed; it will call the proper observers when it encounters * a class, function, or variable declaration. This means that this * parser should not be modified in the observer calls. * * @param const UnicodeString& code the code to parse. * @param LintResultsClass& results any error message will be populated here * @return bool if string could be parsed successfully */ bool ScanString(const UnicodeString& code, LintResultsClass& results); /** * Change the version that this parser can handle. This needs to be called BEFORE ScanFile() or * ScanString() */ void SetVersion(Versions version); /** * Set the class observer. The observer will get notified when a class is encountered. * Memory management of this pointer should be done by the caller. * * @param ClassObserverClass* observer the object to sent notifications to */ void SetClassObserver(ClassObserverClass* observer); /** * Set the class member observer. The observer will get notified when a class member is encountered. * Memory management of this pointer should be done by the caller. * * @param ClassMemberObserverClass* observer the object to sent notifications to */ void SetClassMemberObserver(ClassMemberObserverClass* observer); /** * Set the function observer. The observer will get notified when a function is encountered. * Memory management of this pointer should be done by the caller. * * @param FunctionObserverClass* observer the object to sent notifications to */ void SetFunctionObserver(FunctionObserverClass* observer); /** * Set the variable observer. The observer will get notified when a new variable has been created. * Memory management of this pointer should be done by the caller. * * There are performance implications if you call this method; if you want to be notified * of variables then the full PHP parser is used; and parsing a file can be memory intensive. * * @param VariableObserverClass* observer the object to sent notifications to */ void SetVariableObserver(VariableObserverClass* observer); /** * Set the expression observer. The observer will get notified when a new expression has been created. * Memory management of this pointer should be done by the caller. * * There are performance implications if you call this method; if you want to be notified * of expressions then the full PHP parser is used; and parsing a file can be memory intensive. * * @param ExpressionObserverClass* observer the object to sent notifications to */ void SetExpressionObserver(ExpressionObserverClass* expressionObserver); /** * Perform a TRUE PHP syntax check on the entire file. This syntax check is based on PHP 5.3 * or PHP 5.4 depending on whether SetVersion() was called. * * Note that this is not entirely the same as 'php -l' command; the PHP lint command detects * duplicate function / class names where as this lint check method does not. * * Returns true if the file had no syntax errors. Note that a file that does not have * any PHP code will be considered a good file (a PHP file that has only HTML is * considered good and true will be returned). * * This is a convenience method; unicode filenames are not handled. * * @param file the file to parse. Must be a full path. * @param LintResultsClass& results any error message will be populated here * @return bool true if file was found and had no syntax errors. */ bool LintFile(const std::string& file, LintResultsClass& results); /** * Perform a TRUE PHP syntax check on the entire file. This syntax check is based on PHP 5.3 * or PHP 5.4 depending on whether SetVersion() was called. * * Note that this is not entirely the same as 'php -l' command; the PHP lint command detects * duplicate function / class names where as this lint check method does not. * * Returns true if the file had no syntax errors. Note that a file that does not have * any PHP code will be considered a good file (a PHP file that has only HTML is * considered good and true will be returned). * * @param FILE* file the file to parse. Must be an opened file pointer, this class will NOT own the file pointer * @param fileName this is the name that will be set in results.UnicodeFilename when an error happens * @param LintResultsClass& results any error message will be populated here * @return bool true if file was found and had no syntax errors. */ bool LintFile(FILE* file, const UnicodeString& filename, LintResultsClass& results); /** * Perform a syntax check on the given source code. Source code is assumed to be * all code (HTML will not be skipped, and will result in syntax errors). The PHP * open tag is optional. * Returns true if the code had no syntax errors. * * @param const UnicodeString& code the actual code to parse. * @param LintResultsClass& results any error message will be populated here * @return bool true if the code has no syntax errors. */ bool LintString(const UnicodeString& code, LintResultsClass& results); /** * @return the character position where the parser is currently parsing. This can be called * inside an observer callback; in which case the character position is right PAST the * current token. */ int GetCharacterPosition() const; /** * Parses a given PHP expression. This method will parse the given expression into a list of * of "chained" calls. * * A PHP expression is * - a variable ($obj) * - a function call (myFunc()) * - an object operation ("$obj->prop") * - a static object operation ("MyClass::Prop") * * Object operations can be chained; like "$obj->prop->anotherFunc()". While indirect variables are allowed * in PHP (ie $this->$prop) this method will not handle them as it is nearly impossible to resolve them at parse time. * * The most extreme example is this expression: "$obj->prop->anotherFunc()" * This method will parse the expression into * $obj * ->prop * ->anotherFunc() * For example, if sourceCode represented this string: * * @code * UnicodeString sourceCode = UNICODE_STRING_SIMPLE(" * class UserClass { * private $name; * * function getName() { * return $this-> * "); * @endcode * then the following C++ code can be used to find a variable's type * * @code * ParserClass parser; * UnicodeString expression = UNICODE_STRING_SIMPLE("$this->"); * pelet::SymbolClass exprResult; * if (parser.ParseExpression(expression, exprResult)) { * // if successful, symbol.Lexeme will be set to "$this" * } * @endcode * * * @param expression the code string of the expression to resolve. This must be the code for a single expression. * Examples: * $anObject * $this->prop * $this->work()->another * $this-> * work()->another * work() * self::prop * self::prop:: * self::func()->prop * parent::prop * parent::fun()->prop * aFunction * An expression can have whitespace like this * $anObject * ->method1() * ->method2() * ->method3() * * A special case that happens when the given expression ends with the object operator: * $this-> * MyClass:: * In this case, the operator will be added the chain list; this way the client code can determine that * the variable name actually ended. * @param expression the expression's name and "chain" list. The properties of this object will be reset every call. */ void ParseExpression(UnicodeString expressionString, pelet::VariableClass& variable); private: /** * Clean up any resources after parsing a file. This is also very important if the * parser opens a string; without closing the string will not be released (if it's a * long string). */ void Close(); /** * Used to tokenize code */ LexicalAnalyzerClass Lexer; /** * Notify the ClassObserver when a class has been found. Memory management of this pointer should be * done by the caller. */ ClassObserverClass* ClassObserver; /** * Notify the ClassMemberObserver when a class member has been found. Memory management of this pointer should be * done by the caller. */ ClassMemberObserverClass* ClassMemberObserver; /** * Notify the FunctionObserver when a function has been found. Memory management of this pointer should be * done by the caller. */ FunctionObserverClass* FunctionObserver; /** * Notify the VariableObserver when a variable has been created. Memory management of this pointer should be * done by the caller. */ VariableObserverClass* VariableObserver; /** * Notify the ExpressionObserver when an expressionhas been found. Memory management of this pointer should be * done by the caller. */ ExpressionObserverClass* ExpressionObserver; /** * The PHP version to handle */ Versions Version; }; } #endif // __parserclass__
{'content_hash': 'f0e910471a31c351c4c7c7f1841f2b0f', 'timestamp': '', 'source': 'github', 'line_count': 440, 'max_line_length': 120, 'avg_line_length': 38.12954545454546, 'alnum_prop': 0.7174107408952732, 'repo_name': 'robertop/pelet', 'id': 'c673ac60abd37abe03ad58f7e01f296b5b3a3b78', 'size': '18051', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/pelet/ParserClass.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '6035243'}, {'name': 'HTML', 'bytes': '12620'}, {'name': 'Lua', 'bytes': '15806'}, {'name': 'Makefile', 'bytes': '2367'}, {'name': 'PHP', 'bytes': '2884'}, {'name': 'Shell', 'bytes': '1468'}, {'name': 'Yacc', 'bytes': '661554'}]}
#pragma once extern "C" { /*! * * \brief Data structure to capture X-12-ARIMA options */ typedef struct __X12ARIMA_OPTIONS__ { // Data section long lStartDate; ///< is the serial date number for the start date of the time series. BOOL monthly; ///< is a flag to indicate whether data is monthly/quarterly. size_t nObs; ///< is the number of observations in the input time series. int transform; ///< Transform section (1=Log, 2=Auto and 3=None) // Outlier BOOL AOOutlier; ///< additive outlier adjustment BOOL TCOutlier; ///< temporary BOOL LSOutlier; ///< level shift outlier adjustment int LSRun; ///< level shift run // Regression section BOOL tradingDayRegression; ///< Calendar adjustment: trading days BOOL EasterRegression; ///< Calendar adjustment: easter holidays BOOL ConstantIntercept; ///< Add a linear trend? // ARIMA Modeling BOOL AutoSelect; ///< RegARIMA Modeling: Automodeling? int P; ///< RegARIMA Modeling: Manual, set the order of AR process int Q; ///< RegARIMA Modeling: Manual, set the order of MA process int D; ///< RegARIMA Modeling: Manual, differencing int PP; ///< RegARIMA Modeling: Manual, the order of seasonal AR process int QQ; ///< RegARIMA Modeling: Manual, the order of seasonal MA process int DD; ///< RegARIMA Modeling: Manual, Seasonal differencing // Forecast int nForecastYears; ///< [in] is the number of years to forecast for. double fAlpha; ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. // Seasonal Adjustment BOOL bSeasonalAdjustFilter; ///< is a switch to include seasonal adjustment in the analysis. int nX11Mode; ///< 1=mult, 2=add, 3=pseudoadd, 4=logadd int nX11Options; ///< 1= x11default, 2=s3x1, 3=s3x3, 4=s3x5, 5=s3x9, 6=s3x15, 7=stable int henderson; ///< henderson filter setting, default=13 }X12ARIMA_OPTIONS; /*! * \sa NDK_GLM_GOF() */ typedef enum { GOF_LLF=1, ///< Log-likelihood goodness of fit measure GOF_AIC=2, ///< Akaike information criterion goodness of fit measure GOF_BIC=3, ///< Bayesian or Schwartz information criterion goodness of fit measure GOF_HQC=4, ///< Hannan–Quinn information criterion goodness of fit measure GOF_RSQ=5, ///< R-squared goodness of fit measure GOF_ARSQ=6 ///< Adjusted R-squared goodness of fit measure }GOODNESS_OF_FIT_FUNC; /*! * \sa NDK_ARMA_FIT() */ typedef enum { FIT_MEAN=1, ///< Fitted conditional mean FIT_STDEV=2, ///< Fitted conditional volatility or standard deviation FIT_RESID=3, ///< Raw residuals (actual - fitted mean) FIT_STD_RESID=4 ///< Standardized residuals - (actual - fitted mean)/fitted volatility }FIT_RETVAL_FUNC; /*! * \sa NDK_ARMA_RESID() */ typedef enum { RESIDS_STD=1, ///< Standardized residuals RESIDS_RAW=2 ///< Raw residuals }RESID_RETVAL_FUNC; /*! * \sa NDK_ARMA_PARAM() */ typedef enum { PARAM_GUESS=1, ///< Quick guess (non-optimal) of parameters values PARAM_CALIBRATE=2, ///< Run a calibration process to find optimal values for the model's parameters PARAM_ERROR=3 ///< Compute the standard error of the parameters' values }MODEL_RETVAL_FUNC; /*! * \sa NDK_ARMA_FORE() */ typedef enum { FORECAST_MEAN=1, ///< Mean forecast value FORECAST_STDEV=2, ///< Forecast standard error (aka local volatility) FORECAST_TS_STDEV=3, ///< Volatility term structure FORECAST_LL=4, ///< Lower limit of the forecast confidence interval FORECAST_UL=5 ///< Upper limit of the forecast confidence interval }FORECAST_RETVAL_FUNC; /*! * \ingroup statistical testing * \brief Supported statistical test outputs * \sa NDK_MEANTEST() */ typedef enum { TEST_PVALUE=1, ///< P-value TEST_SCORE=2, ///< Test statistics (aka score) TEST_CRITICALVALUE=3 ///< Critical value }TEST_RETURN; /*! * \ingroup statistical testing * \sa NDK_NORMALTEST() */ typedef enum { NORMALTEST_JB=1, ///< Jacque-Berra NORMALTEST_WS=2, ///< Shapiro-Wilson NORMALTEST_CHISQ=3 ///< Chi-Square test - Doornik and Hansen, "An Omnibus Test for Normality", 1994. }NORMALTEST_METHOD; /*! * \ingroup statistical testing * \sa NDK_ADFTEST() */ typedef enum { ADFTEST_DRIFT_ONLY=1, ///< Model 1: A stochastic drift ADFTEST_DRIFT_N_CONST=2, ///< Model II: A deterministic constant and stochastic drift ADFTEST_DRIFT_N_TREND =3, ///< Model III: A deterministic trend and stochastic drift ADFTEST_DRIFT_N_CONST_N_TREND =4, ///< Model IV: A deterministic constant, trend and stochastic drift ADFTEST_DRIFT_N_CONST_TREND_TREND2 =5 ///< Model V: A deterministic constant, trend, trend^2 and stochastic drift }ADFTEST_OPTION; /*! * \brief Support correlation methods * \sa NDK_XCFTEST(), NDK_XCF() */ typedef enum { XCF_PEARSON=1, ///< Pearson XCF_SPEARMAN=2, ///< Spearman XCF_KENDALL=3 ///< Kendall }CORRELATION_METHOD; /*! * \brief Supported Link function * \sa NDK_GLM_GOF() */ typedef enum { GLM_LVK_IDENTITY=1, ///< Identity (default) GLM_LVK_LOG=2, ///< Log GLM_LVK_LOGIT=3, ///< Logit GLM_LVK_PROBIT=4, ///< Probit GLM_LVK_CLOGLOG=5 ///< Complementary log-log }GLM_LINK_FUNC; /*! * \brief Supported innovation types * \sa NDK_GARCH_PARAM(), */ typedef enum { INNOVATION_GAUSSIAN=1, ///< Gaussian or normal distribution INNOVATION_TDIST=2, ///< Standardized student's T-distribution INNOVATION_GED=3 ///< Standardized generalized error distribution (GED) }INNOVATION_TYPE; /*! * \brief Supported innovation types * \sa NDK_TREND() */ typedef enum { TREND_LINEAR=1, ///< Linear time trend TREND_POLYNOMIAL=2, ///< Polynomial time trend TREND_EXPONENTIAL=3, ///< Exponential time trend TREND_LOGARITHMIC=4, ///< Logarithmic time trend TREND_POWER=5 ///< Power time trend }TREND_TYPE; /*! * \brief multi-colinearity test method * \sa NDK_COLNRTY_TEST() */ typedef enum { COLNRTY_CN=1, ///< Condition Number COLNRTY_VIF=2, ///< Variation Inflation Factor (VIF) COLNRTY_DET=3, ///< Determinant COLNRTY_EIGEN=4 ///< Eigenvalues }COLNRTY_TEST_TYPE; /*! * \brief Periodogram method options * \sa NDK_PERIODOGRAM() */ typedef enum { PERIODOGRAM_NONE=1, ///< don't process the input data PERIODOGRAM_DETREND=2, ///< detrend the input data PERIODOGRAM_DIFFERENCE=3, ///< difference the time series (1,1) PERIODOGRAM_AUTOPROC=4 ///< Auto-process (e.g. detrend, difference, etc.) the input data. }PERIODOGRAM_OPTION_TYPE; /*! * \brief Imputation methods for resampling * \sa NDK_RESAMPLE() */ typedef enum { IMPUTATION_NONE = 0, ///< don't process the input data IMPUTATION_INTERPOLATE_FWD = 1, ///< flat forward IMPUTATION_INTERPOLATE_BKWD = 2, ///< flat backward IMPUTATION_INTERPOLATE_LINEAR = 3, ///< Linear interpolation IMPUTATION_INTERPOLATE_CSPLINE = 4, ///< cubic spline IMPUTATION_FFT = 5 ///< Fast Fourier transform }IMPUTATION_METHOD; typedef enum { X13TRANSFOR_NONE = 0, ///< don't process the input data X13TRANSFOR_AUTO = 1, ///< don't process the input data X13TRANSFOR_LOG = 2, ///< don't process the input data X13TRANSFOR_SQRT = 3, ///< don't process the input data X13TRANSFOR_INV = 4, ///< don't process the input data X13TRANSFOR_LOGIST = 5, ///< don't process the input data X13TRANSFOR_BOXCOX = 6 ///< don't process the input data }X13TRANSFORM_METHOD; typedef enum { X13PRIORADJUST_RATIO = 0, ///< X13PRIORADJUST_PERCENT = 1, ///< X13PRIORADJUST_DIFF = 2 ///< }X13PRIORADJUST_TYPE; typedef enum { X11_MODE_MULT = 0, ///< X11_MODE_ADD = 1, ///< X11_MODE_PSEUDOADD = 2, ///< X11_MODE_LOGADD = 3 ///< }X11_MODE_TYPE; typedef enum { X11_SEASONALMA_3x1 = 0, ///< X11_SEASONALMA_3x3 = 1, ///< X11_SEASONALMA_3x5 = 2, ///< X11_SEASONALMA_3x9 = 3, ///< X11_SEASONALMA_3x15 = 4, ///< X11_SEASONALMA_STABLE = 5, ///< X11_SEASONALMA_DEFAULT = 6, ///< 3x3 MA and 3x5 X11_SEASONALMA_MSR=7 ///< X-11-ARIMA88 }X11_SEASONALMA_TYPE; } // Functions API extern "C" { /// \name Initialization APIs /// @{ /*! * @brief Initializes the SFSDK Library * @details This function should be the first API called in the SDK; It initializes the SDK library dependencies: * 1. Logging system * 2. License system * 3. Database system * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * * \sa SFMacros.h, NDK_Shutdown() */ /*! @note 1. This is the first SDK API @code int nRet = NDK_FAILED; char szAppName[]="MyApp"; nRet = NDK_Init( szAppName, // we have a MyApp.conf file NULL, // use the license key in the license file (NumXL.lic) NULL, // use the activation code in the license file (NumXL.lic) NULL); // use the temp directory in current user's profile // (Windows 7) (c:\users\(username)\AppData\Local\MyApp) // (Windows XP) (c:\Local Settings\(username)\AppData\Local\MyApp) if( nRet >= NDK_SUCCES){ ... .... } @endcode */ int __stdcall NDK_Init( LPCTSTR szAppName, ///< [in] is the application name (user-defined), but must match the configuration base filename. LPCTSTR szKey, ///< [in, optional] is the NumXL license key. If missing (NULL), NDK_Init will attempt to locate the license key & activation code in the system. LPCTSTR szActCode, ///< [in, optional] is the license activation code. If missing (NULL), NDK_Init will attempt to locate the license key & activation code in the system. LPCTSTR szTmpPath ///< [in, optional] is the full path of the log file directory. If NULL, NDK reverts to the temporary directory in the current user's profile. ); /*! * @brief Shutdown and release resources used by the SFSDK Library * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful * \retval Others see \ref SFMacros.h * \sa SFMacros.h, NDK_Init() */ /*! @code int nRet = NDK_FAILED; ... nRet= NDK_Shutdown(); // This is the last SDK API called. // Check for error if( nRet < NDK_SUCCESS){ ... } @endcode */ int __stdcall NDK_Shutdown(void); // Examples /// \example sdk_init.cpp /// @} /// \name Descriptive Statistics /// @{ // Time series statistics // General statistics /*! * \brief Calculates the sample excess kurtosis. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. The time series is homogeneous or equally spaced. * \note 1. The data sample may include missing values (e.g. #N/A). * \note 2. The test hypothesis for the population excess kurtosis: \f$H_{o}: K=0\f$ \f$H_{1}: K\neq 0\f$, where: \f$H_{o}\f$ is the null hypothesis. \f$H_{1}\f$ is the alternate hypothesis. * \note 3. For the case in which the underlying population distribution is normal, the sample excess kurtosis also has a normal sampling distribution: \f$\hat K \sim N(0,\frac{24}{T})\f$, where: \f$\hat k\f$ is the sample excess kurtosis (i.e. 4th moment). \f$T\f$ is the number of non-missing values in the data sample. \f$N(.)\f$ is the normal (i.e. gaussian) probability distribution function. * \note 4. Using a given data sample, the sample excess kurtosis is calculated as: \f$\hat K (x)= \frac{\sum_{t=1}^T(x_t-\bar x)^4}{(T-1)\hat \sigma^4}-3\f$, where: \f$\hat K(x)\f$ is the sample excess kurtosis. \f$x_i\f$ is the i-th non-missing value in the data sample. \f$T\f$ is the number of non-missing values in the data sample. \f$\hat \sigma\f$ is the sample standard deviation. * \note 5. The underlying population distribution is assumed normal (gaussian).. * \note 6. This is a two-sides (i.e. two-tails) test, so the computed p-value should be compared with half of the significance level \f$\frac{\alpha}{2}\f$. * \sa NDK_XKURTTEST(), NDK_GED_XCF(), NDK_TDIST_XKURT() */ int __stdcall NDK_XKURT(double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated sample excess-kurtosis value. ); /*! * \brief Calculates the sample skewness. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF_SKEWTEST() */ int __stdcall NDK_SKEW( double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated sample skew value. ); /*! * \brief Calculates the sample average. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF_MEANTEST() */ int __stdcall NDK_AVERAGE(double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated average value. ); /*! * \brief Calculates the geometric mean of the sample * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_AVERAGE() */ int __stdcall NDK_GMEAN(double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated geometric average value. ); /*! * \brief Calculates the sample variance. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF_STDEVTEST() */ int __stdcall NDK_VARIANCE(double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated variance value. ); /*! * \brief Calculates the minimum value in a given sample. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_MAX(), NDK_QAUNTILE(), NDK_IQR() */ int __stdcall NDK_MIN( double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated minimum value. ); /*! * \brief Calculates the maximum value in a given sample. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_MIN(), NDK_QAUNTILE() */ int __stdcall NDK_MAX(double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated maximum value. ); /*! * \brief Returns the sample p-quantile of the non-missing observations (i.e. divides the sample data into equal parts determined by the percentage p). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series may include missing values (NaN), but they will not be included in the calculations. * \note 2. The quantile function for any distribution is defined between 0 and 1. Its function is the inverse of the cumulative distribution function (CDF). * \note 3. The quantile function returns the sample median when \f$p=0.5\f$. * \note 4. The quantile function returns the sample minimum when \f$p=0\f$. * \note 5. The quantile function returns the sample maximum when \f$p=1\f$. * \note 6. For any probability distribution, the following holds true for the probability \f$p\f$: -\f$P(X< q)\geq p\f$, where: -\f$q\f$ is the sample \f$p\f$-quantile. * \sa NDK_IQR(), NDK_MIN(), NDK_MAX() */ int __stdcall NDK_QUANTILE( double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double p, ///< [in] is a scalar value between 0 and 1 (exclusive). double* retVal ///< [out] is the calculated p-th quantile value. ); /*! * \brief Returns the interquartile range (IQR), also called the midspread or middle fifty. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The input time series data may include missing values (NaN), but they will not be included in the calculations. * \note 2. The interquartile range is defined as follows: -\f$\textup{IQR}=Q_3-Q_1\f$, where: -\f$Q_3\f$ is the third quartile. -\f$Q_1\f$ is the first quartile. * \note 3. Interquartile range (IQR) is a robust statistic because it has a break down point of 25%. It is often preferred to the total range. * \sa NDK_QUANTILE(), NDK_MIN(), NDK_MAX() */ int __stdcall NDK_IQR(double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated IQR value. ); /*! * \brief Returns the sorted sample data * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_SORT_ASC( double* X, ///< [inout] is the input data sample (a one dimensional array). size_t N ///< [in] is the number of observations in X. ); /*! * \brief Calculates the Hurst exponent (a measure of persistence or long memory) for time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. */ /*! * \htmlonly * <h3>References</h3> * <ul> * <li>[1] A.A.Anis, E.H.Lloyd (1976) The expected value of the adjusted rescaled Hurst range of independent normal summands, Biometrica 63, 283-298.</li> * <li>[2] H.E.Hurst (1951) Long-term storage capacity of reservoirs, Transactions of the American Society of Civil Engineers 116, 770-808.</li> * <li>[3] E.E.Peters (1994) Fractal Market Analysis, Wiley.</li> * <li>[4] R.Weron (2002) Estimating long range dependence: finite sample properties and confidence intervals, Physica A 312, 285-299.</li> * </ul> * \endhtmlonly */ /*! * \note 1. The input data series must have at least 9 non-missing values. Otherwise, Hurst function returns #NDK_FAILED. * \note 2. The input data series may include missing values (NaN), but they will not be included in the calculations. * \note 3. The Hurst exponent, \f$h\f$, is defined in terms of the rescaled range as follows: \f$E \left [ \frac{R(n)}{S(n)} \right ]=Cn^H \textup{ as } n \to \infty \f$ * \note 4. Where: -\f$\left [ \frac{R(n)}{S(n)} \right ]\f$ is the Rescaled Range. -\f$E \left [x \right ]\f$ is the expected value. -\f$n\f$ is the time of the last observation (e.g. it corresponds to \f$X_n\f$ in the input time series data.) -\f$h\f$ is a constant. of * \note 5. The Hurst exponent is a measure autocorrelation (persistence and long memory): -A value of \f$0<H<0.5\f$ indicates a time series with negative autocorrelation (e.g. a decrease between values will probably be followed by another decrease). -A value of \f$0.5<H<1\f$ indicates a time series with positive autocorrelation (e.g. an increase between values will probably be followed by another increase). -A value of \f$H=0.5\f$ indicates a "true random walk," where it is equally likely that a decrease or an increase will follow from any particular value (e.g. the time series has no memory of previous values). * \note 6. The Hurst exponent's namesake, Harold Edwin Hurst (1880-1978), was a British hydrologist who researched reservoir capacity along the Nile river. * \note 7. The rescaled range is calculated for a time series, \f$X=X_1,X_2,\dots, X_n\f$, as follows: 1. Calculate the mean:<BR> \f$m=\dfrac{1}{n} \sum_{i=1}^{n} X_i\f$ 2. Create a mean adjusted series:<BR> \f$Y_t=X_{t}-m \textup{ for } t=1,2, \dots ,n\f$ 3. Calculate the cumulative deviate series Z:<BR> \f$Z_t= \sum_{i=1}^{t} Y_{i} \textup{ for } t=1,2, \dots ,n\f$ 4. Create a range series R:<BR> \f$R_t = max\left (Z_1, Z_2, \dots, Z_t \right )- min\left (Z_1, Z_2, \dots, Z_t \right ) \textup{ for } t=1,2, \dots, n\f$ 5. Create a standard deviation series R:<BR> \f$S_{t}= \sqrt{\dfrac{1}{t} \sum_{i=1}^{t}\left ( X_{i} - u \right )^{2}} \textup{ for } t=1,2, \dots ,n\f$ Where:<BR> \f$h\f$ is the mean for the time series values \f$X_1,X_2, \dots, X_t\f$ * \note 8. Calculate the rescaled range series (R/S):<BR> \f$\left ( R/S \right )_{t} = \frac{R_{t}}{S_{t}} \textup{ for } t=1,2, \dots, n\f$ * \sa NDK_GINI() */ int __stdcall NDK_HURST_EXPONENT( double* X, ///< [in] is the input data sample (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double alpha, ///< [in] is the statistical significance level (1%, 5%, 10%). If missing, a default of 5% is assumed. WORD retType, ///< [in] is a number that determines the type of return value: /// 1 = Empirical Hurst exponent (R/S method) /// 2 = Anis-Lloyd/Peters corrected Hurst exponent /// 3 = Theoretical Hurst exponent /// 4 = Upper limit of the confidence interval /// 5 = Lower limit of the confidence interval double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the sample Gini coefficient, a measure of statistical dispersion. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. A low Gini coefficient indicates a more equal distribution, with 0 corresponding to complete equality. Higher Gini coefficients indicate more unequal distributions, with 1 corresponding to complete inequality. * \note 2. The input data series may include missing values (NaN), but they will not be included in the calculations. * \note 3. The values in the input data series must be non-negative. * \note 4. The Gini coefficient is computed as follows: \f$G(S)=1-\frac{2}{n-1}\left ( n-\frac{\sum_{i=1}^{n}iy_i}{\sum_{i=1}^{n}y_i} \right )\f$ * \note 5. Where: - \f$h\f$ is the input data series (\f$h\f$) arranged in descending order, so that \f$y_i\leq y_{i+1}\f$. - \f$n\f$ is the number of non-missing values in the input time series data sample. * \note 6. The Gini coefficient value can range from 0 to 1 and is half the NDK_RMD(). * \note 7. \f$G(S)\f$ is a consistent estimator of the population Gini coefficient, but is generally unbiased (except when the population mean is known). * \note 8. Developed by the Italian statistician Corrado Gini in 1912, the Gini coefficient is commonly used as a measure of comparative income or wealth. Where zero (0) corresponds to complete equality and one (1) to complete inequality. * \sa NDK_HURST_EXPONENT() */ int __stdcall NDK_GINI(double* x, ///< [in] is the input data sample (must be non-negative) (a one dimensional array of values). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Calculates the cross-correlation function between two time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The two time series must be identical in size. * \note 3. The Pearson correlation, \f$r_{xy}\f$, is defined as follows: -\f$r_{xy}= \frac{\sum_{i=1}^N(x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum_{i=1}^N(x_i-\bar{x})^2\times\sum_{i=1}^N(y_i-\bar{y})^2}}\f$, where: -\f$\bar{x}\f$ is the sample average of time series X. -\f$\bar{y}\f$ is the sample average of time series Y. -\f$x_i \in X\f$ is a value from the first input time series data. -\f$y_i \in Y\f$ is a value from the second input time series data. -\f$N\f$ is the number of pairs \f$\left ( x_i,y_i \right )\f$ that do not contain a missing observation. * \sa NDK_ACF(), NDK_XCF() */ int __stdcall NDK_XCF(double* X, ///< [in] is the first univariate time series data (a one dimensional array). double* Y, ///< [in] is the second univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. 0=no lag, 1=1st lag, etc.) to use with the second time series input (X). If missing, a default lag order of zero (i.e. no-lag) is assumed. WORD method, ///< [in] is the algorithm to use for calculating the correlation (see #CORRELATION_METHOD) WORD retType, ///< [in] is a switch to select the return output (1 = correlation value(default), 2 = std error). double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the sample root mean square (RMS). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The input time series data may include missing values (NaN), but they will not be included in the calculations. * \note 2. The root mean square (RMS) is defined as follows for a set of \f$n\f$ values \f${x_1,x_2,...,x_n}\f$: - \f$\textrm{RMS}=\sqrt{\frac{x_1^2+x_2^2+\cdots +x_N^2}{N}} =\sqrt{\frac{\sum_{i=1}^N {x_i^2}}{N}}\f$ * \note 3. Where: - \f$x_i\f$ is the value of the i-th non-missing observation. - \f$N\f$ is the number of non-missing observations in the input sample data. * \note 4. The root mean square (RMS) is a statistical measure of the magnitude of a varying quantity. * \note 5. The root mean square (RMS) has an interesting relationship to the mean (\f$\bar{x}\f$) and the population standard deviation (\f$\sigma\f$), such that: - \f$\textrm{RMS}^2=\bar{x}^2+\sigma^2\f$ * \sa NDK_MD(), NDK_RMD() */ int __stdcall NDK_RMS(double* X, ///< [in] is the input data sample (a one/two dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the mean difference of the input data series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. \note 1. The time series may include missing values (NaN), but they will not be included in the calculations. * \note 2. The sample mean difference (MD) is computed as follows: - \f$\Delta = \textup{MD} = \frac{\sum_{i=1}^n \sum_{j=1}^n \| x_i - x_j \|}{n \times \left ( n-1 \right )}\f$ * \note 3. Where: - \f$x_i\f$ is the value of the i-th non-missing observation. - \f$n\f$ is the number of non-missing observations in the sample. * \note 4. The mean difference is the product of the sample mean and the relative mean difference (RMD) and so can also be expressed in terms of the NDK_GINI: - \f$\textup{MD}= 2 \times G \times \bar{x}\f$ * \note 5. Where: - \f$\bar{x}\f$ is the arithmetic sample mean. - \f$G\f$ is the NDK_GINI. * \note 6. Because of its ties to the Gini coefficient, the mean difference is also called the "Gini mean difference." It is also known as the "absolute mean difference." * \note 7. The sample mean difference is not dependent on a specific measure of central tendency like the standard deviation. * \note 8. The mean difference of a sample is an unbiased and consistent estimator of the population mean difference. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_MD(double* pData, ///< [in] is the input data series (one/two dimensional array). size_t nSize, ///< [in] is the number of observations in pData. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the computed value. ); /*! * \brief Returns the sample relative mean difference. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series may include missing values (NaN), but they will not be included in the calculations. * \note 2. The relative mean difference is defined in terms of the NDK_MD as follows: - \f$\textup{RMD}= \frac{\textup{MD}}{\bar{x}}\f$ * \note 3: Where: -\f$\bar{x}\f$ is the sample mean (average) of the time series. -\f$\textup{MD}\f$ is the mean difference of the time series. * \note 4: The RMD is also equal to twice the NDK_GINI. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_RMD(double* X, ///< [in] is the input data sample (a one/two dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the sample median of absolute deviation (MAD). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The input data series may include missing values (NaN), but they will not be included in the calculations. * \note 2. The median of absolute deviation (MAD) is defined as follows: -\f$\operatorname{MAD} = \operatorname{median}_{i}\left(\ \left| X_{i} - \operatorname{median}_{j} (X_{j}) \right|\ \right)\f$ * \note 3. In short, starting with the deviations from the data's median, the MAD is the median of their absolute values. * \note 4. The median of absolute deviation (MAD) is a measure of statistical dispersion. * \note 5. MAD is a more robust estimator of scale than the sample variance or standard deviation. * \note 6. MAD is especially useful with distributions that have neither mean nor variance (e.g. the Cauchy distribution.) * \note 7. MAD is a robust statistic because it is less sensitive to outliers in a data series than standard deviation. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_MAD(double* X, ///< [in] is the input data sample (a one/two dimensional array). size_t N, ///< [in] is the number of observations in X. WORD reserved, ///< [in] This parameter is reserved and must be 1. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the long-run variance using a Bartlett kernel with window size k. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The input time series data may include missing values (NaN), but they will not be included in the calculations. * \note 2. The long-run variance is computed as follows: -\f$\sigma^2=\frac{1}{T}\sum_{t=k}^{T-k}\sum_{i=-k}^k w_i(x_t-\bar{x})(x_{t-i}-\bar{x})\f$ * \note 3. Where: -\f$x_{t} \in X\f$ is a value from the input time series data. -\f$\bar{x}\f$ is the mean of the input time series data. -The weight \f$w_i\f$ in Bartlett kernel is defined as follows: -\f$w_i= 1- \frac{\left | i \right |}{k+1}\f$ -\f$k\f$ is the input window size for the Bartlett kernel. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_LRVAR(double* X, ///< [in] is the input data sample (a one/two dimensional array). size_t N, ///< [in] is the number of observations in X. size_t w, ///< [in] is the input Bartlett kernel window size. If omitted, the default value is the cubic root of the sample data size. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Calculates the sum of absolute errors (SAE) between the forecast and the eventual outcomes. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The two time series must be identical in size. * \note 3. A missing value (say \f$x_k\f$ or \f$\hat x_k\f$) in either time series will exclude the data point \f$(x_k,\hat x_k)\f$ from the SSE. * \note 4. The sum of absolute errors (SAE) or deviations (SAD), is defined as follows: -\f$\mathrm{SAE}=\mathrm{SAD}=\sum_{i=1}^N \left | x_i-\hat x_i \right |\f$, where: -\f$\{x_i\}\f$ is the actual observations time series. -\f$\{\hat x_i\}\f$ is the estimated or forecasted time series. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_SAD(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Calculates the mean absolute error function for the forecast and the eventual outcomes. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The mean absolute error is a common measure of forecast error in time series analysis. * \note 2. The time series is homogeneous or equally spaced. * \note 3. The two time series must be identical in size. * \note 4. The mean absolute error is given by: -\f$\mathrm{MAE}=\frac{\mathrm{SAE}}{N}=\frac{\sum_{i=1}^N \left | x_i - \hat x_i \right |}{N}\f$, where: -\f$\{x_i\}\f$ is the actual observations time series. -\f$\{\hat x_i\}\f$ is the estimated or forecasted time series. -\f$\mathrm{SAE}\f$ is the sum of the absolute errors (or deviations). -\f$N\f$ is the number of non-missing data points. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_MAE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated value of this function. ); int __stdcall NDK_MASE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t M, ///< [in] is the seasonal period (for non-seasonal time series, set M=1). double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Calculates the mean absolute percentage error (deviation) function for the forecast and the eventual outcomes. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. MAPE is also referred to as MAPD. * \note 2. The time series is homogeneous or equally spaced. * \note 3. For a plain MAPE calculation, in the event that an observation value (i.e. \f$x_k\f$) is equal to zero, the MAPE function skips that data point. * \note 4. The mean absolute percentage error (MAPE), also known as mean absolute percentage deviation (MAPD), measures the accuracy of a method for constructing fitted time series values in statistics. * \note 5. The two time series must be identical in size. * \note 6. The mean absolute percentage error (MAPE) is defined as follows: -\f$\mathrm{MAPE}=\frac{100}{N}\times \sum_{i=1}^N \left | \frac{x_i - \hat x_i}{x_i} \right |\f$, where: -\f$\{x_i\}\f$ is the actual observations time series. -\f$\{\hat x_i\}\f$ is the estimated or forecasted time series. -\f$N\f$ is the number of non-missing data points. * \note 7. When calculating the average MAPE for a number of time series, you may encounter a problem: a few of the series that have a very high MAPE might distort a comparison between the average MAPE of a time series fitted with one method compared to the average MAPE when using another method. * \note 8. In order to avoid this problem, other measures have been defined, for example the SMAPE (symmetrical MAPE), weighted absolute percentage error (WAPE), real aggregated percentage error and relative measure of accuracy (ROMA). * \note 9. The symmetrical mean absolute percentage error (SMAPE) is defined as follows: -\f$\mathrm{SMAPE}=\frac{200}{N}\times \sum_{i=1}^N \left | \frac{x_i - \hat x_i}{x_i+\hat x_i} \right |\f$ * \note 10. The SMAPE is easier to work with than MAPE, as it has a lower bound of 0% and an upper bound of 200%. * \note 11. The SMAPE does not treat over-forecast and under-forecast equally. * \note 12. For a SMAPE calculation, in the event the sum of the observation and forecast values (i.e. \f$x_k + \hat x_k\f$) equals zero, the MAPE function skips that data point. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_MAPE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. BOOL SMAPE, ///< [in] is a switch to select the return output (FALSE=MAPE (default), TRUE=Symmetric MAPE (SMAPI)). double* retVal ///< [out] is the calculated value of this function. ); int __stdcall NDK_MdAPE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. BOOL SMAPE, ///< [in] is a switch to select the scale to divide on: FALSE = Actual obs., TRUE= Average (Actual, Forecast) double* retVal ///< [out] is the calculated value of this function. ); int __stdcall NDK_MAAPE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Calculates the root mean squared error (aka root mean squared deviation (RMSD)) function. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The RMSE is also known as root mean squared deviation (RMSD). * \note 2. Please see NDK_RMSD for definition and notes. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_RMSE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [In] is the number of observations in X. WORD retType, ///< [In] is a switch to select the return output (1=RMSE (default), 2=NRMSE, 3=CV(RMSE)). double* retVal ///< [out] is the calculated value of this function. ); int __stdcall NDK_GRMSE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecast time series data (a one dimensional array). size_t N, ///< [In] is the number of observations in X. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Calculates the sum of the squared errors of the prediction function. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The two time series must be identical in size. * \note 3. A missing value (e.g. \f$x_k\f$ or \f$\hat x_k\f$) in either time series will exclude the data point \f$(x_k,\hat x_k)\f$ from the SSE. * \note 4. The sum of the squared errors, \f$\mathrm{SSE}\f$, is defined as follows: \f$\mathrm{SSE}=\sum_{i=1}^N \left(x_i-\hat x_i \right )^2\f$, where: -\f$\{x_i\}\f$ is the actual observations time series. -\f$\{\hat x_i\}\f$ is the estimated or forecasted time series. * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_SSE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecasted time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated sum of squared errors. ); /*! * \brief Calculates the mean squared errors of the prediction function. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The two data sets must be identical in size. * \note 2. A missing value (e.g. \f$x_k\f$ or \f$\hat x_k\f$) in either time series will exclude the data point \f$(x_k,\hat x_k)\f$ from the MSE. * \sa NDK_SSE() */ int __stdcall NDK_MSE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecasted time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated mean of squared errors. ); int __stdcall NDK_GMSE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecasted time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retVal ///< [out] is the calculated mean of squared errors. ); int __stdcall NDK_MRAE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecasted time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t period, ///< [in] is the seasonal period (for non-seasonal time series, set M=1). double* retVal ///< [out] is the calculated mean of relative absolute error ); int __stdcall NDK_MdRAE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecasted time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t period, ///< [in] is the seasonal period (for non-seasonal time series, set M=1). double* retVal ///< [out] is the calculated median of relative absolute error ); int __stdcall NDK_GMRAE(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecasted time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t period, ///< [in] is the seasonal period (for non-seasonal time series, set M=1). double* retVal ///< [out] is the calculated geometric mean of relative absolute error ); int __stdcall NDK_PB(double* X, ///< [in] is the original (eventual outcomes) time series sample data (a one dimensional array). double* Y, ///< [in] is the forecasted time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t period, ///< [in] is the seasonal period (for non-seasonal time series, set M=1). WORD basis, ///< [in] is the switch to specify the metric used for comparison: 0=absolute error, 1=MAE, 2=MSE double* retVal ///< [out] is the calculated geometric mean of relative absolute error ); /*! * \brief Calculates the sample autocorrelation function (ACF) of a stationary time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (NaN) at either end. * \note 3. The lag order (k) must be less than the time series size or else an error value (#NDK_FAILED) is returned. * \note 4. The ACF values are bound between -1 and 1, inclusive. * \note 5. The sample autocorrelation is computed as: -\f$\hat{\rho}(h)=\frac{\sum_{k=h}^T{(y_{k}-\bar y)(y_{k-h}-\bar y)}}{\sum_{k=h}^T(y_{k}-\bar y)^2}\f$, where: -\f$y_{t}\f$ is the value of the time series at time t. -\f$h\f$ is the lag order. -\f$T\f$ is the number of non-missing values in the time series data. -\f$\bar y\f$ is the sample average/mean of the time series. * \note 6. Special cases: -By definition, \f$\hat{\rho}(0) \equiv 1.0\f$ * \sa NDK_ACF_ERROR(), NDK_XCF() */ int __stdcall NDK_ACF(double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). WORD method, ///< [in] is the method selecor (0 = sample autocorrelation, 1= periodogram-based estimate, 2= cross-correlation based estimate). double* retVal ///< [out] is the calculated sample autocorrelation value. ); /*! * \brief Calculates the standard error in the sample autocorrelation function. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF(), NDK_ACFCI() */ int __stdcall NDK_ACF_ERROR(double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). WORD method, ///< [in] is the method selecor (0 = sample autocorrelation, 1= periodogram-based estimate, 2= cross-correlation based estimate). double* retVal ///< [out] is the standard error in the sample autocorrelation value. ); /*! * \brief Calculates the confidence interval limits (upper/lower) for the autocorrelation function. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (NaN) at either end. * \note 3. The lag order (k) must be less than the time series size, or else an error value (#NDK_FAILED) is returned. * \note 4. The ACFCI function calculates the confidence limits as: -\f$\hat\rho_k - Z_{\alpha/2}\times \sigma_{\rho_k} \leq \rho_k \leq \hat\rho_k+ Z_{\alpha/2}\times \sigma_{\rho_k}\f$, where: -\f$\rho_k\f$ is the population autocorrelation function. -\f$\sigma_{\rho_k}\f$ is the standard error of the sample autocorrelation. -\f$\hat{\rho_{k}}\f$ is the sample autocorrelation function for lag k. -\f$Z\sim N(0,1)\f$ -\f$P(\left|Z\right|\geq Z_{\alpha/2}) = \alpha\f$ * \note 5. For the case in which the underlying population distribution is normal, the sample autocorrelation also has a normal distribution: -\f$\hat \rho_k \sim N(\rho_k,\sigma_{\rho_k}^2)\f$, where: -\f$\hat \rho_k\f$ is the sample autocorrelation for lag k. -\f$\rho_k\f$ is the population autocorrelation for lag k. -\f$\sigma_{\rho_k}\f$ is the standard error of the sample autocorrelation for lag k. * \note 6. Bartlett proved that the variance of the sample autocorrelation of a stationary normal stochastic process (i.e. independent, identically normal distributed errors) can be formulated as: -\f$\sigma_{\rho_k}^2 = \frac{\sum_{j=-\infty}^{\infty}\rho_j^2+\rho_{j+k}\rho_{j-k}-4\rho_j\rho_k\rho_{i-k}+2\rho_j^2\rho_k^2}{T}\f$ * \note 7. Furthermore, the variance of the sample autocorrelation is reformulated: -\f$\sigma_{\rho_k}^2 = \frac{1+\sum_{j=1}^{k-1}\hat\rho_j^2}{T}\f$, where: -\f$\sigma_{\rho_k}\f$ is the standard error of the sample autocorrelation for lag k. -\f$T\f$ is the sample data size. -\f$\hat\rho_j\f$ is the sample autocorrelation function for lag j. -\f$k\f$ is the lag order. * \sa NDK_ACF(), NDK_ACF_ERROR() */ int __stdcall NDK_ACFCI(double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). WORD method, ///< [in] is the method selecor (0 = sample autocorrelation, 1= periodogram-based estimate, 2= cross-correlation based estimate). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* ULCI, ///< [out] is the upper limit value of the confidence interval double* LLCI ///< [out] is the lower limit value of the confidence interval. ); /*! * \brief Calculates the sample partial autocorrelation function (PACF). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF(), NDK_PACF_ERROR(),NDK_PACFCI() */ int __stdcall NDK_PACF( double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). double* retVal ///< [out] is the calculated sample partial-autocorrelation value. ); /*! * \brief Calculates the standard error of the sample partial autocorrelation function (PACF). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_PACF(), NDK_PACFCI() */ int __stdcall NDK_PACF_ERROR( double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). double* retVal ///< [out] is the standard error in the sample partial-autocorrelation value. ); /*! * \brief Calculates the confidence interval limits (upper/lower) for the partial-autocorrelation function. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF(), NDK_ACF_ERROR() */ int __stdcall NDK_PACFCI( double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* ULCI, ///< [out] is the upper limit value of the confidence interval. double* LLCI ///< [out] is the lower limit value of the confidence interval. ); /*! * \brief Calculates the periodgram value for different lags. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ACF(), NDK_PACF() */ int __stdcall NDK_PERIODOGRAM(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in pData. PERIODOGRAM_OPTION_TYPE option, ///< [in] is the pre-processing option to the time series (e.g. detrend, difference, auto, etc.) double alpha, ///< [in] is the statistical significance level (used in the auto-process procedure). If missing, a default of 5% is assumed. double* retVal, ///< [out] is the periodogram values for this series size_t nOutSize ///< [in] is the size of the output buffer (i.e. retVal) ); /*! * \brief Calculates the estimated value of the exponential-weighted volatility (EWV). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (NaN) at either end. * \note 3. The EWMA function assumes that the time series has an average equal to zero. * \note 4. The exponential-weighted moving average is calculated as: -\f$\sigma_t^2=\lambda \sigma_{t-1}^2+(1-\lambda)x_{t-1}^2\f$, where: -\f$x_t\f$ is the value of the time series value at time t. -\f$\lambda\f$ is the smoothing parameter (i.e. a non-negative constant between 0 and 1). * \note 5. The size of the EWMA time series is equal to the input time series, but with the first observation (or last, if the original series is reversed) set to missing (NaN). * \sa NDK_WMA(), NDK_EWXCF() */ int __stdcall NDK_EWMA(double *X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double lambda, ///< [in] is the smoothing parameter used for the exponential-weighting scheme. If missing, a default value of 0.94 is assumed size_t step, ///< [in] is the forecast time/horizon (expressed in terms of steps beyond the end of the time series X). If missing, a default value of 0 is assumed. double* retVal ///< [out] is the estimated value of the exponential-weighted volatility. ); /*! * \brief Computes the correlation factor using the exponential-weighted correlation function. * \details NDK_EWXCF computes the correlation estimate using the exponential-weighted covariance (EWCOV) and volatility (EWMA/EWV) method for each time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The two time series must have identical size and time order. * \note 3. The correlation is defined as: -\f$\rho^{(xy)}_t=\frac{\sigma_t^{(xy)}}{{_x\sigma_t}\times{_y\sigma_t}}\f$ -\f$\sigma_t^{(xy)} = \lambda\sigma_{t-1}^{(xy)}+(1-\lambda)x_{t-1}y_{t-1}\f$ -\f$_x\sigma_t^2=\lambda\times{_x\sigma_{t-1}^2}+(1-\lambda)x_{t-1}^2\f$ -\f$_y\sigma_t^2=\lambda\times{_y\sigma_{t-1}^2}+(1-\lambda)y_{t-1}^2\f$, where: -\f$\rho^{(xy)}_t\f$ is the sample correlation between X and Y at time t. -\f$\sigma_t^{(xy)}\f$ is the sample exponential-weighted covariance between X and Y at time t. -\f$_x\sigma_t\f$ is the sample exponential-weighted volatility for the time series X at time t. -\f$_y\sigma_t\f$ is the sample exponential-weighted volatility for the time series Y at time t. -\f$\lambda\f$ is the smoothing factor used in the exponential-weighted volatility and covariance calculations. * \sa SFMacros.h, NDK_WMA(), NDK_EWMA() */ int __stdcall NDK_EWXCF( double *X, ///< [in] is the first univariate time series data (a one dimensional array). double *Y, ///< [in] is the second univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X (or Y). double lambda, ///< [in] is the smoothing parameter used for the exponential-weighting scheme. If missing, a default value of 0.94 is assumed. size_t step, ///< [in] is the forecast time/horizon (expressed in terms of steps beyond the end of the time series X). If missing, a default value of 0 is assumed. double* retVal ///< [out] is the estimated value of the correlation factor. ); ///@} /// \name Statistical Distribution /// Statistical distribution /// @{ /*! * \brief Calculates the excess kurtosis of the generalized error distribution (GED). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_TDIST_XKURT(), NDK_XKURTTEST() */ int __stdcall NDK_GED_XKURT(double df, ///< [in] is the shape parameter (or degrees of freedom) of the distribution (V > 1). double* retVal ///< [out] is the computed value ); /*! * \brief Calculates the excess kurtosis of the student's t-distribution. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_TDIST_XKURT(), NDK_XKURTTEST() */ int __stdcall NDK_TDIST_XKURT(double df, ///< [in] is the degrees of freedom of the student's t-distribution (v > 4). double* retVal ///< [out] is the computed value. ); /*! * \brief Calculates the empirical distribution function (or empirical cdf) of the sample data. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_KERNEL_DENSITY_ESTIMATE(), NDK_HISTOGRAM() */ int __stdcall NDK_EDF(double* pData, ///< [in] is the input data series (one/two dimensional array). size_t nSize, ///< [in] is the number of elements in pData. double targetVal, ///< [in] is the target value to compute the underlying cdf for. WORD retType, ///< [in] is a switch to select the return output (1=CDF (default), 2=Inverse CDF). double* retVal ///< [out] is the computed value. ); /*! * \brief Returns the number of histogram bins using a given method. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_HIST_BIN_LIMIT(), NDK_HISTOGRAM() */ int __stdcall NDK_HIST_BINS(double* pData, ///< [in] is the input data series (one/two dimensional array). size_t nSize, ///< [in] is the number of elements in pData. WORD argMethod, ///< [in] is a switch to select the calculation method (1=Sturges's formula, 2=Square-root, 3=Scott's Choice, 4=Freedman-Diaconis choice, 5=Optimal (default)). size_t* retVal ///< [out] is the computed value. ); /*! * \brief Returns the upper/lower limit or center value of the k-th histogram bin. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_HIST_BINS(), NDK_HISTOGRAM() */ int __stdcall NDK_HIST_BIN_LIMIT( double* pData, ///< [in] is the input data series (one/two dimensional array). size_t nSize, ///< [in] is the number of elements in pData. size_t nBins, ///< [in] is the input number of bins for the histogram. size_t index, ///< [in] is the bin index or order; e.g. 0=1st bin (default),1=2nd bin,..., N-1. WORD argRetTYpe, ///< [in] is a switch to select the return output (0=lower limit (default), 1=upper limit of the bin, 2=center of the bin). double* retVal ///< [out] is the computed value. ); /*! * \brief Calculates the histogram or cumulative histogram function for a given bin. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_HIST_BINS(), NDK_HISTOGRAM() */ int __stdcall NDK_HISTOGRAM( double* pData, ///< [in] is the input data series (one/two dimensional array). size_t nSize, ///< [in] is the number of elements in pData. size_t nBins, ///< [in] is the input number of bins for the histogram. size_t index, ///< [in] is the bin index or order; e.g. 0=1st bin (default),1=2nd bin,..., N. WORD argRetTYpe, ///< [in] is a switch to select the return output: /// 0. histogram /// 1. cumulative histogram (default)). double* retVal ///< [out] is the computed value. ); /*! * \brief Returns the upper/lower limit or center value of the k-th histogram bin. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_HIST_BINS(), NDK_HISTOGRAM() */ int __stdcall NDK_KERNEL_DENSITY_ESTIMATE(double* pData, ///< [in] is the input data series (one/two dimensional array). size_t nSize, ///< [in] is the number of elements in pData. double targetVal, ///< [in] is the target value to compute the underlying cdf for. double bandwidth, ///< [in] is the smoothing parameter (bandwidth) of the kernel density estimator. If missing, the KDE function calculates an optimal value. WORD argKernelFunc, ///< [in] is a switch to select the kernel function: /// 1=Gaussian (default), /// 2=Uniform /// 3=Triangular /// 4=Biweight (Quatric) /// 5=Triweight /// 6=Epanechnikov double* retVal ///< [out] is the computed value. ); /*! * \brief Returns a sequence of random numbers drawn from Normal distribution * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_GAUSS_FORECI() */ int __stdcall NDK_GAUSS_RNG( double mean, ///< [in] is the mean of the Gaussian distribution. double sigma, ///< [in] is the standard deviation of the Gaussian distribution. UINT seed, ///< [in] is a number to initialize the psuedorandom number generator. double* retArray, ///< [out] are the generated random values. UINT nArraySize ///< [in] is the number of elements in retArray ); /*! * \brief Returns the upper & lower limit of the confidence interval for the Gaussian distribution. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_TSTUDENT_FORECI(), NDK_GED_FORECI() */ int __stdcall NDK_GAUSS_FORECI( double mean, ///< [in] is the mean of the Gaussian distribution. double sigma, ///< [in] is the standard deviation of the Gaussian distribution. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. BOOL upper, ///< [in] is a switch to select the limit (upper/lower). double* retVal ///< [out] is the computed value. ); /*! * \brief Returns the upper & lower limit of the confidence interval for the student\'s t-distribution * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_GAUSS_FORECI(), NDK_GED_FORECI() */ int __stdcall NDK_TSTUDENT_FORECI(double mean, ///< [in] is the mean of the student's t-distribution. double sigma, ///< [in] is the standard deviation of the student's t-distribution. double df, ///< [in] is the degrees of freedom (nu) of the student's t-distribution. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. BOOL upper, ///< [in] is a switch to select the limit (upper/lower). double* retVal ///< [out] is the computed value. ); /*! * \brief Returns the upper & lower limit of the confidence interval for the Generalized Error Distribution (GED) distribution * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_TSTUDENT_FORECI(), NDK_GAUSS_FORECI() */ int __stdcall NDK_GED_FORECI( double mean, ///< [in] is the mean of the GED distribution. double sigma, ///< [in] is the standard deviation of the GED distribution. double df, ///< [in] is the degrees of freedom (nu) of the GED distribution. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. BOOL upper, ///< [in] is a switch to select the limit (upper/lower). double* retVal ///< [out] is the computed value. ); ///@} /// \name Statistical Testing /// Statistical/hypothesis testing is a common method of drawing inferences about a population based on statistical evidence from a sample. /// @{ /*! * \brief Calculates the p-value of the statistical test for the population autocorrelation function. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, NDK_WMA(), NDK_EWMA() */ int __stdcall NDK_ACFTEST(double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. int K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). WORD method, ///< [in] is the type of test: parametric or non-parametric. double target, ///< [in] is the assumed autocorrelation function value. If missing, the default of zero is assumed. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Returns the p-value of the normality test (i.e. whether a data set is well-modeled by a normal distribution). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_MEANTEST(), NDK_SKEWTEST(), #NORMALTEST_METHOD, #TEST_RETURN */ int __stdcall NDK_NORMALTEST( double* X, ///< [in] is the sample data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=Jarque-Bera, 2=Shapiro-Wilk, 3=Chi-Square (Doornik and Hansen)). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Computes the p-value of the statistical portmanteau test (i.e. whether any of a group of autocorrelations of a time series are different from zero). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_NORMALTEST(), NDK_ARCHTEST() */ int __stdcall NDK_WNTEST( double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=Ljung-Box). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Calculates the p-value of the ARCH effect test (i.e. the white-noise test for the squared time series). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_NORMALTEST(), NDK_ARCHTEST(), */ int __stdcall NDK_ARCHTEST( double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=Ljung-Box). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Calculates the p-value of the statistical test for the population mean. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_SKEWTEST(), NDK_STDEVTEST() */ int __stdcall NDK_MEANTEST( double* X, ///< [in] is the sample data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double target, ///< [in] is the assumed mean value. If missing, a default of zero is assumed. double alpha, ///< [in] is the statistical significance level. If missing, the default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=parametric). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Calculates the p-value of the statistical test for the population standard deviation. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_MEANTEST(), NDK_SKEWTEST(), NDK_XKURTTEST() */ int __stdcall NDK_STDEVTEST(double* X, ///< [in] is the sample data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double target, ///< [in] is the assumed standard deviation value. If missing, a default of one is assumed double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=parametric). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Calculates the p-value of the statistical test for the population skew (i.e. 3rd moment). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_NORMALTEST(), NDK_MEANTEST(), NDK_STDEVTEST(), NDK_XKURTTEST() */ int __stdcall NDK_SKEWTEST( double* X, ///< [in] is the sample data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double alpha, ///< [in] is the statistical significance level. If missing, the default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=parametric). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Calculates the p-value of the statistical test for the population excess kurtosis (4th moment). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa SFMacros.h, NDK_NORMALTEST(), NDK_MEANTEST(), NDK_STDEVTEST(), NDK_SKEWTEST() */ int __stdcall NDK_XKURTTEST(double* X, ///< [in] is the sample data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=parametric). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Calculates the test stats, p-value or critical value of the correlation test. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_NORMALTEST(), NDK_MEANTEST(), NDK_STDEVTEST(), NDK_SKEWTEST() */ int __stdcall NDK_XCFTEST(double* X, ///< [in] is the first univariate time series data (a one dimensional array). double *Y, ///< [in] is the second univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X (or Y). int K, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). double target, ///< [in] is the assumed correlation value. If missing, a default of zero is assumed. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD method, ///< [in] is the desired correlation coefficient (1=Pearson (default), 2=Spearman, 3=Kendall). If missing, a Pearson coefficient is assumed. WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [out] is the calculated test statistics. ); /*! * \brief Returns the p-value of the Augmented Dickey-Fuller (ADF) test, which tests for a unit root in the time series sample. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_NORMALTEST(), NDK_MEANTEST(), NDK_STDEVTEST(), NDK_SKEWTEST() */ int __stdcall NDK_ADFTEST(double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD K, ///< [in] is the lag length of the autoregressive process. If missing, an initial value equal to the cubic root of the input data size is used. ADFTEST_OPTION options, ///< [in] is the model description flag for the Dickey-Fuller test variant (1=no constant, 2=contant-only, 3=trend only, 4=constant and trend, 5=const, trend and trend squared). BOOL testDown, ///< [in] is the mode of testing. If set to TRUE (default), ADFTest performs a series of tests. The test starts with the input length lag, but the actual length lag order used is obtained by testing down. double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. WORD method, ///< [in] is the statistical test to perform (1=ADF). WORD retType, ///< [in] is a switch to select the return output: (\ref #TEST_RETURN) /// 1. P-value /// 2. Test statistics (aka score) /// 3. Critical value double* retVal ///< [inout] is the calculated test statistics. ); int __stdcall NDK_KPSSTEST(double* pData, size_t nSize, WORD maxOrder, WORD option, BOOL testDown, WORD argMethod, WORD retType, double alpha, double* retVal); /*! * \brief Returns the Johansen (cointegration) test statistics for two or more time series. * \note 1. Each column in the input matrix corresponds to a separate time series variable. * \note 2. The input matrix can have no more than twelve (12) columns (or variables). * \note 3. Each row in the input matrix corresponds to an observation. * \note 4. The number of cointegrating relationships should be no greater than the number of input variables. * \note 5. The time series data are homogeneous or equally spaced. * \note 6. The time series may include missing values (e.g. NaN) at either end. * \note 7. There are two types of Johansen tests - with trace or with eigenvalue - and the inferences might be a bit different for each. * - The null hypothesis for the trace test is the number of cointegration vectors r <= ? * - The null hypothesis for the eigenvalue test is r = ? * \note 8. The function was added in version 1.62 DEWDROP. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_ADFTEST(), NDK_MEANTEST(), NDK_STDEVTEST(), NDK_SKEWTEST() * */ int __stdcall NDK_JOHANSENTEST(double** XX, ///< [in] is the multivariate time series matrix data (two dimensional). size_t N, ///< [in] is the number of observations in XX. size_t M, ///< [in] is the number of variables in XX. size_t K, ///< [in] is the number of lagged difference terms used when computing the estimator. short nPolyOrder, ///< [in] is the order of the polynomial: (-1=no constant, 0=contant-only (default), 1=constant and trend). BOOL tracetest, ///< [in] is a flag to select test: TRUE=trace, FALSE=maximal eignvalue test. WORD R, ///< [in] is the assumed number of cointegrating relationships between the variables (if missing, r=1). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retStat, ///< [out] is the calculated test statistics score. double *retCV ///< [out] is the calculated test critical value. ); /// \example sdk_cointegration.cpp /*! * \brief Returns the collinearity test statistics for a set of input variables. * \note 1. Each column in the input matrix corresponds to a separate time series variable. * \note 2. The input matrix can have no more than twelve (12) columns (or variables). * \note 3. Each row in the input matrix corresponds to an observation. * \note 4. The input data may include missing values (e.g. NaN). * \note 5. In the variance inflation factor (VIF) method, a series of regressions models are constructed, where one variable is the dependent variable against the remaining predictors. * \note 6. A tolerance of less than 0.20 or 0.10 and/or a VIF of 5 or 10 and above indicates a multicollinearity problem. * \note 7. As a rule of thumb, a condition number (\f$\kappa\f$) greater or equal to 30 indicates a severe multi-collinearity problem. * \note 8. The CollinearityTest function is available starting with version 1.60 APACHE. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_CHOWTEST() * */ int __stdcall NDK_COLNRTY_TEST (double** XX, ///< [in] is the input variables matrix data (two dimensional). size_t N, ///< [in] is the number of rows (observations) in XX. size_t M, ///< [in] is the number of columns (variables) in XX. LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If NULL, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the mask. Must be zero or equal to M. COLNRTY_TEST_TYPE nMethod, ///< [in] is the multi-colinearity measure to compute (see #COLNRTY_TEST_TYPE). WORD nColIndex, ///< [in] is a switch to designate the explanatory variable to examine (not required for condition number). double* retVal ///< [out] is the calculated statistics of collinearity. ); /*! * \brief Returns the p-value of the regression stability test (i.e. whether the coefficients in two linear regressions on different data sets are equal). * \note 1. Each column in the input matrix corresponds to a separate time series variable. * \note 2. The input matrix can have no more than twelve (12) columns (or variables). * \note 3. Each row in the input matrix corresponds to an observation. * \note 4. The input data may include missing values (e.g. NaN). * \note 5. Observations (i.e. row) with missing values in X or Y are removed. * \note 6. The number of observations of each data set must be larger than the number of explanatory variables. * \note 8. The CollinearityTest function is available starting with version 1.60 APACHE. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful. see \ref SFMacros.h * \sa NDK_COLNRTY_TEST() * */ int __stdcall NDK_CHOWTEST( double** XX1, ///< [in] is the independent variables data matrix of the first data set (two dimensional). size_t M, ///< [in] is the number of variables (columns) in XX1 and XX2. double* Y1, ///< [in] is the response or the dependent variable data array for the first data set (one dimensional array). size_t N1, ///< [in] is the number of observations (rows) in the first data set. double** XX2, ///< [in] is the independent variables data matrix of the second data set, such that each column represents one variable. double* Y2, ///< [in] is the response or the dependent variable data array of the second data set (one dimensional array). size_t N2, ///< [in] is the number of observations (rows) in the second data set. LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If NULL, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the mask, which must be zero or equal to M. double intercept, ///< [in] is the regression constant or the intercept value (e.g. zero). If missing, an intercept is not fixed and will be computed from the data set. TEST_RETURN retType, ///< [in] is a switch to select the return output (see #TEST_RETURN for more details). double* retVal ///< [in] is the calculated Chow test statistics. ); ///@} /*! * \name Transfom * @{ */ /*! * \brief Returns an array of cells for the backward shifted, backshifted or lagged time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_DIFF() */ int __stdcall NDK_LAG(double* X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t K ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). ); /*! * \brief Returns an array of cells for the differenced time series (i.e. (1-L^S)^D). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_LAG(), NDK_INTEG */ int __stdcall NDK_DIFF( double* X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t S, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). size_t D ///< [in] is the number of repeated differencing (e.g. d=0 (none), d=1 (difference once), 2=(difference twice), etc.). ); /*! * \brief Returns an array of cells for the integrated time series (inverse operator of NDK_DIFF). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_LAG(), NDK_DIFF */ int __stdcall NDK_INTEG(double* X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t S, ///< [in] is the lag order (e.g. k=0 (no lag), k=1 (1st lag), etc.). size_t D, ///< [in] is the number of repeated differencing (e.g. d=0 (none), d=1 (difference once), 2=(difference twice), etc.). double* X0, ///< [in,optional] is the initial (un-differenced) univariate time series data (a one dimensional array). If missing (i.e. NULL), zeros are assumed. size_t N0 ///< [in] is the number of observations in X0. ); /*! * \brief Returns an array of cells of a time series after removing all missing values. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_LAG(), NDK_DIFF */ int __stdcall NDK_RMNA( double *X, ///< [inout] is the univariate sample data (a one dimensional array). size_t* N ///< [inout] is the number of observations in X. ); /*! * \brief Returns the time-reversed order time series (i.e. the first observation is swapped with the last observation, etc.): both missing and non-missing values. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_LAG(), NDK_DIFF */ int __stdcall NDK_REVERSE(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N ///< [in] is the number of observations in X. ); /*! * \brief Returns an array of cells for the scaled time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ADD(), NDK_SUB() */ int __stdcall NDK_SCALE(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double K ///< [in] is the scalar/multiplier value. ); /*! * \brief Returns an array of the difference between two time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_ADD(), NDK_SCALE() */ int __stdcall NDK_SUB(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N1, ///< [in] is the number of observations in X. const double *Y, ///< [in] is the second univariate time series data (a one dimensional array). size_t N2 ///< [in] is the number of observations in Y. ); /*! * \brief Returns an array of cells for the sum of two time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_SUB(), NDK_SCALE() */ int __stdcall NDK_ADD(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N1, ///< [in] is the number of observations in X. const double *Y, ///< [in] is the second univariate time series data (a one dimensional array). size_t N2 ///< [in] is the number of observations in Y. ); /*! * \brief Computes the complementary log-log transformation, including its inverse. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_HodrickPrescotFilter(), NDK_DFT(), NDK_IDFT() */ int __stdcall NDK_CLOGLOG(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD retTYpe ///< [in] is a number that determines the type of return value: 1 (or missing)=C-log-log , 2=inverse C-log-log. ); /*! * \brief Computes the probit transformation, including its inverse. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_HodrickPrescotFilter(), NDK_DFT(), NDK_IDFT() */ int __stdcall NDK_PROBIT(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD retTYpe ///< [in] is a number that determines the type of return value: 1 (or missing)=probit , 2=inverse probit. ); /*! * \brief Computes the complementary log-log transformation, including its inverse. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_PROBIT(), NDK_BOXCOX(), NDK_CLOGLOG() */ int __stdcall NDK_LOGIT(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD retTYpe ///< [in] is a number that determines the type of return value: 1 (or missing)=logit, 2=inverse logit. ); /*! * \brief Computes the complementary log-log transformation, including its inverse. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_LOGIT(), NDK_PROBIT(), NDK_CLOGLOG() */ int __stdcall NDK_BOXCOX( double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* lambda, ///< [in] is the input power parameter of the transformation, on a scale from 1 to 0. If omitted, a default value of 0 is assumed. double* alpha, ///< [in] is the input shift parameter for X. If omitted, the default value is 0. int retTYpe, ///< [in] is a number that determines the type of return value: 1 (or missing)=Box-Cox, 2=inverse Box-Cox, 3= LLF of Box-Cox. double *retVal ///< [out] is the calculated log-likelihood value of the transform (retType=3). ); /*! * \brief Detrends a time series using a regression of y against a polynomial time trend of order p. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_BOXCOX(), NDK_RMSEASONAL(), NDK_DIFF() */ int __stdcall NDK_DETREND(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD polyOrder ///< [in] is the order of the polynomial time trend: /// 0. subtracts mean (default) /// 1. constant plus trend model /// 2. constant plus trend and squared trend model ); /*! * \brief Returns an array of the deseasonalized time series, assuming a linear model. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_DETREND(), NDK_DIFF() */ int __stdcall NDK_RMSEASONAL( double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. size_t period ///< [in] is the number of observations(i.e. points) in one season. ); /*! * \brief Returns an array of a time series after substituting all missing values with the mean/median. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_RMNA(), NDK_INTERPOLATE() */ int __stdcall NDK_INTERP_NAN( double* X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. WORD nMethod, ///< [in] is an identifier for the method used to generate values for any missing data: /// 1. Mean (default) /// 2. Median /// 3. Constant /// 4. Forward flat /// 5. Backward flat /// 6. Linear /// 7. Cubic spline /// 8. Weighted moving average /// 9. Exponential smoothing /// 10. Brownian bridge double plug ///< [in] is the data argument related to the selected treatment method (if applicable). For instance, if the method is constant, then the value would be the actual value. ); /*! * \brief Examine whether the given array has one or more missing values. * \return status code of the operation * \retval #NDK_TRUE One or more missing value are detected. * \retval #NDK_FALSE No missing value is found. * \retval #NDK_FAILED Operation unsuccessful. See \ref SFMacros.h for more details. * \sa NDK_RMNA(), NDK_INTERP_NAN() */ int __stdcall NDK_HASNA(const double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. BOOL intermediate ///< [in] is a switch to tune the search for missng values: /// - TRUE = Only search for intermediate missing values. /// - FALSE = Search for all missing values in X. ); /// \name Resampling /// resampling API functions calls /// @{ /*! * \brief Returns the resampled time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SESMTH(), NDK_EWMA(), NDK_DESMTH(), NDK_TESMTH, NDK_LESMTH() */ int __stdcall NDK_RESAMPLE(double* pData, size_t nSize, BOOL isStock, double relSampling, IMPUTATION_METHOD method, double* pOutData, size_t *newSize); int __stdcall NDK_INTERP_BROWN(double* pData , size_t nSize); ///@} /// \name Smoothing /// Smoothing API functions calls /// @{ /*! * \brief Returns the weighted moving (rolling/running) average using the previous m data points. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SESMTH(), NDK_EWMA(), NDK_DESMTH(), NDK_TESMTH, NDK_LESMTH() */ int __stdcall NDK_WMA(double *pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of elements in pData. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). double* weights, ///< [in] is the size of the equal-weighted window or an array of multiplying factors (i.e. weights) of the moving/rolling window. size_t nwSize, ///< [in] is the number of elements in the weights array. int nHorizon, ///< [in] is the forecast time/horizon beyond the end of X. If missing, a default value of 0 (Latest or end of X) is assumed. double* retVal ///< [out] is the calculated value of the weighted moving average. ); /*! * \brief Returns the (Brown's) simple exponential (EMA) smoothing estimate of the value of X at time t+m (based on the raw data up to time t). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_WMA(), NDK_EWMA(), NDK_DESMTH(), NDK_TESMTH, NDK_LESMTH() */ int __stdcall NDK_SESMTH(double *pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of elements in pData. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). double* alpha, ///< [inout] is the smoothing factor (alpha should be between zero and one (exclusive)). If missing or omitted, a value of 0.333 is used. int nHorizon, ///< [in] is the forecast time horizon beyond the end of X. If missing, a default value of 0 (latest or end of X) is assumed. BOOL bOptimize, ///< [in] is a flag (True/False) for searching and using the optimal value of the smoothing factor. If missing or omitted, optimize is assumed false. double* internals, ///< [out,opt] is an array of the intermediate forecast calculation. size_t nInternalsSize, ///< [inout,opt] size of the output buffer, and number or values to return. double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the (Holt-Winter's) double exponential smoothing estimate of the value of X at time T+m. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_WMA(), NDK_EWMA(), NDK_SESMTH(), NDK_TESMTH, NDK_LESMTH() */ int __stdcall NDK_DESMTH(double *pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of elements in pData. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). double *alpha, ///< [in] is the data smoothing factor (alpha should be between zero and one (exclusive)). double *beta, ///< [in] is the trend smoothing factor (beta should be between zero and one (exclusive)). int xlHorizon, ///< [in] is the forecast time horizon beyond the end of X. If missing, a default value of 0 (latest or end of X) is assumed. BOOL bOptimize, ///< [in] is a flag (True/False) for searching and using the optimal value of the smoothing factor. If missing or omitted, optimize is assumed false. double* internals, ///< [out,opt] is an array of the intermediate forecast calculation. size_t nInternalsSize, ///< [in,opt] size of the output buffer, and number or values to return. WORD wInternalSeries, ///< [in, opt] a switch to select the series to return in internals ( 0 = Smoothing forecast, 1=level, 2=trend) double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the (Brown's) linear exponential smoothing estimate of the value of X at time T+m (based on the raw data up to time t). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_WMA(), NDK_EWMA(), NDK_SESMTH(), NDK_TESMTH, NDK_DESMTH() */ int __stdcall NDK_LESMTH( double *pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of elements in pData. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). double *alpha, ///< [in] is the smoothing factor (alpha should be between zero and one (exclusive)). If missing or omitted, a value of 0.333 is used. int xlHorizon, ///< [in] is the forecast time horizon beyond the end of X. If missing, a default value of 0 (latest or end of X) is assumed. BOOL bOptimize, ///< [in] is a flag (True/False) for searching and using the optimal value of the smoothing factor. If missing or omitted, optimize is assumed false. double* internals, ///< [out,opt] is an array of the intermediate forecast calculation. size_t nInternalsSize, ///< [in,opt] size of the output buffer, and number or values to return. WORD wInternalSeries, ///< [in, opt] a switch to select the series to return in internals ( 0 = Smoothing forecast, 1=level, 2=trend) double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the (Winters's) triple exponential smoothing estimate of the value of X at time T+m. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_WMA(), NDK_EWMA(), NDK_SESMTH(), NDK_LESMTH, NDK_DESMTH() */ int __stdcall NDK_TESMTH(double *pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of elements in pData. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). double *alpha, ///< [in] is the data smoothing factor (alpha should be between zero and one (exclusive)). double *beta, ///< [in] is the trend smoothing factor (beta should be between zero and one (exclusive)). double *gamma, ///< [in] is the seasonal change smoothing factor (Gamma should be between zero and one (exclusive)). int L, ///< [in] is the season length. int nHorizon, ///< [in] is the forecast time horizon beyond the end of X. If missing, a default value of 0 (latest or end of X) is assumed. BOOL bOptimize, ///< [in] is a flag (True/False) for searching and using optimal value of the smoothing factor. If missing or omitted, optimize is assumed false. double* internals, ///< [out,opt] is an array of the intermediate forecast calculation. size_t nInternalsSize, ///< [in,opt] size of the output buffer, and number or values to return. WORD wInternalSeries, ///< [in, opt] a switch to select the series to return in internals ( 0 = Smoothing forecast, 1=level, 2=trend) double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns the (Winters's) triple exponential smoothing estimate of the value of X at time T+m. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_WMA(), NDK_EWMA(), NDK_SESMTH(), NDK_LESMTH, NDK_DESMTH() */ int __stdcall NDK_GESMTH(double *pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of elements in pData. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). double *alpha, ///< [in] is the data smoothing factor (alpha should be between zero and one (exclusive)). double *beta, ///< [in] is the trend smoothing factor (beta should be between zero and one (exclusive)). double *gamma, ///< [in] is the seasonal change smoothing factor (Gamma should be between zero and one (exclusive)). double *phi, ///< [in] is the damping coefficient for the trend. double *lambda, ///< [in] is the coefficient value for the autocorrelation adjustment WORD TrendType, ///< [in] is the type of trend in the model (0=none, 1=additive, 2- damped additive, 3=multiplicative, 4=damped multiplicative) WORD SeasonalityType, ///< [in] is the type of seasonality in the modem (0=none, 1=additive, 2=multiplicative) int seasonLength, ///< [in] is the season length. int nHorizon, ///< [in] is the forecast time horizon beyond the end of X. If missing, a default value of 0 (latest or end of X) is assumed. BOOL bOptimize, ///< [in] is a flag (True/False) for searching and using optimal value of the smoothing factor. If missing or omitted, optimize is assumed false. BOOL bAutoCorrelationAdj, ///< [in] is a flag (True/False) for adding a correction term for the 1st ourder autocorrelation in the BOOL bLogTransform, ///< [in] is a flag (True/False) for applying natural log transform to the input data prior to smoothing. double* internals, ///< [out,opt] is an array of the intermediate forecast calculation. size_t nInternalsSize, ///< [in,opt] size of the output buffer, and number or values to return. WORD wInternalSeries, ///< [in, opt] a switch to select the series to return in internals ( 0 = one-step forecasting, 1=level, 2=trend, 3=seasonality) double* retVal ///< [out] is the calculated value of this function. ); /*! * \brief Returns values along a trend curve (e.g. linear, quadratic, exponential, etc.) at time T+m. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_WMA(), NDK_EWMA(), NDK_SESMTH(), NDK_LESMTH, NDK_DESMTH(), NDK_TESMTH */ int __stdcall NDK_TREND(double *pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of elements in pData. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). WORD nTrendType, ///< [in] is the model description flag for the trend function: /// 1. Linear /// 2. Polynomial /// 3. Exponential /// 4. Logarithmic /// 5. Power WORD argPolyOrder, ///< [in] is the polynomial order. This is only relevant for a polynomial trend type and is ignored for all others. If missing, POrder = 1. BOOL AllowIntercep, ///< [in] is a switch to include or exclude an intercept in the regression. double InterceptVal, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. int nHorizon, ///< [in] is the forecast time horizon beyond the end of X. If missing, a default value of 0 (latest or end of X) is assumed. WORD retType, ///< [in] is a switch to select the return output: /// 1. Forecast value /// 2. Upper limit of the confidence interval /// 3. Lower limit of the confidence interval /// 4. R-Squared double argAlpha, ///< [in] is the statistical significance or confidence level (i.e. alpha). If missing or omitted, an alpha value of 5% is assumed. double* retVal ///< [out] is the calculated value of this function. ); ///@} /// \name Multiple Linear Regression (MLR) /// @{ int __stdcall NDK_SLR_PARAM (double* pXData, size_t nXSize, double* pYData, size_t nYSize, double intercept, double alpha, WORD nRetType, WORD ParamIndex, double* retVal); int __stdcall NDK_SLR_FORE (double* pXData, size_t nXSize, double* pYData, size_t nYSize, double intercept, double target, double alpha, WORD nRetType, double* retVal); int __stdcall NDK_SLR_FITTED (double* pXData, size_t nXSize, double* pYData, size_t nYSize, double intercept, WORD nRetType); int __stdcall NDK_SLR_ANOVA ( double* pXData, size_t nXSize, double* pYData, size_t nYSize, double intercept, WORD nRetType, double* retVal); int __stdcall NDK_SLR_GOF ( double* pXData, size_t nXSize, double* pYData, size_t nYSize, double intercept, WORD nRetType, double* retVal); /*! * \brief Calculates the OLS regression coefficients values. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_MLR_FORE(), NDK_MLR_FITTED(), NDK_MLR_ANOVA(), NDK_MLR_GOF, NDK_MLR_PRFTest, NDK_MLR_STEPWISE */ int __stdcall NDK_MLR_PARAM (double** X, ///< [in] is the independent (explanatory) variables data matrix, such that each column represents one variable. size_t nXSize, ///< [in] is the number of observations (rows) in X. size_t nXVars, ///< [in] is the number of independent (explanatory) variables (columns) in X. LPBYTE mask, ///< [in] is the boolean array to choose the explanatory variables in the model. If missing, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the "mask." double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array of cells). size_t nYSize, ///< [in] is the number of observations in Y. double intercept, ///< [in] is the constant or intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. double alpha, ///< [in] is the statistical significance of the test (i.e. alpha). If missing or omitted, an alpha value of 5% is assumed. WORD nRetType, ///< [in] is a switch to select the return output (1=value (default), 2=std. error, 3=t-stat, 4=P-value, 5=upper limit (CI), 6=lower limit (CI)): /// 1. Value (mean) /// 2. Std error /// 3. Test score /// 4. P-value /// 5. Upper limit of the confidence interval /// 6. Lower limit of the confidence interval WORD nParamIndex, ///< [in] is a switch to designate the target parameter (0=intercept (default), 1=first variable, 2=2nd variable, etc.). double* retVal ///< [out] is the computed statistics of the regression coefficient. ); /*! * \brief Calculates the forecast mean, error and confidence interval. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_MLR_PARAM(), NDK_MLR_FITTED(), NDK_MLR_ANOVA(), NDK_MLR_GOF, NDK_MLR_PRFTest, NDK_MLR_STEPWISE */ int __stdcall NDK_MLR_FORE (double** X, ///< [in] is the independent (explanatory) variables data matrix, such that each column represents one variable. size_t nXSize, ///< [in] is the number of observations (rows) in X. size_t nXVars, ///< [in] is the number of independent (explanatory) variables (columns) in X. LPBYTE mask, ///< [in] is the boolean array to choose the explanatory variables in the model. If missing, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the "mask." double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array of cells). size_t nYSize, ///< [in] is the number of observations in Y. double intercept, ///< [in] is the constant or intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. double* target, ///< [in] is the value of the explanatory variables (a one dimensional array). double alpha, ///< [in] is the statistical significance of the test (i.e. alpha). If missing or omitted, an alpha value of 5% is assumed. WORD nRetType, ///< [in] is a switch to select the return output (1=forecast (default), 2=error, 3=upper limit, 4=lower limit): /// 1. Forecast (mean) /// 2. Std error /// 3. Upper limit of the confidence interval /// 4. Lower limit of the conficence interval double* retVal ///< [out] is the computed forecast statistics. ); /*! * \brief Returns the fitted values of the conditional mean, residuals or leverage measures. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_MLR_FORE(), NDK_MLR_PARAM(), NDK_MLR_ANOVA(), NDK_MLR_GOF, NDK_MLR_PRFTest, NDK_MLR_STEPWISE */ int __stdcall NDK_MLR_FITTED (double** X, ///< [in] is the independent (explanatory) variables data matrix, such that each column represents one variable. size_t nXSize, ///< [in] is the number of observations (rows) in X. size_t nXVars, ///< [in] is the number of independent (explanatory) variables (columns) in X. LPBYTE mask, ///< [in] is the boolean array to choose the explanatory variables in the model. If missing, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the "mask." double* Y, ///< [in] is the response or dependent variable data array (one dimensional array of cells). size_t nYSize, ///< [in] is the number of observations in Y. double intercept, ///< [in] is the constant or intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. WORD nRetType ///< [in] is a switch to select the return output (1=fitted values (default), 2=residuals, 3=standardized residuals, 4=leverage, 5=Cook's distance). /// 1. Fitted/conditional mean /// 2. Residuals /// 3. Standardized residuals /// 4. Leverage factor (H) /// 5. Cook's distance (D) ); /*! * \brief Calculates the regression model analysis of the variance (ANOVA) values. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_MLR_FORE(), NDK_MLR_PARAM(), NDK_MLR_FITTED(), NDK_MLR_GOF, NDK_MLR_PRFTest, NDK_MLR_STEPWISE */ int __stdcall NDK_MLR_ANOVA (double** pXData, ///< [in] is the independent (explanatory) variables data matrix, such that each column represents one variable. size_t nXSize, ///< [in] is the number of observations (rows) in X size_t nXVars, ///< [in] is the number of independent (explanatory) variables (columns) in X. LPBYTE mask, ///< [in] is the boolean array to choose the explanatory variables in the model. If missing, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the "mask." double* Y, ///< [in] is the response or dependent variable data array (one dimensional array of cells). size_t nYSize, ///< [in] is the number of observations in Y. double intercept, ///< [in] is the constant or intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. WORD nRetType, ///< [in] is a switch to select the output (1=SSR (default), 2=SSE, 3=SST, 4=MSR, 5=MSE, 6=F-stat, 7=P-value): /// 1. SSR (sum of squares of the regression) /// 2. SSE (sum of squares of the residuals) /// 3. SST (sum of squares of the dependent variable) /// 4. MSR (mean squares of the regression) /// 5. MSE (mean squares error or residuals) /// 6. F-stat (test score) /// 7. Significance F (P-value of the test) double* retVal ///< [out] is the calculated statistics ANOVA output. ); /*! * \brief Calculates a measure for the goodness of fit (e.g. R^2). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_MLR_FORE(), NDK_MLR_PARAM(), NDK_MLR_FITTED(), NDK_MLR_GOF, NDK_MLR_PRFTest, NDK_MLR_STEPWISE */ int __stdcall NDK_MLR_GOF ( double** X, ///< [in] is the independent (explanatory) variables data matrix, such that each column represents one variable. size_t nXSize, ///< [in] is the number of observations (rows) in X. size_t nXVars, ///< [in] is the number of independent (explanatory) variables (columns) in X. LPBYTE mask, ///< [in] is the boolean array to choose the explanatory variables in the model. If missing, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the "mask." double* Y, ///< [in] is the response or dependent variable data array (one dimensional array of cells). size_t nYSize, ///< [in] is the number of observations in Y. double intercept, ///< [in] is the constant or intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. WORD nRetType, ///< [in] is a switch to select a fitness measure (1=R-square (default), 2=adjusted R-square, 3=RMSE, 4=LLF, 5=AIC, 6=BIC/SIC): /// 1. R-square (coefficient of determination) /// 2. Adjusted R-square /// 3. Regression Error (RMSE) /// 4. Log-likelihood (LLF) /// 5. Akaike information criterion (AIC) /// 6. Schwartz/Bayesian information criterion (SIC/BIC) double* retVal ///< [out] is the calculated goodness-of-fit statistics. ); /*! * \brief Calculates the p-value and related statistics of the partial f-test (used for testing the inclusion/exclusion variables). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_MLR_FORE(), NDK_MLR_PARAM(), NDK_MLR_ANOVA(), NDK_MLR_GOF, NDK_MLR_FITTED, NDK_MLR_STEPWISE */ int __stdcall NDK_MLR_PRFTest ( double** X, ///< [in] is the independent (explanatory) variables data matrix, such that each column represents one variable. size_t nXSize, ///< [in] is the number of observations (rows) in X. size_t nXVars, ///< [in] is the number of independent (explanatory) variables (columns) in X. double* Y, ///< [in] is the response or dependent variable data array (one dimensional array of cells). size_t nYSize, ///< [in] is the number of observations in Y. double intercept, ///< [in] is the constant or intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. LPBYTE mask1, ///< [in] is the boolean array to choose the explanatory variables in model 1. If missing, all variables in X are included. size_t nMaskLen1, ///< [in] is the number of elements in "mask1." LPBYTE mask2, ///< [in] is the boolean array to choose the explanatory variables in model 2. If missing, all variables in X are included. size_t nMaskLen2, ///< [in] is the number of elements in "mask2." double alpha, ///< [in] is the statistical significance of the test (i.e. alpha). If missing or omitted, an alpha value of 5% is assumed. WORD nRetType, ///< [in] is a switch to select the return output (1 = P-Value (default), 2 = Test Stats, 3 = Critical Value.) double* retVal ///< [out] is the calculated test statistics/ ); /*! * \brief Returns a list of the selected variables after performing the stepwise regression. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_MLR_FORE(), NDK_MLR_PARAM(), NDK_MLR_ANOVA(), NDK_MLR_GOF, NDK_MLR_PRFTest, NDK_MLR_STEPWISE */ int __stdcall NDK_MLR_STEPWISE (double** X, ///< [in] is the independent (explanatory) variables data matrix, such that each column represents one variable. size_t nXSize, ///< [in] is the number of observations (rows) in X. size_t nXVars, ///< [in] is the number of independent (explanatory) variables (columns) in X. LPBYTE mask, ///< [inout] is the boolean array to choose the explanatory variables in the model. If missing, all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in the "mask." double* Y, ///< [in] is the response or dependent variable data array (one dimensional array of cells). size_t nYSize, ///< [in] is the number of observations in Y. double intercept, ///< [in] is the constant or intercept value to fix (e.g. zero). If missing (i.e. NaN), an intercept will not be fixed and is computed normally. double alpha, ///< [in] is the statistical significance of the test (i.e. alpha). If missing or omitted, an alpha value of 5% is assumed. WORD nMode ///< [in] is a switch to select the variable's inclusion/exclusion approach (1=forward selection (default), 2=backward elimination , 3=bi-directional elimination): /// 1. Forward selection /// 2. Bacward elemination /// 3. Bi-directional elemination ); ///@} /// \name Principal Component Analysis (PCA) /// @{ /*! * \brief Returns an array of cells for the i-th principal component (or residuals). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCA_COMP (double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in WORD standardize, ///< [in] is a flag or switch to standardize the input variables prior to the analysis: /// 1. standardize ((subtract mean and divide by standard deviation) /// 2. subtract mean. WORD nCompIndex, ///< [in] is the component number to return. WORD retType, ///< [in] is a switch to select the return output /// 1. proportion of variance, /// 2. variance, /// 3. eigenvalue, /// 4. loadings, /// 5. Principal Component (PC) data. double* retVal, ///< [out] is the calculated value or data size_t nOutSize ///< [in] is the size of retVal ); /*! * \brief Returns an array of cells for the fitted values of the i-th input variable. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCA_VAR ( double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE varMask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in mask WORD standardize, ///< [in] is a flag or switch to standardize the input variables prior to the analysis: /// 1. standardize ((subtract mean and divide by standard deviation) /// 2. subtract mean. WORD nVarIndex, ///< [in] is the input variable number WORD wMacPC, ///< [in] is the number of principal components (PC) to include WORD retType, ///< [in] is a switch to select the return output: /// 1. final communality /// 2. loading/weights /// 3. fitted values /// 4. residuals double* retVal, ///< [out] is the calculated value or data size_t nOutSize ///< [in] is the size of retVal ); /*! * \brief Calculates the regression coefficients values for a given input variable. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCR_PARAM ( double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in mask double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nYSize, ///< [in] is the number of elements in Y double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally double alpha, ///< [in] is the statistical significance of the test (i.e. alpha) WORD nRetType, ///< [in] is a switch to select the return output: /// 1. Value (default), /// 2. Std. Error /// 3. t-stat /// 4. P-Value /// 5. Upper Limit (CI) /// 6. Lower Limit (CI)) WORD nParamIndex, ///< [in] is a switch to designate the target parameter (0 = intercept (default), 1 = first variable, 2 = 2nd variable, etc.). double* retVal ///< [out] is the calculated parameter value or statistics. ); /*! * \brief Calculates the model's estimated values, std. errors and related statistics. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCR_FORE (double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in mask double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nYSize, ///< [in] is the number of elements in Y double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally double* target, ///< [in] is the value of the explanatory variables (a one dimensional array) double alpha, ///< [in] is the statistical significance of the test (i.e. alpha) WORD nRetType, ///< [in] is a switch to select the return output (1 = forecast (default), 2 = error, 3 = upper limit, 4 = lower limit). double* retVal ///< [out] is the calculated forecast value or statistics. ); /*! * \brief Returns an array of cells for the i-th principal component (or residuals). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCR_FITTED (double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in mask double* Y, ///< [inout] is the response or the dependent variable data array (one dimensional array) size_t nYSize, ///< [in] is the number of elements in Y double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally WORD nRetType ///< [in] is a switch to select the return output /// 1. fitted values (default), /// 2. residuals, /// 3. standardized residuals, /// 4. leverage (H), /// 5. Cook's distance. ); /*! * \brief Returns an array of cells for the i-th principal component (or residuals). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCR_ANOVA ( double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in mask double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nYSize, ///< [in] is the number of elements in Y double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally WORD nRetType, ///< [in] is a switch to select the return output: /// 1. SSR (sum of squares of the regression) /// 2. SSE (sum of squares of the residuals) /// 3. SST (sum of squares of the dependent variable) /// 4. MSR (mean squares of the regression) /// 5. MSE (mean squares error or residuals) /// 6. F-stat (test score) /// 7. Significance F (P-value of the test) double* retVal ///< [out] is the calculated statistics ANOVA output. ); /*! * \brief Returns an array of cells for the i-th principal component (or residuals). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCR_GOF ( double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in mask double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nYSize, ///< [in] is the number of elements in Y double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally WORD nRetType, ///< [in] is a switch to select a fitness measure (1 = R-Square (default), 2 = Adjusted R Square, 3 = RMSE, 4 = LLF, 5 = AIC, 6 = BIC/SIC ). /// 1. R-square (coefficient of determination) /// 2. Adjusted R-square /// 3. Regression Error (RMSE) /// 4. Log-likelihood (LLF) /// 5. Akaike information criterion (AIC) /// 6. Schwartz/Bayesian information criterion (SIC/BIC) double* retVal ///< [out] is the calculated goodness of fit measure ); /*! * \brief Returns an array of cells for the i-th principal component (or residuals). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCR_PRFTest ( double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nYSize, ///< [in] is the number of elements in Y double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally LPBYTE mask1, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen1, ///< [in] is the number of elements in mask1 LPBYTE mask2, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen2, ///< [in] is the number of elements in mask2 double alpha, ///< [in] is the statistical significance of the test (i.e. alpha) WORD nRetType, ///< [in] is a switch to select the return output (1 = P-Value (default), 2 = Test Stats, 3 = Critical Value.) double* retVal ///< [out] is the calculated test statistics/ ); /*! * \brief Returns an array of cells for the i-th principal component (or residuals). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PCA_VAR(), NDK_PCR_PARAM(), NDK_PCR_FORE(), NDK_PCR_FITTED(), NDK_PCR_ANOVA(), NDK_PCR_GOF(), NDK_PCR_PRFTest(), NDK_PCR_STEPWISE() */ int __stdcall NDK_PCR_STEPWISE (double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nXSize, ///< [in] is the number of observations (i.e. rows) in X size_t nXVars, ///< [in] is the number of variables (i.e. columns) in X LPBYTE mask, ///< [in] is the boolean array to select a subset of the input variables in X. If missing (i.e. NULL), all variables in X are included. size_t nMaskLen, ///< [in] is the number of elements in mask double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nYSize, ///< [in] is the number of elements in Y double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally double alpha, ///< [in] is the statistical significance of the test (i.e. alpha) WORD nMode ///< [in] is a switch to select the variable's inclusion/exclusion approach (1=forward selection (default), 2=backward elimination , 3=bi-directional elimination): /// 1. Forward selection /// 2. Bacward elemination /// 3. Bi-directional elemination ); ///@} /// \name GLM /// Gneralized Linear Model Functions /// @{ /*! * \brief Examines the model's parameters for constraints (e.g. positive variance, etc.). * \details * \htmlonly <h4>Notes</h4> <ol> <li>The number of betas must be equal to the number of explanatory variables (i.e. X) plus one (intercept). </li> <li> For GLM with Poisson distribution: <ul> <li>The values of the response variables must be non-negative integers.</li> <li>The value of the dispersion factor (Phi) value must be either missing or equal to one.</li> </ul> </li> <li> For GLM with Binomial distribution, <ul> <li>The values of the response variable must be non-negative fractions between zero and one, inclusive.</li> <li>The value of the dispersion factor (Phi) must be a positive fraction (greater than zero, and less than one).</li> </ul> </li> <li>For GLM with Guassian distribution, the dispersion factor (Phi) value must be positive.</li> </ol> * \endhtmlonly * \return status code of the operation * \retval #NDK_TRUE GLM model is valid * \retval #NDK_FALSE GLM model in invalid. For other return values, see \ref SFMacros.h * \sa NDK_GLM_FITTED(), NDK_GLM_RESID(), NDK_GLM_PARAM(), NDK_GLM_FORE */ int __stdcall NDK_GLM_VALIDATE(double* betas, ///< [in] are the coefficients of the GLM model (a one dimensional array) size_t nBetas, ///< [in] is the number of the coefficients in betas. Note that nBetas must be equal to nVars+1 double phi, ///< [in] is the GLM dispersion paramter. Phi is only meaningful for Binomial (1/batch or trial size) and for Guassian (variance). /// - Binomial : phi = Reciprocal of the batch/trial size. /// - Gaussion : phi = variance. /// - Poisson : phi = 1.0 WORD Lvk ///< [in] is the link function that describes how the mean depends on the linear predictor (see #GLM_LINK_FUNC). /// 1. Identity (default) /// 2. Log /// 3. Logit /// 4. Probit /// 5. Complementary log-log ); /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit function of the GLM model. * \htmlonly <h4>Notes</h4> <ol> <li>Missng values (i.e. #N/A!) are not allowed in the either response(Y) or the explanatory input arrays.</li> <li>The number of rows in response variable (Y) must be equal to number of rows of the explanatory variables (X).</li> <li>The number of betas must equal to the number of explanatory variables (i.e. X) plus one (intercept). </li> <li> For GLM with Poisson distribution, <ul> <li>The values of response variable must be non-negative integers.</li> <li>The value of the dispersion factor (Phi) value must be either missing or equal to one.</li> </ul> </li> <li> For GLM with Binomial distribution, <ul> <li>The values of the response variable must be non-negative fractions between zero and one, inclusive.</li> <li>The value of the dispersion factor (Phi) must be a positive fraction (greater than zero, and less than one).</li> </ul> </li> <li>For GLM with Guassian distribution, the dispersion factor (Phi) value must be positive.</li> </ol> \endhtmlonly * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GLM_FITTED(), NDK_GLM_RESID(), NDK_GLM_PARAM(), NDK_GLM_FORE */ int __stdcall NDK_GLM_GOF( double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nSize, ///< [in] is the number of observations double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nVars, ///< [in] is the number of independent variables (or columns in X) double* betas, ///< [in] are the coefficients of the GLM model (a one dimensional array) size_t nBetas, ///< [in] is the number of the coefficients in betas. Note that nBetas must be equal to nVars+1 double phi, ///< [in] is the GLM dispersion paramter. Phi is only meaningful for Binomial (1/batch or trial size) and for Guassian (variance). /// - Binomial : phi = Reciprocal of the batch/trial size. /// - Gaussion : phi = variance. /// - Poisson : phi = 1.0 WORD Lvk, ///< [in] is the link function that describes how the mean depends on the linear predictor (see #GLM_LINK_FUNC). /// 1. Identity (default) /// 2. Log /// 3. Logit /// 4. Probit /// 5. Complementary log-log WORD retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC) double* retVal ///< [out] is the calculated goodness of fit measure. ); /*! * \brief Returns the standardized residuals/errors of a given GLM. * \htmlonly <h4>Notes</h4> <ol> <li>Missng values (i.e. #N/A!) are not allowed in the either response(Y) or the explanatory input arrays.</li> <li>The number of rows in response variable (Y) must be equal to number of rows of the explanatory variables (X).</li> <li>The number of betas must equal to the number of explanatory variables (i.e. X) plus one (intercept). </li> <li> For GLM with Poisson distribution, <ul> <li>The values of response variable must be non-negative integers.</li> <li>The value of the dispersion factor (Phi) value must be either missing or equal to one.</li> </ul> </li> <li> For GLM with Binomial distribution, <ul> <li>The values of the response variable must be non-negative fractions between zero and one, inclusive.</li> <li>The value of the dispersion factor (Phi) must be a positive fraction (greater than zero, and less than one).</li> </ul> </li> <li>For GLM with Guassian distribution, the dispersion factor (Phi) value must be positive.</li> </ol> \endhtmlonly * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GLM_FITTED(), NDK_GLM_RESID(), NDK_GLM_PARAM(), NDK_GLM_FORE */ int __stdcall NDK_GLM_RESID( double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nSize, ///< [in] is the number of observations double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nVars, ///< [in] is the number of independent variables (or columns in X) double* betas, ///< [in] are the coefficients of the GLM model (a one dimensional array) size_t nBetas, ///< [in] is the number of the coefficients in betas. Note that nBetas must be equal to nVars+1 double phi, ///< [in] is the GLM dispersion paramter. Phi is only meaningful for Binomial (1/batch or trial size) and for Guassian (variance). /// - Binomial : phi = Reciprocal of the batch/trial size. /// - Gaussion : phi = variance. /// - Poisson : phi = 1.0 WORD Lvk, ///< [in] is the link function that describes how the mean depends on the linear predictor (see #GLM_LINK_FUNC). /// 1. Identity (default) /// 2. Log /// 3. Logit /// 4. Probit /// 5. Complementary log-log WORD retType ///< [in] is a switch to select a residuals-type:raw or standardized. see \ref #RESID_RETVAL_FUNC ); /*! * \brief Returns an array of cells for the initial (non-optimal), optimal or standard errors of the model's parameters * \htmlonly <h4>Notes</h4> <ol> <li>Missng values (i.e. #N/A!) are not allowed in the either response(Y) or the explanatory input arrays.</li> <li>The number of rows in response variable (Y) must be equal to number of rows of the explanatory variables (X).</li> <li>The number of betas must equal to the number of explanatory variables (i.e. X) plus one (intercept). </li> <li> For GLM with Poisson distribution, <ul> <li>The values of response variable must be non-negative integers.</li> <li>The value of the dispersion factor (Phi) value must be either missing or equal to one.</li> </ul> </li> <li> For GLM with Binomial distribution, <ul> <li>The values of the response variable must be non-negative fractions between zero and one, inclusive.</li> <li>The value of the dispersion factor (Phi) must be a positive fraction (greater than zero, and less than one).</li> </ul> </li> <li>For GLM with Guassian distribution, the dispersion factor (Phi) value must be positive.</li> </ol> \endhtmlonly * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GLM_FITTED(), NDK_GLM_RESID(), NDK_GLM_GOF(), NDK_GLM_FORE */ int __stdcall NDK_GLM_PARAM( double* Y, ///< [in] is the response or the dependent variable data array (one dimensional array) size_t nSize, ///< [in] is the number of observations double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nVars, ///< [in] is the number of independent variables (or columns in X) double* betas, ///< [inout] are the coefficients of the GLM model (a one dimensional array) size_t nBetas, ///< [in] is the number of the coefficients in betas. Note that nBetas must be equal to nVars+1 double* phi, ///< [inout] is the GLM dispersion paramter. Phi is only meaningful for Binomial (1/batch or trial size) and for Guassian (variance). /// - Binomial : phi = Reciprocal of the batch/trial size. /// - Gaussion : phi = variance. /// - Poisson : phi = 1.0 WORD Lvk, ///< [in] is the link function that describes how the mean depends on the linear predictor (see #GLM_LINK_FUNC). /// 1. Identity (default) /// 2. Log /// 3. Logit /// 4. Probit /// 5. Complementary log-log WORD retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC) size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing, the default maximum of 100 is assumed. ); /*! * \brief calculates the expected response (i.e. mean) value; given the GLM model and the values of the explanatory variables. * * \htmlonly <h4>Notes</h4> <ol> <li>Missng values (i.e. #N/A!) are not allowed in the either response(Y) or the explanatory input arrays.</li> <li>The number of rows in response variable (Y) must be equal to number of rows of the explanatory variables (X).</li> <li>The number of betas must equal to the number of explanatory variables (i.e. X) plus one (intercept).</li> <li>For GLM with Poisson distribution, <ul> <li>The values of response variable must be non-negative integers.</li> <li>The value of the dispersion factor (Phi) value must be either missing or equal to one.</li> </ul> </li> <li>For GLM with Binomial distribution, <ul> <li>The values of the response variable must be non-negative fractions between zero and one, inclusive.</li> <li>The value of the dispersion factor (Phi) must be a positive fraction (greater than zero, and less than one).</li> </ul> </li> <li>For GLM with Guassian distribution, the dispersion factor (Phi) value must be positive.</li> </ol> \endhtmlonly * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GLM_FITTED(), NDK_GLM_RESID(), NDK_GLM_GOF(), NDK_GLM_FORE */ int __stdcall NDK_GLM_FORE( double* X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nVars, ///< [in] is the number of independent variables (or columns in X) double* betas, ///< [inout] are the coefficients of the GLM model (a one dimensional array) size_t nBetas, ///< [in] is the number of the coefficients in betas. Note that nBetas must be equal to nVars+1 double phi, ///< [inout] is the GLM dispersion paramter. Phi is only meaningful for Binomial (1/batch or trial size) and for Guassian (variance). /// - Binomial : phi = Reciprocal of the batch/trial size. /// - Gaussion : phi = variance. /// - Poisson : phi = 1.0 WORD Lvk, ///< [in] is the link function that describes how the mean depends on the linear predictor (see #GLM_LINK_FUNC). /// 1. Identity (default) /// 2. Log /// 3. Logit /// 4. Probit /// 5. Complementary log-log WORD retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref # FORECAST_RETVAL_FUNC) double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retval ///< [out] is the calculated forecast value ); int __stdcall NDK_GLM_FITTED( double* Y, ///< [inout] is the response or the dependent variable data array (one dimensional array) size_t nSize, ///< [in] is the number of observations double** X, ///< [in] is the independent variables data matrix, such that each column represents one variable size_t nVars, ///< [in] is the number of independent variables (or columns in X) double* betas, ///< [in] are the coefficients of the GLM model (a one dimensional array) size_t nBetas, ///< [in] is the number of the coefficients in betas. Note that nBetas must be equal to nVars+1 double phi, ///< [in] is the GLM dispersion paramter. Phi is only meaningful for Binomial (1/batch or trial size) and for Guassian (variance). /// - Binomial : phi = Reciprocal of the batch/trial size. /// - Gaussion : phi = variance. /// - Poisson : phi = 1.0 WORD Lvk, ///< [in] is the link function that describes how the mean depends on the linear predictor (see #GLM_LINK_FUNC). /// 1. Identity (default) /// 2. Log /// 3. Logit /// 4. Probit /// 5. Complementary log-log WORD retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC) ); ///@} /// \name ARMA /// The ARMA model is a tool for understanding and forecasting future values in a given time series. The model consists of two parts: an autoregressive component, i.e. AR(p), and a moving average component, i.e. MA(q), and it is referred to as ARMA(p,q). /// @{ /*! * \brief Computes the log-likelihood (LLF), Akaike Information Criterion (AIC) or other goodness of fit functions of the ARMA model. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARMA_PARAM(), NDK_ARMA_VALIDATE(), NDK_ARMA_FORE(), NDK_ARMA_RESID() */ int __stdcall NDK_ARMA_GOF( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). WORD retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC). double* retVal ///< [out] is the calculated goodness of fit value. ); /*! * \brief Returns the standardized residuals of a given ARMA model * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \deprecated this function is being replaced by NDK_ARMA_FITTED() * \sa NDK_ARMA_PARAM(), NDK_ARMA_VALIDATE(), NDK_ARMA_FORE(), NDK_ARMA_GOF() */ int __stdcall NDK_ARMA_RESID( double* pData, ///< [inout] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component) double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component) WORD retType ///< [in] is a switch to select a residuals-type:raw or standardized. see \ref #RESID_RETVAL_FUNC ); /*! * \brief Returns the initial (non-optimal), optimal or standard errors of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARMA_GOF(), NDK_ARMA_VALIDATE(), NDK_ARMA_FORE(), NDK_ARMA_RESID() */ int __stdcall NDK_ARMA_PARAM( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* mean, ///< [inout] is the ARMA model mean (i.e. mu). double* sigma, ///< [inout] is the standard deviation of the model's residuals/innovations. double* phis, ///< [inout] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [inout] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). MODEL_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC). size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Calculates the out-of-sample forecast statistics. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARMA_PARAM(), NDK_ARMA_VALIDATE(), NDK_ARMA_GOF(), NDK_ARMA_RESID() */ int __stdcall NDK_ARMA_FORE( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). size_t nStep, ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). FORECAST_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned (FORECAST_MEAN, FORECAST_STDEV , ..) /// (see \ref #FORECAST_RETVAL_FUNC). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the calculated forecast value. ); /*! * \brief Returns the fitted values (i.e. mean, volatility and residuals). * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARMA_PARAM(), NDK_ARMA_VALIDATE(), NDK_ARMA_GOF(), NDK_ARMA_RESID(), NDK_ARMA_GOF() */ int __stdcall NDK_ARMA_FITTED( double* pData, ///< [inout] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). FIT_RETVAL_FUNC retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC). ); /*! * \brief Examines the model's parameters for stability constraints (e.g. stationarity, invertibility, causality, etc.). * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_TRUE model is stable * \retval #NDK_FALSE model is instable * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARMA_PARAM(), NDK_ARMA_VALIDATE(), NDK_ARMA_GOF(), NDK_ARMA_RESID(), NDK_ARMA_GOF() */ int __stdcall NDK_ARMA_VALIDATE(double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q ///< [in] is the number of elements in thetas (order of MA component). ); /*! * \brief Returns the simulated values. * * \note 1. ARMA_SIM returns an array of one simulation path starting from the end of the input data. * \note 2. The input data argument (i.e. latest observations) is optional. If omitted, an array of zeroes is assumed. * \note 3. The time series is homogeneous or equally spaced. * \note 4. The time series may include missing values (e.g. NaN) at either end. * \note 5. The long-run mean can take any value or be omitted, in which case a zero value is assumed. * \note 6. The residuals/innovations standard deviation (sigma) must be greater than zero. * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARMA_PARAM(), NDK_ARMA_VALIDATE(), NDK_ARMA_GOF(), NDK_ARMA_RESID(), NDK_ARMA_GOF() */ int __stdcall NDK_ARMA_SIM(double mean, ///< [in] is the ARMA model long-run mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). double* pData, ///< [in] are the values of the latest (most recent) observations. size_t nSize, ///< [in] is the number elements in pData. UINT nSeed, ///< [in] is an unsigned integer to initialize the psuedorandom number generator. double* retArray, ///< [out] is the output array to hold nSteps future simulations. size_t nSteps ///< [in] is the number of future steps to simulate for. ); ///@} /// \name ARIMA /// ARIMA model functions /// @{ /*! * \brief Examines the model's parameters for stability constraints (e.g. stationarity, invertibility, causality, etc.). * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The integration order argument (d) must be a positive integer. * \note 3. The time series may include missing values (e.g. NaN) at either end. * \note 4. The long-run mean can take any value or may be omitted, in which case a zero value is assumed. * \note 5. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARIMA_GOF(), NDK_ARIMA_PARAM(), NDK_ARIMA_FORE(), NDK_ARIMA_FITTED(), NDK_ARIMA_SIM() */ int __stdcall NDK_ARIMA_VALIDATE( double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the integration order. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q ///< [in] is the number of elements in thetas (order of MA component). ); /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit functions of the ARIMA model. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARIMA_VALIDATE(), NDK_ARIMA_PARAM(), NDK_ARIMA_FORE(), NDK_ARIMA_FITTED(), NDK_ARIMA_SIM() */ int __stdcall NDK_ARIMA_GOF( double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the model's integration order. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). GOODNESS_OF_FIT_FUNC retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC). double* retVal ///< [out] is the calculated GOF return value. ); /*! * \brief Returns the quick guess, optimal (calibrated) or std. errors of the values of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The integration order argument (d) must be a positive integer. * \note 4. The long-run mean can take any value or may be omitted, in which case a zero value is assumed. * \note 5. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARIMA_VALIDATE(), NDK_ARIMA_GOF(), NDK_ARIMA_FORE(), NDK_ARIMA_FITTED(), NDK_ARIMA_SIM() */ int __stdcall NDK_ARIMA_PARAM( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* mean, ///< [inout] is the ARMA model mean (i.e. mu). double* sigma, ///< [inout] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the model's integration order. double* phis, ///< [inout] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [inout] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). MODEL_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC). size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Calculates the out-of-sample simulated values. * * \note 1. The input data argument (i.e. latest observations) is optional. If omitted, an array of zeroes is assumed. * \note 2. The time series is homogeneous or equally spaced. * \note 3. The time series may include missing values (e.g. NaN) at either end. * \note 4. The input data argument (i.e. latest observations) is optional. If omitted, an array of zeroes is assumed. * \note 5. The residuals/innovations standard deviation (sigma) must be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARIMA_VALIDATE(), NDK_ARIMA_GOF(), NDK_ARIMA_FORE(), NDK_ARIMA_FITTED(), NDK_ARIMA_PARAM() */ int __stdcall NDK_ARIMA_SIM( double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the model's integration order. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. UINT nSeed, ///< [in] is an unsigned integer for setting up the random number generators. double* retVal, ///< [out] is the calculated simulation value. size_t nSteps ///< [in] is the number of future steps to simulate for. ); /*! * \brief Calculates the out-of-sample conditional forecast (i.e. mean, error, and confidence interval). * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The integration order argument (d) must be a positive integer. * \note 4. The long-run mean can take any value or may be omitted, in which case a zero value is assumed. * \note 5. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARIMA_VALIDATE(), NDK_ARIMA_GOF(), NDK_ARIMA_SIM(), NDK_ARIMA_FITTED(), NDK_ARIMA_PARAM() */ int __stdcall NDK_ARIMA_FORE( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the model's integration order. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). size_t nStep, ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). FORECAST_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned (see \ref #FORECAST_RETVAL_FUNC). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the calculated forecast value. ); /*! * \brief Returns the in-sample model fitted values of the conditional mean, volatility or residuals. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The integration order argument (d) must be a positive integer. * \note 4. The long-run mean can take any value or may be omitted, in which case a zero value is assumed. * \note 5. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_ARIMA_VALIDATE(), NDK_ARIMA_GOF(), NDK_ARIMA_SIM(), NDK_ARIMA_FORE(), NDK_ARIMA_PARAM() */ int __stdcall NDK_ARIMA_FITTED( double* pData, ///< [inout] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the ARMA model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the model's integration order. double* phis, ///< [in] are the parameters of the AR(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in phis (order of AR component). double* thetas, ///< [in] are the parameters of the MA(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in thetas (order of MA component). FIT_RETVAL_FUNC retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC). ); ///@} /// \name FARIMA /// Fractional ARIMA model functions /// @{ /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit function of the FARIMA model. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_RESID(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_FARIMA_GOF( double* pData, size_t nSize, double mean, double sigma, double nIntegral, double* phis, size_t p, double* thetas, size_t q, WORD retType, double* retVal); /*! * \brief Returns the standardized residuals of a given FARIMA model * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_FARIMA_RESID( double* pData/*IN-OUT*/, size_t nSize, double mean, double sigma, double nIntegral, double* phis, size_t p, double* thetas, size_t q, WORD retType); /*! * \brief Returns the initial (non-optimal), optimal or standard errors of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_FARIMA_PARAM( double* pData, size_t nSize, double* mean, double* sigma, double nIntegral, double* phis, size_t p, double* thetas, size_t q, WORD retType, size_t maxIter); /*! * \brief Returns a simulated data series the underlying FARIMA process. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_FARIMA_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_FARIMA_SIM( double* pData, size_t nSize, double mean, double sigma, double nIntegral, double* phis, size_t p, double* thetas, size_t q, size_t nStep , size_t nSeed, double* retVal); /*! * \brief Calculates the out-of-sample forecast statistics. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_FARIMA_GOF(), NDK_FARIMA_RESID(), NDK_FARIMA_PARAM(), NDK_FARIMA_FITTED(), NDK_FARIMA_VALIDATE() */ int __stdcall NDK_FARIMA_FORE( double* pData, size_t nSize, double mean, double sigma, double nIntegral, double* phis, size_t p, double* thetas, size_t q, size_t nStep , WORD retType, double* retVal); /*! * \brief Returns an array of cells for the fitted values (i.e. mean, volatility and residuals) * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_FARIMA_GOF(), NDK_FARIMA_RESID(), NDK_FARIMA_PARAM(), NDK_FARIMA_FORE(), NDK_FARIMA_VALIDATE() */ int __stdcall NDK_FARIMA_FITTED( double* pData, size_t nSize, double mean, double sigma, double nIntegral, double* phis, size_t p, double* thetas, size_t q, WORD retType); ///@} /// \name SARIMA /// Seasonal ARIMA model functions /// @{ /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit function of the SARIMA model. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 4. The maximum likelihood estimation (MLE) is a statistical method for fitting a model to the data and provides estimates for the model's parameters. * \note 5. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 6. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed to be zero. * \note 7. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed to be zero. * \note 8. The season length - s - is optional and can be omitted, in which case s is assumed to be zero (i.e. plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_RESID(), NDK_SARIMA_PARAM(), NDK_SARIMA_FORE(), NDK_SARIMA_FITTED(), NDK_SARIMA_VALIDATE() */ int __stdcall NDK_SARIMA_GOF( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. GOODNESS_OF_FIT_FUNC retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC). double* retVal ///< [out] is the calculated goodness of fit value. ); /*! * \brief Returns the quick guess, optimal (calibrated) or std. errors of the values of model's parameters. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed to be zero. * \note 6. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed to be zero. * \note 7. The season length - s - is optional and can be omitted, in which case s is assumed to be zero (i.e. plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_FORE(), NDK_SARIMA_FITTED(), NDK_SARIMA_VALIDATE() */ int __stdcall NDK_SARIMA_PARAM( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* mean, ///< [inout] is the mean of the ARMA process. double* sigma, ///< [inout] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [inout] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [inout] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [inout] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [inout] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. MODEL_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC). size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Returns the initial (non-optimal), optimal or standard errors of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. SARIMA_SIM returns an array of one simulation path starting from the end of the input data. * \note 3. The time series may include missing values (e.g. NaN) at either end. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The input data argument (i.e. latest observations) is optional. If omitted, an array of zeroes is assumed. * \note 6. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 7. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed to be zero. * \note 8. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed to be zero. * \note 9. The season length - s - is optional and can be omitted, in which case s is assumed to be zero (i.e. Plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_FORE(), NDK_SARIMA_FITTED(), NDK_SARIMA_VALIDATE() */ int __stdcall NDK_SARIMA_SIM( double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. size_t nSeed, ///< [in] is an unsigned integer for setting up the random number generators. double* retVal, ///< [out] is the simulated value. size_t nStep ///< [in] is the simulation time/horizon (expressed in terms of steps beyond end of the time series). ); /*! * \brief Calculates the out-of-sample conditional forecast (i.e. mean, error, and confidence interval). * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed to be zero. * \note 6. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed to be zero. * \note 7. The season length - s - is optional and can be omitted, in which case s is assumed to be zero (i.e. plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_PARAM(), NDK_SARIMA_FITTED(), NDK_SARIMA_VALIDATE() */ int __stdcall NDK_SARIMA_FORE(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. size_t nStep, ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). FORECAST_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned (see \ref #FORECAST_RETVAL_FUNC). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the calculated forecast value. ); /*! * \brief Returns the in-sample model fitted values of the conditional mean, volatility or residuals. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed to be zero. * \note 6. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed to be zero. * \note 7. The season length - s - is optional and can be omitted, in which case s is assumed to be zero (i.e. plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_PARAM(), NDK_SARIMA_FORE(), NDK_SARIMA_VALIDATE() */ int __stdcall NDK_SARIMA_FITTED(double* pData, ///< [inout] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. FIT_RETVAL_FUNC retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC). ); /*! * \brief Examines the model's parameters for stability constraints (e.g. stationarity, invertibility, causality, etc.). * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 4. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 5. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed to be zero. * \note 6. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed to be zero. * \note 7. The season length - s - is optional and can be omitted, in which case s is assumed to be zero (i.e. plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_PARAM(), NDK_SARIMA_FORE(), NDK_SARIMA_FITTED() */ int __stdcall NDK_SARIMA_VALIDATE(double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ ///< [in] is the order of the seasonal MA component. ); ///@} /// \name AirLine ///AirLine model functions /// @{ /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit functions of the AirLine model. * * \note 1. The Airline model is a special case of multiplicative seasonal ARIMA model, and it assumes independent and normally distributed residuals with constant variance. * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_RESID(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_AIRLINE_GOF(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. \f$\mu\f$). double sigma, ///< [in] is the standard deviation (\f$\sigma\f$) of the model's residuals/innovations. WORD S, ///< [in] is the length of seasonality (expressed in terms of lags, where s > 1). double theta, ///< [in] is the coefficient of first-lagged innovation (\f$\theta\f$)(see model description). double theta2, ///< [in] is the coefficient of s-lagged innovation (\f$\Theta\f$) (see model description). GOODNESS_OF_FIT_FUNC retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC). double* retVal ///< [out] is the calculated value of the goodness of fit. ); /*! * \brief Returns an array of cells for the standardized residuals of a given AirLine model. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \deprecated this function is being replaced by NDK_AIRLINE_FITTED() * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_AIRLINE_RESID( double* pData, ///< [inout] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD S, ///< [in] is the length of seasonality (expressed in terms of lags, where s > 1). double theta, ///< [in] is the coefficient of first-lagged innovation (see model description). double theta2, ///< [in] is the coefficient of s-lagged innovation (see model description). RESID_RETVAL_FUNC retType ///< [in] is a switch to select a residuals-type:raw or standardized. see \ref #RESID_RETVAL_FUNC. ); /*! * \brief Returns the initial/quick guess of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_AIRLINE_PARAM( double* pData, ///< [inout] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* mean, ///< [inout] is the model mean (i.e. mu). double* sigma, ///< [inout] is the standard deviation of the model's residuals/innovations. WORD S, ///< [in] is the length of seasonality (expressed in terms of lags, where s > 1). double* theta, ///< [inout] is the coefficient of first-lagged innovation (see model description). double* theta2, ///< [inout] is the coefficient of s-lagged innovation (see model description. MODEL_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC). size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Calculates the out-of-sample forecast statistics. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The season length must be greater than one. * \note 6. The input argument for the non-seasonal MA parameter - theta - is optional and can be omitted, in which case no non-seasonal MA component is included. * \note 7. The input argument for the seasonal MA parameter - theta2 - is optional and can be omitted, in which case no seasonal MA component is included. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_AIRLINE_FORE( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD S, ///< [in] is the length of seasonality (expressed in terms of lags, where s > 1). double theta, ///< [in] is the coefficient of first-lagged innovation (see model description). double theta2, ///< [in] is the coefficient of s-lagged innovation (see model description). size_t nStep, ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). FORECAST_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned (see \ref #FORECAST_RETVAL_FUNC). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the calculated forecast value. ); /*! * \brief Calculates the out-of-sample conditional mean forecast. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The input data argument (i.e. latest observations) is optional. If omitted, a value of zero is assumed. * \note 3. The time series may include missing values (e.g. NaN) at either end. * \note 4. The \f$\epsilon\f$ are normally distributed with mean zero and unit standard deviation. * \note 5. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 6. The value of the residuals/innovations standard deviation (sigma) must be positive. * \note 7. The season length must be greater than one. * \note 8. The input argument for the non-seasonal MA parameter - theta - is optional and can be omitted, in which case no non-seasonal MA component is included. * \note 9. The input argument for the seasonal MA parameter - theta2 - is optional and can be omitted, in which case no seasonal MA component is included. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_VALIDATE(), NDK_AIRLINE_GOF(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED(), NDK_AIRLINE_PARAM() */ int __stdcall NDK_AIRLINE_SIM( double* pData, ///< [in] is a univariate time series of the initial values (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD S, ///< [in] is the length of seasonality (expressed in terms of lags, where s > 1). double theta, ///< [in] is the coefficient of first-lagged innovation (see model description). double theta2, ///< [in] is the coefficient of s-lagged innovation (see model description). UINT nSeed, ///< [in] is an unsigned integer for setting up the random number generators. double* retArray, ///< [out] is the calculated simulation value. size_t nSteps ///< [in] is the number of future steps to simulate for. ); /*! * \brief Returns the fitted values of the conditional mean. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run mean argument (mean) can take any value or be omitted, in which case a zero value is assumed. * \note 4. The season length must be greater than one. * \note 5. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 6. The input argument for the non-seasonal MA parameter - theta - is optional and can be omitted, in which case no non-seasonal MA component is included. * \note 7. The input argument for the seasonal MA parameter - theta2 - is optional and can be omitted, in which case no seasonal MA component is included. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_VALIDATE() */ int __stdcall NDK_AIRLINE_FITTED( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD S, ///< [in] is the length of seasonality (expressed in terms of lags, where s > 1). double theta, ///< [in] is the coefficient of first-lagged innovation (see model description). double theta2, ///< [in] is the coefficient of s-lagged innovation (see model description). FIT_RETVAL_FUNC retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC). ); /*! * \brief Examines the model's parameters for stability constraints (e.g. stationarity, etc.). * * \note 1. The Airline model is a special case of multiplicative seasonal ARIMA model, and it assumes independent and normally distributed residuals with constant variance. * \note 2. The time series is homogeneous or equally spaced. * \note 3. The time series may include missing values (e.g. NaN) at either end. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED() */ int __stdcall NDK_AIRLINE_VALIDATE( double mean, ///< [in] is the model mean (i.e. mu). double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD S, ///< [in] is the length of seasonality (expressed in terms of lags, where s > 1). double theta, ///< [in] is the coefficient of first-lagged innovation (see model description). double theta2 ///< [in] is the coefficient of s-lagged innovation (see model description). ); ///@} /// \name X12-ARIMA /// Seasonal ajustments using X12-ARIMA API functions calls /// @{ /*! * \brief Initialize the filesystem environment on the local machine for the current user * * \note 1. This function creates a subfolder under the current user local profile for X12ARIMA models, and copy all the scripts needed to run the x12a program. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_ENV_INIT(BOOL override ///< [in] is a boolean flag to wipe our existing files and copy new ones. ); /*! * \brief Finalize the X12A environment and release any resources allocated * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_ENV_CLEANUP(void); /*! * \brief Initialize the required files for the given scenario/model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_SCEN_INIT(LPCTSTR szScenarioName, ///< [in] is the scenario name, must be unique LPVOID X12Options ///< [in] (optional) is an instance of #X12ARIMA_OPTIONS structure with all X12 model options. ); /*! * \brief Finalize the given scenario/model and free allocated resources * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_SCEN_CLEAUP(LPCTSTR szScenarioName /*!< [in] is the scenario name or the model unique identifier */); /*! * \brief Write the given data into an X12a formatted data file * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_DATA_FILE( LPCTSTR szScenarioName, double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t nLen, ///< [in] is the number of observations in X BOOL monthly, ///< [in] is a boolean flag for whether the data is monthly/quartelry sampled. LONG startDate, ///< [in] is the serial date number of the 1st observation in the series WORD reserved ///< [in] is a reserved argument for future releases. must be set to 1 ); /*! * \brief Create or updates the x12a specification file using the options selected * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_SPC_FILE(LPCTSTR szScenarioName, LPVOID X12Options); /*! * \brief Run a batch file in x12a environment * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_RUN_BATCH(LPCTSTR szScenarioName, LPCTSTR szBatchFile, LPWORD status); /*! * \brief Run a x12a program for the given model or scenrio * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_RUN_SCENARIO(LPCTSTR szScenarioName, LPWORD status); /*! * \brief Read the status file generated by x12a program * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_RUN_STAT(LPCTSTR szScenarioName, LPWORD status, LPTSTR szMsg, size_t* nLen); /*! * \brief Return the full path of the output file generated by x12a program * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_OUT_FILE(LPCTSTR szScenarioName, ///< [in] is the scenaio.model name WORD retType, ///< [in] is a switch to designate the desired specific output file. /// 0. The X12 specification file (*.spc) /// 1. The X12 log file /// 2. The output file /// 3. The error file LPTSTR szOutFile, ///< [out] is a buffer to hold the return full path size_t* nLen, ///< [inout] is the length of the szOutFile. Upon return, this argument stores the actual number of bytes used. BOOL OpenFileFlag ///< [in] is a switch to instruct the functiona whether it should open the file using system default editor (e.g. notepad) ); /*! * \brief Read the output time series (e.g. seasonal adjusted data) generated by x12a program * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X12_OUT_SERIES(LPCTSTR szScenarioName, ///< [in] is the given scenario/model WORD nComponent, ///< [in] is the desired output of the X12a output /// 1. Final seasonal factors (d11) /// 2. final trend-cycle (d12) /// 3. final irregular component (d13) /// 4. final seasonal factors (d10) /// 5. combined holiday and trading day factors (d18) /// 6. combined seasonal and trading day factors (d16) double* pData, ///< [out] is the output buffer to hold the data series size_t* nLen ///< [inout] is the original size of the output buffer. Upon return, nLen will have the actual number of data copied. ); /*! * \brief Read the output forecaste series generated by x12a program * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_SCEN_CLEAUP(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES() */ int __stdcall NDK_X12_FORE_SERIES( LPCTSTR szScenarioName, ///< [in] is the given X12-ARIMA scenario/model identifier size_t nStep, ///< [in] is the forecast horizon WORD retType, ///< [in] is the switch to designate desired output /// 1. Mean /// 2. Lower limit value of the conficent interval /// 3. Upper limit value of the confidence interval double* pData ///< [out] is the forecast output value ); ///@} /// \name X13ARIMA-SEATS /// X13ARIMA-SEATS model functions /// @{ /*! * \brief Initialize the filesystem environment on the local machine for the current user * * \note 1. This function creates a subfolder under the current user local profile for X13ARIMA models, and copy all the scripts needed to run the x13as program. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X13_ENV_CLEANUP() */ int __stdcall NDK_X13_ENV_INIT(BOOL override ///< [in] is a boolean flag to wipe our existing files and copy new ones. ); /*! * \brief Finalize the X13AS environment and release any resources allocated * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X13_ENV_INIT() */ int __stdcall NDK_X13_ENV_CLEANUP(void); /*! * \brief Initialize the required files for the given scenario/model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X13_ENV_INIT(), NDK_X13_ENV_CLEANUP(), NDK_X13_SCEN_CLEAUP() */ int __stdcall NDK_X13_SCEN_INIT(LPCTSTR szScenarioName, ///< [in] is the scenario name, must be unique LPVOID X13Options ///< [in] (optional) is an instance of #X13ARIMA_OPTIONS structure with all X13 model options. ); /*! * \brief reconstruct the different (input/intermediate/output) files * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X13_ENV_INIT(), NDK_X13_ENV_CLEANUP(), NDK_X13_SCEN_CLEAUP() */ int __stdcall NDK_X13_SCEN_REFRESH(LPCTSTR szScenarioName); /*! * \brief Finalize the given scenario/model and free allocated resources * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X12_ENV_INIT(), NDK_X12_ENV_CLEANUP(), NDK_X12_SCEN_INIT(), NDK_X12_DATA_FILE(), NDK_X12_SPC_FILE(), NDK_X12_RUN_BATCH(), NDK_X12_RUN_SCENARIO(), NDK_X12_RUN_STAT(), NDK_X12_OUT_FILE(), NDK_X12_OUT_SERIES(), NDK_X12_FORE_SERIES() */ int __stdcall NDK_X13_SCEN_CLEAUP(LPCTSTR szScenarioName /*!< [in] is the scenario name or the model unique identifier */ ); /*! * \brief Write the given data into an X13as formatted data file * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X13_ENV_INIT(), NDK_X13_ENV_CLEANUP(), NDK_X13_SCEN_INIT(), NDK_X13_SCEN_CLEAUP() */ int __stdcall NDK_X13_DATA_FILE(LPCTSTR szScenarioName, LPCTSTR szOutputFile, double* X, ///< [in] is the univariate time series data (a one dimensional array). size_t nLen, ///< [in] is the number of observations in X BOOL monthly, ///< [in] is a boolean flag for whether the data is monthly/quartelry sampled. LONG startDate, ///< [in] is the serial date number of the 1st observation in the series WORD reserved ///< [in] is a reserved argument for future releases. must be set to 1 ); /*! * \brief Write the actual holidays dates into an genhol formatted data file * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X13_ENV_INIT(), NDK_X13_ENV_CLEANUP(), NDK_X13_SCEN_INIT(), NDK_X13_SCEN_CLEAUP() */ int __stdcall NDK_X13_HOLIDAY_FILE( LPCTSTR szScenarioName, ///< [in] is the scenario name or the model unique identifier LPCTSTR szHoliday, ///< [in] is the holiday code (unique identifier) to get dates for. LONG startDate, ///< [in] is the serial date number of the beginning of the search interval LONG endDate ///< [in] is the serial date number of the end of the search interval ); /*! * \brief Write the (user) holidays dates into an genhol formatted data file * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_X13_HOLIDAY_FILE(), NDK_X13_SCEN_INIT(), NDK_X13_SCEN_CLEAUP() */ int __stdcall NDK_X13_USER_EVENT_FILE(LPCTSTR szScenarioName, ///< [in] is the scenario name or the model unique identifier LPCTSTR szName, ///< [in] is the user-defined name (unique identifier) of the event. PLONG holidays, ///< [in] is an array of dates serial numbers. size_t nLen ///< [in] is the number of elements in the [holidays] array. ); int __stdcall NDK_X13_ADD_EVENT_FACTOR( LPCTSTR szScenarioName, ///< [in] is the scenario name or the model unique identifier LPCTSTR szName, ///< [in] is the user-defined name (unique identifier) of the event. PLONG holidays, ///< [in] (optional, uer-defined only) is an array of dates serial numbers. size_t nLen, ///< [in] (optional, uer-defined only) is the number of elements in the [holidays] array. double begbefore, ///< [in] Denotes the position relative to the holiday of the beginning of the window used to generate the before-holiday regressor. This value should be negative, and less than or equal to the value for the endbefore argument. The minimum value that can be specified is -42. double endbefore, ///< [in] Denotes the position relative to the holiday of the end of the window used to generate the before-holiday regressor. This value should be negative. double begAfter, ///< [in] Denotes the position relative to the holiday of the beginning of the window used to generate the after-holiday regressor. Since this effect occurs after the holiday, the value should be non-negative. double endAfter, ///< [in] Denotes the position relative to the holiday of the end of the window used to generate the after-holiday regressor. This value should be positive, and greater than or equal to the value for the begafter argument. The maximum value that can be specified is 49 double zeroBefore, ///< [in] Defines the year before which all values in the regressor are set to be zero. If this argument is set, first < zerobefore <= last, and if zeroafter is set, then zerobefore < zeroafter. double zeroAfter, ///< [in] Defines the year on or after which all values in the regressor are set to be zero. If this argument is set, first < zeroafter <= last, and if zeroafter is set, then zerobefore < zeroafter. WORD wCenter ///< [in] Specifies the removal of the (sample) mean or the seasonal means from the user-defined regression variables. ///< 0 = None, 1=mean, 2=calendar (only with ratio type of data) ); int __stdcall NDK_X13_REGRESSORS_SETTING( LPCTSTR szScenarioName, ///< [in] is the scenario name or the model unique identifier double dwFirstYear, double dwLastYear, double dwFirstMeanYear, double dwLastMeanYear, DWORD dwPeriod, BOOL bRatio, double dwStockDay ); int __stdcall NDK_X13_RUN_GENHOL(LPCTSTR szScenarioName); int __stdcall NDK_X13_RUN_BATCH(LPCTSTR szScenarioName, LPCTSTR szBatchFile, LPWORD status); int __stdcall NDK_X13_SPC_SERIES_SETTING(LPCTSTR szScenarioName, LPCTSTR szSeriesName, double* pData, size_t nLen, BOOL stock, BOOL monthly, LONG startDate, WORD fileType); int __stdcall NDK_X13_SPC_TRANSFORM_SETTING(LPCTSTR szScenarioName, X13TRANSFORM_METHOD zTransform, double zPower); int __stdcall NDK_X13_SPC_PRIOR_ADJUST_SETTING( LPCTSTR szScenarioName, BOOL lom, BOOL loq, BOOL leapYear, double* pTempData, size_t nTempLen, LONG zTempStartDate, X13PRIORADJUST_TYPE nTempDataType, double* pPermData, size_t nPermLen, LONG zPermStartDate, X13PRIORADJUST_TYPE nPermDataType); int __stdcall NDK_X13_SPC_X11_SETTING(LPCTSTR szScenarioName, BOOL enable, X11_MODE_TYPE mode, X11_SEASONALMA_TYPE seasonalma, int trendma, double sigmaLL, double sigmaUL); int __stdcall NDK_X13_SPC_SEATS_SETTING(LPCTSTR szScenarioName, BOOL enable, BOOL hpCycle, BOOL infiniteFilter, BOOL bAdmissableCompositionApprox, BOOL bAcceptSeasonStationary, double maxLBQStat); int __stdcall NDK_X13_WRITE_SPC_FILE(LPCTSTR szScenarioName); int __stdcall NDK_X13_RUN_SPC_FILE(LPCTSTR szScenarioName); int __stdcall NDK_X13AS_OUT_FILE(LPCTSTR szScenarioName, WORD retType, LPTSTR szOutFile, size_t* nLen, BOOL OpenFileFlag); int __stdcall NDK_X13AS_OUT_SERIES(LPCTSTR szScenarioName, LPCTSTR szComponent, double* pData, size_t* nLen); ///@} /// \name SARIMAX /// Seasonal ARIMA-X model functions /// @{ /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit functions of the SARIMA-X model. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 4. The maximum likelihood estimation (MLE) is a statistical method for fitting a model to the data and provides estimates for the model's parameters. * \note 5. The intercept or the regression constant term input argument is optional. If omitted, a zero value is assumed. * \note 6. The long-run mean argumen (mean) of the differenced regression residuals can take any value. If omitted, a zero value is assumed. * \note 7. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed zero. * \note 8. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed zero. * \note 9. The season length - s - is optional and can be omitted, in which case s is assumed zero (i.e. Plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMAX_FITTED(), NDK_SARIMAX_PARAM(), NDK_SARIMAX_FORE(), NDK_SARIMAX_FORE(), NDK_SARIMAX_VALIDATE() */ int __stdcall NDK_SARIMAX_GOF(double* pData, ///< [in] is the response univariate time series data (a one dimensional array). double** pFactors, ///< [in] is the exogneous factors time series data (each column is a separate factor, and each row is an observation). size_t nSize, ///< [in] is the number of observations. size_t nFactors, ///< [in] is the number of exognous factors. double* fBetas, ///< [in] is the weights or loading of the exogneous factors. double mean, ///< [in] is the ARIMA/SARIMA model's long-run mean/trend (i.e. mu). If missing (i.e. NaN), then it is assumed zero. double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. GOODNESS_OF_FIT_FUNC retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC). double* retVal ///< [out] is the calculated goodness of fit value. ); /*! * \brief Examines the model's parameters for stability constraints (e.g. causality, invertability, stationary, etc.). * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The intercept or the regression constant term input argument is optional. If omitted, a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed zero. * \note 6. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed zero. * \note 7. The season length - s - is optional and can be omitted, in which case s is assumed zero (i.e. Plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_PARAM(), NDK_SARIMA_FORE(), NDK_SARIMA_FITTED() */ int __stdcall NDK_SARIMAX_VALIDATE(double mean, ///< [in] is the model mean (i.e. mu) for the differenced series. double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ ///< [in] is the order of the seasonal MA component. ); /*! * \brief Returns the in-sample model fitted values of the conditional mean, volatility or residuals. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The intercept or the regression constant term input argument is optional. If omitted, a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The long-run mean argument (mean) of the differenced regression residuals can take any value. If omitted, a zero value is assumed. * \note 6. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed zero. * \note 7. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed zero. * \note 8. The season length - s - is optional and can be omitted, in which case s is assumed zero (i.e. Plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMAX_GOF(), NDK_SARIMAX_RESID(), NDK_SARIMAX_PARAM(), NDK_SARIMAX_FORE(), NDK_SARIMAX_VALIDATE() */ int __stdcall NDK_SARIMAX_FITTED( double* pData, ///< [inout] is the univariate time series data (a one dimensional array). double** pFactors, ///< [in] is the exogneous factors time series data (each column is a separate factor, and each row is an observation). size_t nSize, ///< [in] is the number of observations. size_t nFactors, ///< [in] is the number of exognous factors. double* fBetas, ///< [in] is the weights or loading of the exogneous factors. double mean, ///< [in] is the ARIMA/SARIMA model's long-run mean/trend (i.e. mu). If missing (i.e. NaN), then it is assumed zero. double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. FIT_RETVAL_FUNC retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC). ); /*! * \brief Returns the quick guess, optimal (calibrated) or std. errors of the values of model's parameters. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The intercept or the regression constant term input argument is optional. If omitted, a zero value is assumed. * \note 4. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 5. The long-run mean argument (mean) of the differenced regression residuals can take any value. If omitted, a zero value is assumed. * \note 6. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed zero. * \note 7. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed zero. * \note 8. The season length - s - is optional and can be omitted, in which case s is assumed zero (i.e. Plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMAX_GOF(), NDK_SARIMAX_RESID(), NDK_SARIMAX_FORE(), NDK_SARIMAX_FITTED(), NDK_SARIMAX_VALIDATE() */ int __stdcall NDK_SARIMAX_PARAM( double* pData, ///< [inout] is the univariate time series data (a one dimensional array). double** pFactors, ///< [in] is the exogneous factors time series data (each column is a separate factor, and each row is an observation). size_t nSize, ///< [in] is the number of observations. size_t nFactors, ///< [in] is the number of exognous factors. double* fBetas, ///< [inout] is the weights or loading of the exogneous factors. double* mean, ///< [inout] is the mean of the differenced time series process. double* sigma, ///< [inout] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [inout] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [inout] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [inout] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [inout] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. MODEL_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC). size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Calculates the out-of-sample forecast statistics. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 4. The exogneous factors input are expected to have at least n-more observations than the reponse variable. * \note 5. The intercept or the regression constant term input argument is optional. If omitted, a zero value is assumed. * \note 6. The long-run mean argument (mean) of the differenced regression residuals can take any value. If omitted, a zero value is assumed. * \note 7. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed zero. * \note 8. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed zero. * \note 9. The season length - s - is optional and can be omitted, in which case s is assumed zero (i.e. Plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_PARAM(), NDK_SARIMA_FITTED(), NDK_SARIMA_VALIDATE() */ int __stdcall NDK_SARIMAX_FORE(double* pData, ///< [in] is the univariate time series data (a one dimensional array). double** pFactors, ///< [in] is the exogneous factors time series data (each column is a separate factor, and each row is an observation). size_t nSize, ///< [in] is the number of observations. size_t nFactors, ///< [in] is the number of exognous factors. double* fBetas, ///< [inout] is the weights or loading of the exogneous factors. double mean, ///< [inout] is the mean of the ARMA process. double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. size_t nStep, ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). FORECAST_RETVAL_FUNC retType, ///< [in] is a switch to select the type of value returned (see \ref #FORECAST_RETVAL_FUNC). double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the calculated forecast value. ); /*! * \brief Calculates the out-of-sample simulated values. * * \note 1. The time series is homogeneous or equally spaced. * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The residuals/innovations standard deviation (i.e.\f$\sigma\f$) should be greater than zero. * \note 4. The intercept or the regression constant term input argument is optional. If omitted, a zero value is assumed. * \note 5. The exogenous factors input are expected to have at least n-more observations than the reponse variable. * \note 6. The long-run mean argument (mean) of the differenced regression residuals can take any value. If omitted, a zero value is assumed. * \note 7. The non-seasonal integration order - d - is optional and can be omitted, in which case d is assumed zero. * \note 8. The seasonal integration order - sD - is optional and can be omitted, in which case sD is assumed zero. * \note 9. The season length - s - is optional and can be omitted, in which case s is assumed zero (i.e. Plain ARIMA). * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_SARIMA_GOF(), NDK_SARIMA_RESID(), NDK_SARIMA_FORE(), NDK_SARIMA_FITTED(), NDK_SARIMA_VALIDATE() */ int __stdcall NDK_SARIMAX_SIM(double* fBetas, ///< [inout] is the weights or loading of the exogneous factors. size_t nFactors, ///< [in] is the number of exognous factors. double mean, ///< [inout] is the mean of the ARMA process. double sigma, ///< [in] is the standard deviation of the model's residuals/innovations. WORD nIntegral, ///< [in] is the non-seasonal difference order. double* phis, ///< [in] are the coefficients's values of the non-seasonal AR component. size_t p, ///< [in] is the order of the non-seasonal AR component. double* thetas, ///< [in] are the coefficients's values of the non-seasonal MA component. size_t q, ///< [in] is the order of the non-seasonal MA component. WORD nSIntegral, ///< [in] is the seasonal difference. WORD nSPeriod, ///< [in] is the number of observations per one period (e.g. 12=Annual, 4=Quarter). double* sPhis, ///< [in] are the coefficients's values of the seasonal AR component. size_t sP, ///< [in] is the order of the seasonal AR component. double* sThetas, ///< [in] are the coefficients's values of the seasonal MA component. size_t sQ, ///< [in] is the order of the seasonal MA component. double* pData, ///< [in] is the univariate time series data (a one dimensional array). double** pFactors, ///< [in] is the past exogneous factors time series data (each column is a separate factor, and each row is an observation). size_t nSize, ///< [in] is the number of observations in X. UINT nSeed, ///< [in] is an unsigned integer for setting up the random number generators. size_t nStep, ///< [in] is the simulation time/horizon (expressed in terms of steps beyond end of the time series). double* retVal ///< [out] is the simulated value. ); ///@} /// \name GARCH ///GARCH Functions /// @{ /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit function of the GARCH model. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCH_GOF(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC) double* retVal ///< [out] is the calculated goodness of fit value. ); /*! * \brief Returns an array of cells for the standardized residuals of a given GARCH model * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \deprecated this function is being replaced by NDK_GARCH_FITTED() * \sa NDK_GARCH_GOF(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCH_RESID(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType ///< [in] is a switch to select a residuals-type:raw or standardized. see \ref #RESID_RETVAL_FUNC ); /*! * \brief Returns an array of cells for the initial (non-optimal), optimal or standard errors of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCH_PARAM(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* mu, ///< [inout] is the GARCH model conditional mean (i.e. mu). double* Alphas, ///< [inout] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array double* Betas, ///< [inout] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double* nu, ///< [inout] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC) size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Returns a simulated data series the underlying GARCH process. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCH_SIM(double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. double* pData, ///< [in] is the univariate time series of the latest observations (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* sigmas, ///< [in] is the univariate time series of the latest observations (a one dimensional array of cells (e.g. rows or columns)) of the last q realized volatilities. size_t nSigmaSize, ///< [in] is the number of elements in sigmas. Only the latest q observations are used. UINT nSeed, ///< [in] is an unsigned integer for setting up the random number generators double* retArray, ///< [out] is the calculated simulation value size_t nSteps ///< [in] is the number of future steps to simulate for. ); /*! * \brief Calculates the out-of-sample forecast statistics. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCH_FORE( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* sigmas, ///< [in] is the univariate time series data (a one dimensional array of cells (e.g. rows or columns)) of the last q realized volatilities. size_t nSigmaSize, ///< [in] is the number of elements in sigmas. Only the latest q observations are used. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian or Normal Distribution /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. size_t nStep , ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). WORD retType, ///< [in] is a switch to select the type of value returned /// 1. Mean forecast /// 2. Forecast Error /// 3. Volatility term structure /// 4. Confidence interval lower limit /// 5. Confidence interval upper limit /// (see \ref #FORECAST_RETVAL_FUNC) double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the calculated forecast value ); /*! * \brief Returns an array of cells for the fitted values (i.e. mean, volatility and residuals) * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCH_FITTED( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC) ); /*! * \brief Calculates the long-run average volatility for the given GARCH model * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run variance is not affected by our choice of shock/innovation distribution * \note 4. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCH_LRVAR( double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. double* retVal ///< [out] is the calculated long run value ); /*! * \brief Examines the model's parameters for stability constraints (e.g. variance stationary, positive variance, etc.). * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_TRUE Model is stable (i.e. variance process is stationary and yield positive values) * \retval #NDK_FALSE Model is unstable. * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED() */ int __stdcall NDK_GARCH_VALIDATE(double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. ); ///@} /// \name EGARCH ///EGARCH Functions /// @{ /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit function of the GARCH model. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_EGARCH_RESID(), NDK_EGARCH_PARAM(), NDK_EGARCH_FORE(), NDK_EGARCH_FITTED(), NDK_EGARCH_VALIDATE() */ int __stdcall NDK_EGARCH_GOF( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the EGARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Gammas, ///< [in] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC) double* retVal ///< [out] is the calculated goodness of fit value. ); /*! * \brief Returns an array of cells for the standardized residuals of a given GARCH model * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \deprecated this function is being replaced by NDK_EGARCH_FITTED() * \sa NDK_GARCH_GOF(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_EGARCH_RESID( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the EGARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Gammas, ///< [in] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType ///< [in] is a switch to select a residuals-type:raw or standardized. see \ref #RESID_RETVAL_FUNC ); /*! * \brief Returns an array of cells for the initial (non-optimal), optimal or standard errors of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_EGARCH_GOF(), NDK_EGARCH_RESID(), NDK_EGARCH_FORE(), NDK_EGARCH_FITTED(), NDK_EGARCH_VALIDATE() */ int __stdcall NDK_EGARCH_PARAM( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* mu, ///< [inout] is the EGARCH model conditional mean (i.e. mu). double* Alphas, ///< [inout] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array double* Gammas, ///< [inout] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). double* Betas, ///< [inout] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double* nu, ///< [inout] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC) size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Returns a simulated data series the underlying EGARCH process. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_EGARCH_RESID(), NDK_EGARCH_PARAM(), NDK_EGARCH_FORE(), NDK_EGARCH_FITTED(), NDK_EGARCH_VALIDATE() */ int __stdcall NDK_EGARCH_SIM( double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Gammas, ///< [in] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* sigmas, ///< [in] is the univariate time series data (a one dimensional array of cells (e.g. rows or columns)) of the last q realized volatilities. size_t nSigmaSize, ///< [in] is the number of elements in sigmas. Only the latest q observations are used. UINT nSeed, ///< [in] is an unsigned integer for setting up the random number generators double* retArray, ///< [out] is the calculated simulation value size_t nSteps ///< [in] is the number of future steps to simulate for. ); /*! * \brief Calculates the out-of-sample forecast statistics. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_EGARCH_GOF(), NDK_EGARCH_RESID(), NDK_EGARCH_PARAM(), NDK_EGARCH_FITTED(), NDK_EGARCH_VALIDATE() */ int __stdcall NDK_EGARCH_FORE(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* sigmas, ///< [in] is the univariate time series data (a one dimensional array of cells (e.g. rows or columns)) of the last q realized volatilities. size_t nSigmaSize, ///< [in] is the number of elements in sigmas. Only the latest q observations are used. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Gammas, ///< [inout] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. size_t nStep , ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). WORD retType, ///< [in] is a switch to select the type of value returned /// 1. Mean forecast /// 2. Forecast Error /// 3. Volatility term structure /// 4. Confidence interval lower limit /// 5. Confidence interval upper limit /// (see \ref #FORECAST_RETVAL_FUNC) double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the simulated value for the GARCH process. ); /*! * \brief Returns an array of cells for the fitted values (i.e. mean, volatility and residuals) * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_EGARCH_FITTED( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Gammas, ///< [in] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC) ); /*! * \brief Calculates the long-run average volatility for a given E-GARCH model. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The long-run variance is not affected by our choice of shock/innovation distribution * \note 4. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 5. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 6. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_EGARCH_GOF(), NDK_EGARCH_RESID(), NDK_EGARCH_PARAM(), NDK_EGARCH_FORE(), NDK_EGARCH_VALIDATE() */ int __stdcall NDK_EGARCH_LRVAR( double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Gammas, ///< [inout] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. double* retVal ///< [out] is the calculated Long run volatility. ); /*! * \brief Examines the model's parameters for stability constraints (e.g. stationary, positive variance, etc.). * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of gamma-coefficients must match the number of alpha-coefficients minus one. * \note 5. The number of parameters in the input argument - beta - determines the order of the GARCH component model. * * \return status code of the operation * \retval #NDK_TRUE Model is stable (i.e. variance process is stationary and yield positive values) * \retval #NDK_FALSE Model is unstable. * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_AIRLINE_GOF(), NDK_AIRLINE_RESID(), NDK_AIRLINE_PARAM(), NDK_AIRLINE_FORE(), NDK_AIRLINE_FITTED() */ int __stdcall NDK_EGARCH_VALIDATE( double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Gammas, ///< [inout] are the leverage parameters (starting with the lowest lag). size_t g, ///< [in] is the number of elements in Gammas. Must be equal to (p-1). const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. ); ///@} /// \name GARCH-M ///GARCH-M Functions /// @{ /*! * \brief Computes the log-likelihood ((LLF), Akaike Information Criterion (AIC) or other goodness of fit function of the GARCH model. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCHM_RESID(), NDK_GARCHM_PARAM(), NDK_GARCHM_FORE(), NDK_GARCHM_FITTED(), NDK_GARCHM_VALIDATE() */ int __stdcall NDK_GARCHM_GOF(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). double flambda, ///< [in] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType, ///< [in] is a switch to select a fitness measure ( see \ref #GOODNESS_OF_FIT_FUNC) double* retVal ///< [out] is the calculated goodness of fit value. ); /*! * \brief Returns an array of cells for the standardized residuals of a given GARCH model * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \deprecated this function is being replaced by NDK_GARCHM_FITTED() * \sa NDK_GARCHM_GOF(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCHM_RESID( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). double flambda, ///< [in] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType ///< [in] is a switch to select a residuals-type:raw or standardized. see \ref #RESID_RETVAL_FUNC ); /*! * \brief Returns an array of cells for the initial (non-optimal), optimal or standard errors of the model's parameters. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCHM_PARAM( double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* mu, ///< [inout] is the GARCH model conditional mean (i.e. mu). double* flambda, ///< [inout] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. double* Alphas, ///< [inout] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array double* Betas, ///< [inout] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double* nu, ///< [inout] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType, ///< [in] is a switch to select the type of value returned: 1= Quick Guess, 2=Calibrated, 3= Std. Errors ( see \ref #MODEL_RETVAL_FUNC) size_t maxIter ///< [in] is the maximum number of iterations used to calibrate the model. If missing or less than 100, the default maximum of 100 is assumed. ); /*! * \brief Returns a simulated data series the underlying GARCH process. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCHM_SIM( double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). double flambda, ///< [in] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* sigmas, ///< [in] is the univariate time series data (a one dimensional array of cells (e.g. rows or columns)) of the last q realized volatilities. size_t nSigmaSize, ///< [in] is the number of elements in sigmas. Only the latest q observations are used. UINT nSeed, ///< [in] is an unsigned integer for setting up the random number generators double* retArray, ///< [out] is the calculated simulation value size_t nSteps ///< [in] is the number of future steps to simulate for. ); /*! * \brief Calculates the out-of-sample forecast statistics. * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FITTED(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCHM_FORE(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double* sigmas, ///< [in] is the univariate time series data (a one dimensional array of cells (e.g. rows or columns)) of the last q realized volatilities. size_t nSigmaSize, ///< [in] is the number of elements in sigmas. Only the latest q observations are used. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). double flambda, ///< [in] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian or Normal Distribution /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. size_t nStep , ///< [in] is the forecast time/horizon (expressed in terms of steps beyond end of the time series). WORD retType, ///< [in] is a switch to select the type of value returned /// 1. Mean forecast /// 2. Forecast Error /// 3. Volatility term structure /// 4. Confidence interval lower limit /// 5. Confidence interval upper limit /// (see \ref #FORECAST_RETVAL_FUNC) double alpha, ///< [in] is the statistical significance level. If missing, a default of 5% is assumed. double* retVal ///< [out] is the calculated forecast value ); /*! * \brief Returns an array of cells for the fitted values (i.e. mean, volatility and residuals) * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCHM_GOF(), NDK_GARCHM_RESID(), NDK_GARCHM_PARAM(), NDK_GARCHM_FORE(), NDK_GARCHM_VALIDATE() */ int __stdcall NDK_GARCHM_FITTED(double* pData, ///< [in] is the univariate time series data (a one dimensional array). size_t nSize, ///< [in] is the number of observations in X. double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). double flambda, ///< [in] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. WORD retType ///< [in] is a switch to select a output type ( see \ref #FIT_RETVAL_FUNC) ); /*! * \brief Calculates the long-run average volatility for the given GARCH-M model * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCH_GOF(), NDK_GARCH_RESID(), NDK_GARCH_PARAM(), NDK_GARCH_FORE(), NDK_GARCH_VALIDATE() */ int __stdcall NDK_GARCHM_LRVAR( double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). double flambda, ///< [in] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu, ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. double* retVal ///< [out] is the calculated long run value ); /*! * \brief Examines the model's parameters for stability constraints (e.g. stationary, etc.). * * \note 1. The time series is homogeneous or equally spaced * \note 2. The time series may include missing values (e.g. NaN) at either end. * \note 3. The number of parameters in the input argument - alpha - determines the order of the ARCH component model. * \note 4. The number of parameters in the input argument - beta - determines the order of the GARCH component model * * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_GARCHM_GOF(), NDK_ARCHM_RESID(), NDK_ARCHM_PARAM(), NDK_ARCHM_FORE(), NDK_ARCHM_FITTED() */ int __stdcall NDK_GARCHM_VALIDATE(double mu, ///< [in] is the GARCH model conditional mean (i.e. mu). double flambda, ///< [in] is the volatility coefficient for the mean. In finance, lambda is referenced as the risk premium. const double* Alphas, ///< [in] are the parameters of the ARCH(p) component model (starting with the lowest lag). size_t p, ///< [in] is the number of elements in Alphas array const double* Betas, ///< [in] are the parameters of the GARCH(q) component model (starting with the lowest lag). size_t q, ///< [in] is the number of elements in Betas array WORD nInnovationType,///< [in] is the probability distribution function of the innovations/residuals (see #INNOVATION_TYPE) /// - INNOVATION_GAUSSIAN Gaussian Distribution (default) /// - INNOVATION_TDIST Student's T-Distribution, /// - INNOVATION_GED Generalized Error Distribution (GED) double nu ///< [in] is the shape factor (or degrees of freedom) of the innovations/residuals probability distribution function. ); ///@} /// \name Speactral Analysis /// @{ /*! * \brief Returns an array of cells for the convolution operator of two time series * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, NDK_LAG(), NDK_DIFF */ int __stdcall NDK_CONVOLUTION(double *X, ///< [in] is the univariate time series data (a one dimensional array). size_t N1, ///< [in] is the number of observations in X. double *Y, ///< [in] is the second univariate time series data (a one dimensional array) size_t N2, ///< [in] is the number of observations in Y. double* Z, ///< [out] is the convolution time series output size_t* W ///< [inout] is the maximum number of elements in Z. ); /*! * \brief Calculates the inverse discrete fast Fourier transformation, recovering the time series. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, NDK_LAG(), NDK_DIFF */ int __stdcall NDK_IDFT( double *amp, ///< [in] is an array of the amplitudes of the fourier transformation components. double *phase, ///< [in] is an array of the phase angle (radian) of the Fourier transformation components . size_t nSize, ///< [in] is the number of spectrum components (i.e. size of amp and phase). double* X, ///< [out] is the filtered (recovered) time series output size_t N ///< [in] is the original number of observations used to calculate the fourier transform. ); /*! * \brief Calculates the discrete fast Fourier transformation for amplitude and phase. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, NDK_LAG(), NDK_DIFF */ int __stdcall NDK_DFT(double *X, ///< [in] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. double* retAmp, ///< [out] is an array of the amplitudes of the fourier transformation components double* retPhase, ///< [out] is an array of the phase angle (radian) of the Fourier transformation components . size_t M ///< [in] is the number of spectrum components (i.e. size of amp and phase) ); /*! * \brief computes cyclical component of given time series using the Hodrick–Prescott filter. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_BaxterKingFilter(), NDK_DFT(), NDK_IDFT() */ int __stdcall NDK_HodrickPrescotFilter(double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). double lambda ///< [in] is the multiplier used to penalize the variation in the trend component. If missing, a default is used based on data frequency. ); /*! * \brief Computes trend and cyclical component of a macroeconomic time series using Baxter-King Fixed Length Symmetric Filter. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_HodrickPrescotFilter(), NDK_DFT(), NDK_IDFT() */ int __stdcall NDK_BaxterKingFilter( double *X, ///< [inout] is the univariate time series data (a one dimensional array). size_t N, ///< [in] is the number of observations in X. BOOL bAscending, ///< [in] is the time order in the data series (i.e. the first data point's corresponding date (earliest date=1 (default), latest date=0)). size_t freq_min, ///< [in] is the number of periods for the high pass filter (e.g. 6 for quarterly data, 18 for monthly data). size_t freq_max, ///< [in] is the number of periods for the low passfilter (e.g. 32 for quarterly data, 96 for montly data). size_t K, ///< [in] is the number of points(aka terms) to use in the approximate optimal filter. If missing, a default value of 12 is assumed BOOL drift, ///< [in] is a logical value: FALSE if no drift in time series (default), TRUE if drift in time series. BOOL unitroot, ///< [in] is a logical value: FALSE if no unit-root is in time series (default), TRUE if unit-root is in time series. WORD retTYpe ///< [in] is the integer enumeration for the filter output: (1= trend component (default), 2=cyclical component, 3=noise component) ); ///@} /*! * \name Portfolio Analysis * \brief * @{ */ /// \brief compute the portfolio equivalent returns /*! * \brief Calculates the portfolio equivalent return. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PORTFOLIO_VARIANCE(), NDK_PORTFOLIO_COVARIANCE() */ int __stdcall NDK_PORTFOLIO_RET(double* weights, size_t nAssets, double* returns, double* ret); /*! * \brief Calculates the overall portfolio variance (volatility squared). * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PORTFOLIO_RET(), NDK_PORTFOLIO_COVARIANCE() */ int __stdcall NDK_PORTFOLIO_VARIANCE(double* weights, size_t nAssets, double** covar, double* variance); /*! * \brief Calculates the covariance between two portfolios. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation is unsuccessful (see \ref SFMacros.h) * \sa NDK_PORTFOLIO_RET(), NDK_PORTFOLIO_VARIANCE() */ int __stdcall NDK_PORTFOLIO_COVARIANCE(double* weights1, double* weights2, size_t nAssets, double** covar, double* retVal); ///@} /*! * \name Utilities * * @{ */ /*! * \brief estimate the value of the function represented by (x,y) data set at an intermediate x-value. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval #NDK_FAILED Operation unsuccessful (see \ref SFMacros.h) * \sa NDK_WMA(), NDK_EWMA() */ int __stdcall NDK_INTERPOLATE(double* X, ///< [in] is the x-component of the input data table (a one dimensional array) size_t Nx, ///< [in] is the number of elements in X double* Y, ///< [in] is the y-component of the input data table (a one dimensional array) size_t Ny, ///< [in] is the number of elements in Y double* XT, ///< [in] is the desired x-value(s) to interpolate for (a single value or a one dimensional array). size_t Nxt, ///< [in] is the number of elements in XT WORD nMethod, ///< [in] is the interpolation method (1=Forward Flat, 2=Backward Flat, 3=Linear, 4=Cubic Spline). /// 1. Forward Flat /// 2. Backward Flat /// 3. Linear /// 4. Cublic Spline BOOL extrapolate, ///< [in] sets whether or not to allow extrapolation (1=Yes, 0=No). If missing, the default is to not allow extrapolation double* YVals, ///< [out] is the output buffer to store the interpolated values size_t Nyvals ///< [in] is the number of elements in YVals (must equal to Nxt). ); /*! * \brief Query & retrieve NumXL SDK environment information * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, NDK_Init() */ int __stdcall NDK_INFO(int nRetType, ///< [in] is a key/identifier to select the desired output /// 1. Version Number (default /// 2. Release /// 3. License Key /// 4. License Level /// 5. License Expiry Date /// 6. Installation Path /// 7. Data (e.g. Log-file) Path /// 8. Computer ID(unique identifier) LPTSTR szMsg, ///< [out] The buffer that will receive the return value int nSize ///< [inout] maximum number of characters to copy to the buffer. ); /*! * \brief write a log message to the logging system * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, SFLogger.h, SFLOG_LogMsg() */ int __stdcall NDK_MSG( int nRetCode, ///< [in] is the log level (1=trace, 2=Debug, 3=Info, 4=Warn, 5=Error, 6=Fatal Error) LPTSTR pMsg, ///< [in] is the log message size_t nSize ///< [in] us the number of characters in pMsg ); /*! * \brief set the seed value of the random number generator * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, SFSDK.h */ int __stdcall NDK_RNG_SEED(ULONG ulSeed ///< [in] is the new seed value for the random number generator ); /*! * \brief Locate and return the full path of the default editor (e.g. notepad) in the system * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa SFMacros.h, NDK_Init() */ int __stdcall NDK_DEFAULT_EDITOR (LPTSTR szFullPath, ///< [out] is the buffer that will receive the return value size_t* nSize ///< [inout] is the maximum number of characters to copy to the buffer. ); /*! * \brief Returns the n-th token/substring in a string after splitting it using a given delimiter * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa NDK_REGEX_REPLACE(), NDK_REGEX_MATCH() */ int __stdcall NDK_TOKENIZE (LPCTSTR szTxt, ///< [in] is the input string to match for. LPCTSTR szDelim, ///< [in] is the character to use for splitting the string. If missing, comma (,) is used. short nOrder, ///< [in] is the order of the token to return, where first = 1, second = 2,..., and last = -1. If missing, the first token is returned LPTSTR pRetVal, ///< [out] is the n-th token/substring in a string size_t nSize ///< [in] is the number of characters in pRetVal buffer ); /*! * \brief Returns TRUE if the string matches the regular expression expressed * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa NDK_REGEX_REPLACE(), NDK_TOKENIZE() */ int __stdcall NDK_REGEX_MATCH( LPCTSTR szLine, ///< [in] is the input string to match for. LPCTSTR szPattern, ///< [in] is the regular expression (regex PERL-style) to match the input string with (e.g. ^Thi[sS].*$). BOOL ignoreCase, ///< [in] is a flag to instruct the function to ignore the letter-case in the string BOOL partialOK, ///< [in] is a flag/switch to indicate whether a substring or a partial match (search) is permitted or to only consider full-string match. BOOL* bMatch ///< [out] is the return value of the match. ); /*! * \brief Returns the modified string after performing match/replace on the given string. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa NDK_REGEX_REPLACE(), NDK_TOKENIZE() */ int __stdcall NDK_REGEX_REPLACE(LPCTSTR szLine, ///< [in] is the input string to process. LPCTSTR szKey, ///< [in] is the regular expression (PERL-style) (e.g. "^\d\w{1,2}.*$"). LPCTSTR szValue, ///< [in] is the value to replace the match with. If missing or omitted, an empty string is used BOOL ignoreCase, ///< [in] is a flag to instruct the matching function whether to ignore letter-case. If missing, ignore_case is set to TRUE BOOL global, ///< [in] is a flag to instruct the function whether to match and replace the first occurence (FALSE) or all the matches (TRUE). LPTSTR pRetVal, ///< [out] is the modified string after replacement size_t nSize ///< [in] is the size of the output buffer (pRetVal) ); /*! * \brief calculates the value of the regression function for an intermediate x-value. * \return status code of the operation * \retval #NDK_SUCCESS Operation successful * \retval Error code * \sa NDK_TREND(), NDK_DETREND() */ int __stdcall NDK_REGRESSION( double* X, ///< [in] is the x-component of the input data table (a one dimensional array). size_t nX, ///< [in] is the number of elements in X. double* Y, ///< [in] is the y-component (i.e. function) of the input data table (a one dimensional array). size_t nY, ///< [in] is the number of elements in Y WORD nRegressType, ///< [in] is the model description flag for the trend function (1 = Linear (default), 2 = Polynomial, 3 = Exponential, 4 = Logarithmic, 5 = Power). WORD POrder, ///< [in] is the polynomial order. This is only relevant for a polynomial type of trend and is ignored for all others. If missing, POrder = 1. double intercept, ///< [in] is the constant or the intercept value to fix (e.g. zero). If missing (NaN), an intercept will not be fixed and is computed normally. double target, ///< [in] is the desired x-value to calculate regression value for (a single value). WORD nRetType, ///< [in] is a switch to select the return output (1 = Forecast value (default), 2 = Upper limit, 3 = Lower Limit, 4 = R-Squared). double alpha, ///< [in] is the statistical significance or confidence level (i.e. alpha). If missing or omitted, an alpha value of 5% is assumed double* retVal ///< [out] is the calculated value ); ///@} } /// @}
{'content_hash': '72a47784762482a67fe4141953762fc8', 'timestamp': '', 'source': 'github', 'line_count': 5079, 'max_line_length': 341, 'avg_line_length': 74.60858436700138, 'alnum_prop': 0.5582590245872006, 'repo_name': 'spiderxl/sdk', 'id': '73cc4f524ba8dcf455ab31eb18b9f08a36e34af3', 'size': '379454', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/SFSDK.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '430124'}, {'name': 'C#', 'bytes': '23001'}, {'name': 'C++', 'bytes': '8895'}, {'name': 'Visual Basic', 'bytes': '218372'}]}
package org.apache.kafka.copycat.runtime; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.utils.SystemTime; import org.apache.kafka.common.utils.Time; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.copycat.cli.WorkerConfig; import org.apache.kafka.copycat.connector.Connector; import org.apache.kafka.copycat.connector.ConnectorContext; import org.apache.kafka.copycat.connector.Task; import org.apache.kafka.copycat.errors.CopycatException; import org.apache.kafka.copycat.sink.SinkTask; import org.apache.kafka.copycat.source.SourceTask; import org.apache.kafka.copycat.storage.*; import org.apache.kafka.copycat.util.ConnectorTaskId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * <p> * Worker runs a (dynamic) set of tasks in a set of threads, doing the work of actually moving * data to/from Kafka. * </p> * <p> * Since each task has a dedicated thread, this is mainly just a container for them. * </p> */ public class Worker { private static final Logger log = LoggerFactory.getLogger(Worker.class); private Time time; private WorkerConfig config; private Converter keyConverter; private Converter valueConverter; private Converter internalKeyConverter; private Converter internalValueConverter; private OffsetBackingStore offsetBackingStore; private HashMap<String, Connector> connectors = new HashMap<>(); private HashMap<ConnectorTaskId, WorkerTask> tasks = new HashMap<>(); private KafkaProducer<byte[], byte[]> producer; private SourceTaskOffsetCommitter sourceTaskOffsetCommitter; public Worker(WorkerConfig config, OffsetBackingStore offsetBackingStore) { this(new SystemTime(), config, offsetBackingStore); } @SuppressWarnings("unchecked") public Worker(Time time, WorkerConfig config, OffsetBackingStore offsetBackingStore) { this.time = time; this.config = config; this.keyConverter = config.getConfiguredInstance(WorkerConfig.KEY_CONVERTER_CLASS_CONFIG, Converter.class); this.keyConverter.configure(config.originalsWithPrefix("key.converter."), true); this.valueConverter = config.getConfiguredInstance(WorkerConfig.VALUE_CONVERTER_CLASS_CONFIG, Converter.class); this.valueConverter.configure(config.originalsWithPrefix("value.converter."), false); this.internalKeyConverter = config.getConfiguredInstance(WorkerConfig.INTERNAL_KEY_CONVERTER_CLASS_CONFIG, Converter.class); this.internalKeyConverter.configure(config.originalsWithPrefix("internal.key.converter."), true); this.internalValueConverter = config.getConfiguredInstance(WorkerConfig.INTERNAL_VALUE_CONVERTER_CLASS_CONFIG, Converter.class); this.internalValueConverter.configure(config.originalsWithPrefix("internal.value.converter."), false); this.offsetBackingStore = offsetBackingStore; this.offsetBackingStore.configure(config.originals()); } public void start() { log.info("Worker starting"); Properties unusedConfigs = config.unusedProperties(); Map<String, Object> producerProps = new HashMap<>(); producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Utils.join(config.getList(WorkerConfig.BOOTSTRAP_SERVERS_CONFIG), ",")); producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"); producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"); for (String propName : unusedConfigs.stringPropertyNames()) { producerProps.put(propName, unusedConfigs.getProperty(propName)); } producer = new KafkaProducer<>(producerProps); offsetBackingStore.start(); sourceTaskOffsetCommitter = new SourceTaskOffsetCommitter(time, config); log.info("Worker started"); } public void stop() { log.info("Worker stopping"); long started = time.milliseconds(); long limit = started + config.getLong(WorkerConfig.TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_CONFIG); for (Map.Entry<String, Connector> entry : connectors.entrySet()) { Connector conn = entry.getValue(); log.warn("Shutting down connector {} uncleanly; herder should have shut down connectors before the" + "Worker is stopped.", conn); try { conn.stop(); } catch (CopycatException e) { log.error("Error while shutting down connector " + conn, e); } } for (Map.Entry<ConnectorTaskId, WorkerTask> entry : tasks.entrySet()) { WorkerTask task = entry.getValue(); log.warn("Shutting down task {} uncleanly; herder should have shut down " + "tasks before the Worker is stopped.", task); try { task.stop(); } catch (CopycatException e) { log.error("Error while shutting down task " + task, e); } } for (Map.Entry<ConnectorTaskId, WorkerTask> entry : tasks.entrySet()) { WorkerTask task = entry.getValue(); log.debug("Waiting for task {} to finish shutting down", task); if (!task.awaitStop(Math.max(limit - time.milliseconds(), 0))) log.error("Graceful shutdown of task {} failed.", task); task.close(); } long timeoutMs = limit - time.milliseconds(); sourceTaskOffsetCommitter.close(timeoutMs); offsetBackingStore.stop(); log.info("Worker stopped"); } /** * Add a new connector. * @param connConfig connector configuration * @param ctx context for the connector */ public void addConnector(ConnectorConfig connConfig, ConnectorContext ctx) { String connName = connConfig.getString(ConnectorConfig.NAME_CONFIG); Class<?> maybeConnClass = connConfig.getClass(ConnectorConfig.CONNECTOR_CLASS_CONFIG); log.info("Creating connector {} of type {}", connName, maybeConnClass.getName()); Class<? extends Connector> connClass; try { connClass = maybeConnClass.asSubclass(Connector.class); } catch (ClassCastException e) { throw new CopycatException("Specified class is not a subclass of Connector: " + maybeConnClass.getName()); } if (connectors.containsKey(connName)) throw new CopycatException("Connector with name " + connName + " already exists"); final Connector connector = instantiateConnector(connClass); connector.initialize(ctx); try { Map<String, Object> originals = connConfig.originals(); Properties props = new Properties(); props.putAll(originals); connector.start(props); } catch (CopycatException e) { throw new CopycatException("Connector threw an exception while starting", e); } connectors.put(connName, connector); log.info("Finished creating connector {}", connName); } private static Connector instantiateConnector(Class<? extends Connector> connClass) { try { return Utils.newInstance(connClass); } catch (Throwable t) { // Catches normal exceptions due to instantiation errors as well as any runtime errors that // may be caused by user code throw new CopycatException("Failed to create connector instance", t); } } public Map<ConnectorTaskId, Map<String, String>> reconfigureConnectorTasks(String connName, int maxTasks, List<String> sinkTopics) { log.trace("Reconfiguring connector tasks for {}", connName); Connector connector = connectors.get(connName); if (connector == null) throw new CopycatException("Connector " + connName + " not found in this worker."); Map<ConnectorTaskId, Map<String, String>> result = new HashMap<>(); String taskClassName = connector.taskClass().getName(); int index = 0; for (Properties taskProps : connector.taskConfigs(maxTasks)) { ConnectorTaskId taskId = new ConnectorTaskId(connName, index); index++; Map<String, String> taskConfig = Utils.propsToStringMap(taskProps); taskConfig.put(TaskConfig.TASK_CLASS_CONFIG, taskClassName); if (sinkTopics != null) taskConfig.put(SinkTask.TOPICS_CONFIG, Utils.join(sinkTopics, ",")); result.put(taskId, taskConfig); } return result; } public void stopConnector(String connName) { log.info("Stopping connector {}", connName); Connector connector = connectors.get(connName); if (connector == null) throw new CopycatException("Connector " + connName + " not found in this worker."); try { connector.stop(); } catch (CopycatException e) { log.error("Error shutting down connector {}: ", connector, e); } connectors.remove(connName); log.info("Stopped connector {}", connName); } /** * Get the IDs of the connectors currently running in this worker. */ public Set<String> connectorNames() { return connectors.keySet(); } /** * Add a new task. * @param id Globally unique ID for this task. * @param taskConfig the parsed task configuration */ public void addTask(ConnectorTaskId id, TaskConfig taskConfig) { log.info("Creating task {}", id); if (tasks.containsKey(id)) { String msg = "Task already exists in this worker; the herder should not have requested " + "that this : " + id; log.error(msg); throw new CopycatException(msg); } final Task task = instantiateTask(taskConfig.getClass(TaskConfig.TASK_CLASS_CONFIG).asSubclass(Task.class)); // Decide which type of worker task we need based on the type of task. final WorkerTask workerTask; if (task instanceof SourceTask) { SourceTask sourceTask = (SourceTask) task; OffsetStorageReader offsetReader = new OffsetStorageReaderImpl(offsetBackingStore, id.connector(), internalKeyConverter, internalValueConverter); OffsetStorageWriter offsetWriter = new OffsetStorageWriter(offsetBackingStore, id.connector(), internalKeyConverter, internalValueConverter); workerTask = new WorkerSourceTask(id, sourceTask, keyConverter, valueConverter, producer, offsetReader, offsetWriter, config, time); } else if (task instanceof SinkTask) { workerTask = new WorkerSinkTask(id, (SinkTask) task, config, keyConverter, valueConverter, time); } else { log.error("Tasks must be a subclass of either SourceTask or SinkTask", task); throw new CopycatException("Tasks must be a subclass of either SourceTask or SinkTask"); } // Start the task before adding modifying any state, any exceptions are caught higher up the // call chain and there's no cleanup to do here Properties props = new Properties(); props.putAll(taskConfig.originals()); workerTask.start(props); if (task instanceof SourceTask) { WorkerSourceTask workerSourceTask = (WorkerSourceTask) workerTask; sourceTaskOffsetCommitter.schedule(id, workerSourceTask); } tasks.put(id, workerTask); } private static Task instantiateTask(Class<? extends Task> taskClass) { try { return Utils.newInstance(taskClass); } catch (KafkaException e) { throw new CopycatException("Task class not found", e); } } public void stopTask(ConnectorTaskId id) { log.info("Stopping task {}", id); WorkerTask task = getTask(id); if (task instanceof WorkerSourceTask) sourceTaskOffsetCommitter.remove(id); task.stop(); if (!task.awaitStop(config.getLong(WorkerConfig.TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_CONFIG))) log.error("Graceful stop of task {} failed.", task); task.close(); tasks.remove(id); } /** * Get the IDs of the tasks currently running in this worker. */ public Set<ConnectorTaskId> taskIds() { return tasks.keySet(); } private WorkerTask getTask(ConnectorTaskId id) { WorkerTask task = tasks.get(id); if (task == null) { log.error("Task not found: " + id); throw new CopycatException("Task not found: " + id); } return task; } public Converter getInternalKeyConverter() { return internalKeyConverter; } public Converter getInternalValueConverter() { return internalValueConverter; } }
{'content_hash': '6dc7afa4b06ec1e47ae7f5bc03bc904f', 'timestamp': '', 'source': 'github', 'line_count': 321, 'max_line_length': 139, 'avg_line_length': 41.308411214953274, 'alnum_prop': 0.6619909502262443, 'repo_name': 'bluebreezecf/kafka', 'id': 'b37e49f82b0bfabc61ddb7dc8a9db121a92194e6', 'size': '14069', 'binary': False, 'copies': '1', 'ref': 'refs/heads/trunk', 'path': 'copycat/runtime/src/main/java/org/apache/kafka/copycat/runtime/Worker.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '20579'}, {'name': 'HTML', 'bytes': '5443'}, {'name': 'Java', 'bytes': '3079838'}, {'name': 'Python', 'bytes': '481095'}, {'name': 'Scala', 'bytes': '2641655'}, {'name': 'Shell', 'bytes': '92527'}, {'name': 'XSLT', 'bytes': '7116'}]}
package org.apache.geode.internal.cache.entries; // DO NOT modify this class. It was generated from LeafRegionEntry.cpp import java.util.concurrent.atomic.AtomicLongFieldUpdater; import org.apache.geode.internal.cache.DiskId; import org.apache.geode.internal.cache.DiskStoreImpl; import org.apache.geode.internal.cache.PlaceHolderDiskRegion; import org.apache.geode.internal.cache.RegionEntry; import org.apache.geode.internal.cache.RegionEntryContext; import org.apache.geode.internal.cache.eviction.EvictionController; import org.apache.geode.internal.cache.persistence.DiskRecoveryStore; import org.apache.geode.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry; /* * macros whose definition changes this class: * * disk: DISK lru: LRU stats: STATS versioned: VERSIONED offheap: OFFHEAP * * One of the following key macros must be defined: * * key object: KEY_OBJECT key int: KEY_INT key long: KEY_LONG key uuid: KEY_UUID key string1: * KEY_STRING1 key string2: KEY_STRING2 */ /** * Do not modify this class. It was generated. Instead modify LeafRegionEntry.cpp and then run * ./dev-tools/generateRegionEntryClasses.sh (it must be run from the top level directory). */ public class VMThinDiskRegionEntryHeapIntKey extends VMThinDiskRegionEntryHeap { // --------------------------------------- common fields ---------------------------------------- private static final AtomicLongFieldUpdater<VMThinDiskRegionEntryHeapIntKey> LAST_MODIFIED_UPDATER = AtomicLongFieldUpdater.newUpdater(VMThinDiskRegionEntryHeapIntKey.class, "lastModified"); protected int hash; private HashEntry<Object, Object> nextEntry; @SuppressWarnings("unused") private volatile long lastModified; private volatile Object value; // ---------------------------------------- disk fields ----------------------------------------- /** * @since GemFire 5.1 */ protected DiskId id; // --------------------------------------- key fields ------------------------------------------- // DO NOT modify this class. It was generated from LeafRegionEntry.cpp private final int key; public VMThinDiskRegionEntryHeapIntKey(final RegionEntryContext context, final int key, final Object value) { super(context, (value instanceof RecoveredEntry ? null : value)); // DO NOT modify this class. It was generated from LeafRegionEntry.cpp initialize(context, value); this.key = key; } // DO NOT modify this class. It was generated from LeafRegionEntry.cpp @Override protected Object getValueField() { return this.value; } @Override protected void setValueField(final Object value) { this.value = value; } @Override protected long getLastModifiedField() { return LAST_MODIFIED_UPDATER.get(this); } @Override protected boolean compareAndSetLastModifiedField(final long expectedValue, final long newValue) { return LAST_MODIFIED_UPDATER.compareAndSet(this, expectedValue, newValue); } @Override public int getEntryHash() { return this.hash; } @Override protected void setEntryHash(final int hash) { this.hash = hash; } @Override public HashEntry<Object, Object> getNextEntry() { return this.nextEntry; } @Override public void setNextEntry(final HashEntry<Object, Object> nextEntry) { this.nextEntry = nextEntry; } // ----------------------------------------- disk code ------------------------------------------ // DO NOT modify this class. It was generated from LeafRegionEntry.cpp protected void initialize(final RegionEntryContext context, final Object value) { diskInitialize(context, value); } @Override public int updateAsyncEntrySize(final EvictionController evictionController) { throw new IllegalStateException("should never be called"); } // DO NOT modify this class. It was generated from LeafRegionEntry.cpp @Override public DiskId getDiskId() { return this.id; } @Override public void setDiskId(final RegionEntry oldEntry) { this.id = ((DiskEntry) oldEntry).getDiskId(); } private void diskInitialize(final RegionEntryContext context, final Object value) { DiskRecoveryStore diskRecoveryStore = (DiskRecoveryStore) context; DiskStoreImpl diskStore = diskRecoveryStore.getDiskStore(); long maxOplogSize = diskStore.getMaxOplogSize(); // get appropriate instance of DiskId implementation based on maxOplogSize this.id = DiskId.createDiskId(maxOplogSize, true, diskStore.needsLinkedList()); Helper.initialize(this, diskRecoveryStore, value); } // ----------------------------------------- key code ------------------------------------------- // DO NOT modify this class. It was generated from LeafRegionEntry.cpp @Override public Object getKey() { return this.key; } @Override public boolean isKeyEqual(final Object key) { if (key instanceof Integer) { return ((Integer) key).intValue() == this.key; } return false; } // DO NOT modify this class. It was generated from LeafRegionEntry.cpp }
{'content_hash': 'e13cb1c42ae90d6e3f52ddd628c608d8', 'timestamp': '', 'source': 'github', 'line_count': 145, 'max_line_length': 102, 'avg_line_length': 34.84827586206897, 'alnum_prop': 0.687908173362359, 'repo_name': 'smanvi-pivotal/geode', 'id': '92363f96a7e310faa9eb04541b8f2908e9d9da16', 'size': '5842', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'geode-core/src/main/java/org/apache/geode/internal/cache/entries/VMThinDiskRegionEntryHeapIntKey.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '106707'}, {'name': 'Groovy', 'bytes': '2928'}, {'name': 'HTML', 'bytes': '3998074'}, {'name': 'Java', 'bytes': '26700079'}, {'name': 'JavaScript', 'bytes': '1781013'}, {'name': 'Ruby', 'bytes': '6751'}, {'name': 'Shell', 'bytes': '21891'}]}
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("nil-runtime")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("nil-runtime")] [assembly: AssemblyCopyright("Copyright © 2016")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
{'content_hash': '77481f0647e02de905ab2c3f50bc9b00', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 98, 'avg_line_length': 43.236363636363635, 'alnum_prop': 0.7060555088309504, 'repo_name': 'zhongzf/nativescript-dotnet-runtime', 'id': '9bfbc4e51d7048250d63d6d0c6a7f02e1c6095eb', 'size': '2381', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'nil-runtime/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '85788'}, {'name': 'JavaScript', 'bytes': '2760248'}]}
<form method="post">{% csrf_token %} ¿Estás seguro que deseas borrar "{{ object }}"? <input type="submit" value="Submit" /> </form>
{'content_hash': 'c4fef9e41ae222ee1cc0fea65addde63', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 51, 'avg_line_length': 35.5, 'alnum_prop': 0.5985915492957746, 'repo_name': 'GoberInfinity/ExampleDjango', 'id': '417a387fe6c3466b70981ca6fae8d52886505327', 'size': '144', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'crudclassviews/templates/crudclassviews/person_confirm_delete.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '187'}, {'name': 'HTML', 'bytes': '2054'}, {'name': 'JavaScript', 'bytes': '615'}, {'name': 'Python', 'bytes': '16642'}]}
import * as yargs from "yargs"; export function initCLI() { console.log("init cli"); }
{'content_hash': '13878994ea13d4b9806c7eaf242fb0f4', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 31, 'avg_line_length': 18.4, 'alnum_prop': 0.6521739130434783, 'repo_name': 'pnml/fuse-box', 'id': 'b78d2c491e5886bae60ff92173defd759a4f0119', 'size': '92', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/cli/entry.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '533'}, {'name': 'HTML', 'bytes': '44'}, {'name': 'JavaScript', 'bytes': '646157'}, {'name': 'TypeScript', 'bytes': '926593'}]}
/*global module, test, equal, ok, jQuery */ (function ($) { "use strict"; /* If there is no delegation support, forcibly reset the plugin between * test runs */ function resetPlugin() { if (!$.fn.on && !$.fn.delegate && !$.fn.live) { $.fn.example.boundClassNames = []; } } module("Basic usage", { setup: function () { $('#basic1').example('Test'); $('#basicform').submit(function (e) { e.preventDefault(); }); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#basic1').val(), "Test", "The example should read 'Test'."); ok($('#basic1').hasClass('example'), "The class should be 'example'."); }); test("should be cleared on focus", function () { $('#basic1').focus(); equal($('#basic1').val(), "", "The example should be cleared."); ok(!$('#basic1').hasClass('example'), "The class should no longer be 'example'."); }); test("should reappear on blur if empty", function () { $('#basic1').focus().blur(); equal($('#basic1').val(), "Test", "The example should read 'Test'."); ok($('#basic1').hasClass('example'), "The class should be 'example'."); }); test("should not be populated with an example on blur if user input is present", function () { $('#basic1').focus(); $('#basic1').val("My own value"); $('#basic1').blur(); equal($('#basic1').val(), "My own value", "The example should not be cleared."); ok(!$('#basic1').hasClass('example'), "The class should not be 'example'."); }); test("should not be populated with an example on focus if user input is present", function () { $('#basic1').focus().val("My own value").blur().focus(); equal($('#basic1').val(), "My own value", "The example should not be cleared."); ok(!$('#basic1').hasClass('example'), "The class should not be 'example'."); }); test("should be cleared on form submit", function () { $('#basicform').submit(); equal($('#basic1').val(), "", "The example should be cleared."); }); test("shouldn't clear user inputs on form submit", function () { $('#basic2').focus().val("User input"); $('#basicform').triggerHandler('submit'); equal($('#basic2').val(), "User input", "The user input should be intact."); }); module("Using custom classes", { setup: function () { $('#custom1').example("Test", {className: "notExample"}); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#custom1').val(), "Test", "The example should be set."); ok($('#custom1').hasClass('notExample'), "The class should be the specified one."); ok(!$('#custom1').hasClass('example'), "The class should not be 'example'."); }); test("should be cleared on focus", function () { $('#custom1').focus(); equal($('#custom1').val(), "", "The example should be cleared."); ok(!$('#custom1').hasClass('notExample'), "The class should not be the specified one."); }); test("should be reappear on blur", function () { $('#custom1').focus().blur(); equal($('#custom1').val(), "Test", "The example should reappear."); ok($('#custom1').hasClass('notExample'), "The class should be the specified one."); }); module("Multiple forms", { setup: function () { $('#multipleform1, #multipleform2').submit(function (e) { e.preventDefault(); }); $('#mf1').example('Test'); $('#mf2').example('Test'); }, teardown: resetPlugin }); test("should only clear examples in that form", function () { $('#multipleform1').submit(); equal($('#mf1').val(), "", "The example should be cleared."); equal($('#mf2').val(), "Test", "An example in another form should not be cleared."); }); module("Simple callback", { setup: function () { $('#callback1').example(function () { return "Callback Test"; }); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#callback1').val(), "Callback Test", "The example should read 'Callback Test'."); ok($('#callback1').hasClass('example'), "The class should be 'example'."); }); test("should be cleared on focus", function () { $('#callback1').focus(); equal($('#callback1').val(), "", "The example should be cleared."); ok(!$('#callback1').hasClass('example'), "The class should no longer be 'example'."); }); test("should reappear on blur if empty", function () { $('#callback1').focus().blur(); equal($('#callback1').val(), "Callback Test", "The example should read 'Callback Test'."); ok($('#callback1').hasClass('example'), "The class should be 'example'."); }); module("More complicated callback", { setup: function () { $('#callback2').example(function () { return $(this).attr('title'); }); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#callback2').val(), "Starting", "The example should read 'Starting'."); ok($('#callback2').hasClass('example'), "The class should be 'example'."); }); test("should be cleared on focus", function () { $('#callback2').focus(); equal($('#callback2').val(), "", "The example should be cleared."); ok(!$('#callback2').hasClass('example'), "The class should no longer be 'example'."); }); test("should reappear on blur if empty", function () { $('#callback2').focus().blur(); equal($('#callback2').val(), "Starting", "The example should read 'Starting'."); ok($('#callback2').hasClass('example'), "The class should be 'example'."); }); test("should run the callback every time instead of caching it", function () { $('#callback2').attr('title', 'Another'); $('#callback2').focus().blur(); equal($('#callback2').val(), "Another", "The example should read 'Another'."); ok($('#callback2').hasClass('example'), "The class should be 'example'."); }); module("Metadata plugin", { setup: function () { $('#m1').example(); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#m1').val(), "Something", "The example should read 'Something'."); ok($('#m1').hasClass('m1'), "The class should be 'm1'."); }); test("should be cleared on focus", function () { $('#m1').focus(); equal($('#m1').val(), "", "The example should be cleared."); ok(!$('#m1').hasClass('m1'), "The class should no longer be 'm1'."); }); test("should reappear on blur if empty", function () { $('#m1').focus().blur(); equal($('#m1').val(), "Something", "The example should read 'Something'."); ok($('#m1').hasClass('m1'), "The class should be 'm1'."); }); test("should be overridden by arguments", function () { $('#m2').example('Precedence', {className: 'o1'}); equal($('#m2').val(), "Precedence", "The example in the arguments should take precedence"); ok($('#m2').hasClass('o1'), "The class should be 'o1'."); }); module("On page load", { teardown: resetPlugin }); test("should not set an example if a value is already set", function () { $('#load1').example("Test"); equal($('#load1').val(), "Already filled in", "The example should not be set."); ok(!$('#load1').hasClass('example'), "The class should not be 'example'."); }); test("should not clear a field with a value even when using a callback", function () { $('#load2').example(function () { return "Nope"; }); equal($('#load2').val(), "Default", "The value should be the default."); ok(!$('#load2').hasClass('example'), "The class should not be 'example'."); }); module("Changing values by Javascript", { setup: function () { $('#f1').example('Example'); }, teardown: resetPlugin }); test("should set example", function () { equal($('#f1').val(), "Example", "The example should read 'Example'."); ok($('#f1').hasClass('example'), "The example class should be set."); }); test("should remove example class when changed", function () { $('#f1').val("New value"); $('#f1').change(); equal($('#f1').val(), "New value", "Value should be changed to 'New value'."); ok(!$('#f1').hasClass('example'), "The example class should no longer be set."); /* Clear the field between test runs. */ $('#f1').val(''); }); module("Clearing values when loaded from cache", { teardown: resetPlugin }); test("value should be set to default value", function () { /* Fake loading from cache by setting the example to be different to * the recorded defaultValue. */ $('#c1').val('Cached example').example('Cached example'); equal($('#c1').val(), "Filled in", "Value should have been reset to 'Filled in'."); }); test("value should be cleared and set to the example if without default", function () { $('#c2').val('Cached example').example('Cached example'); equal($('#c2').val(), 'Cached example', "Value should have been emptied."); ok($('#c2').hasClass('example'), 'The example class should be set.'); }); test("value is not touched if it doesn't match the example", function () { $('#c3').val('Some user input').example('Test'); equal($('#c3').val(), 'Some user input', 'Value should not have been modified.'); ok(!$('#c3').hasClass('example'), 'The example class should not be set.'); }); test('value is always cleared if the example is a callback', function () { $('#c4').val('Some user input').example(function () { return 'Test'; }); equal($('#c4').val(), 'Test', 'The cached value is overridden.'); ok($('#c4').hasClass('example'), 'The example class should be set.'); }); test('value is not touched if it is the default', function () { $('#c5').val('Some default').example('Test'); equal($('#c5').val(), 'Some default', 'Value should not have been modified.'); ok(!$('#c5').hasClass('example'), 'The example class should not be set.'); }); module('Custom events', { teardown: resetPlugin }); test('a specific form is cleared when calling example:resetForm on it', function () { $('#ce1, #ce2').example('Testing'); $('#custom').trigger('example:resetForm'); equal($('#ce1').val(), '', 'The value should have been cleared.'); ok(!$('#ce1').hasClass('example'), 'The example class should not be set.'); equal($('#ce2').val(), 'Testing', 'The value should not have been cleared.'); ok($('#ce2').hasClass('example'), 'The example class should be set.'); }); test('triggering example:resetForm on a field will bubble to the form', function () { $('#ce1').example('Testing'); $('#ce1').trigger('example:resetForm'); equal($('#ce1').val(), '', 'The value should have been cleared.'); ok(!$('#ce1').hasClass('example'), 'The example class should not be set.'); }); }(jQuery));
{'content_hash': '36ff2e589dff2edf047d73e54038b016', 'timestamp': '', 'source': 'github', 'line_count': 281, 'max_line_length': 99, 'avg_line_length': 41.779359430604984, 'alnum_prop': 0.547274275979557, 'repo_name': 'mudge/jquery_example', 'id': 'bc881493b21f22c98ac4deb594978428aff164c3', 'size': '11740', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/jquery.example_test.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '4602'}, {'name': 'HTML', 'bytes': '3105'}, {'name': 'JavaScript', 'bytes': '66502'}, {'name': 'Ruby', 'bytes': '147'}]}
<?php namespace Drupal\block; use Drupal\Core\Block\BlockPluginInterface; use Drupal\Core\Config\Entity\ConfigEntityInterface; /** * Provides an interface defining a block entity. */ interface BlockInterface extends ConfigEntityInterface { /** * Indicates the block label (title) should be displayed to end users. * * @deprecated in Drupal 8.3.x, will be removed before Drupal 9.0.0. * Use \Drupal\Core\Block\BlockPluginInterface::BLOCK_LABEL_VISIBLE. * * @see https://www.drupal.org/node/2829775 */ const BLOCK_LABEL_VISIBLE = BlockPluginInterface::BLOCK_LABEL_VISIBLE; /** * Denotes that a block is not enabled in any region and should not be shown. * * @deprecated Scheduled for removal in Drupal 9.0.0. */ const BLOCK_REGION_NONE = -1; /** * Returns the plugin instance. * * @return \Drupal\Core\Block\BlockPluginInterface * The plugin instance for this block. */ public function getPlugin(); /** * Returns the plugin ID. * * @return string * The plugin ID for this block. */ public function getPluginId(); /** * Returns the region this block is placed in. * * @return string * The region this block is placed in. */ public function getRegion(); /** * Returns the theme ID. * * @return string * The theme ID for this block instance. */ public function getTheme(); /** * Returns an array of visibility condition configurations. * * @return array * An array of visibility condition configuration keyed by the condition ID. */ public function getVisibility(); /** * Gets conditions for this block. * * @return \Drupal\Core\Condition\ConditionInterface[]|\Drupal\Core\Condition\ConditionPluginCollection * An array or collection of configured condition plugins. */ public function getVisibilityConditions(); /** * Gets a visibility condition plugin instance. * * @param string $instance_id * The condition plugin instance ID. * * @return \Drupal\Core\Condition\ConditionInterface * A condition plugin. */ public function getVisibilityCondition($instance_id); /** * Sets the visibility condition configuration. * * @param string $instance_id * The condition instance ID. * @param array $configuration * The condition configuration. * * @return $this */ public function setVisibilityConfig($instance_id, array $configuration); /** * Returns the weight of this block (used for sorting). * * @return int * The block weight. */ public function getWeight(); /** * Sets the region this block is placed in. * * @param string $region * The region to place this block in. * * @return $this */ public function setRegion($region); /** * Sets the block weight. * * @param int $weight * The desired weight. * * @return $this */ public function setWeight($weight); /** * Creates a duplicate of the block entity. * * @param string $new_id * (optional) The new ID on the duplicate block. * @param string $new_theme * (optional) The theme on the duplicate block. * * @return static * A clone of $this with all identifiers unset, so saving it inserts a new * entity into the storage system. */ public function createDuplicateBlock($new_id = NULL, $new_theme = NULL); }
{'content_hash': '630d823d07c3b7def923126c3b6565ef', 'timestamp': '', 'source': 'github', 'line_count': 143, 'max_line_length': 105, 'avg_line_length': 23.958041958041957, 'alnum_prop': 0.6579100992410974, 'repo_name': 'leorawe/sci-base', 'id': 'f4ce6268c2adedc3c6bd7e7acc5a1da77f6dd698', 'size': '3426', 'binary': False, 'copies': '68', 'ref': 'refs/heads/master', 'path': 'web/core/modules/block/src/BlockInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '891567'}, {'name': 'Gherkin', 'bytes': '3374'}, {'name': 'HTML', 'bytes': '809692'}, {'name': 'JavaScript', 'bytes': '1514397'}, {'name': 'PHP', 'bytes': '36312357'}, {'name': 'Ruby', 'bytes': '63696'}, {'name': 'Shell', 'bytes': '59930'}]}
var path = require('path'); var url = require('url'); function fromFileURL(url) { return url.substr(7 + !!process.platform.match(/^win/)).replace(/\//g, path.sep); } exports.fromFileURL = fromFileURL; function toFileURL(path) { return 'file://' + (process.platform.match(/^win/) ? '/' : '') + path.replace(/\\/g, '/'); } exports.toFileURL = toFileURL; function isFileURL(url) { return url.substr(0, 5) === 'file:'; } exports.isFileURL = isFileURL; /* Remove scheme prefix from file URLs, so that they are paths. */ function filePath(url) { if (isFileURL(url)) return url.replace(/^file:\/+/, '/'); } exports.filePath = filePath; /* Coerce URLs to paths, assuming they are file URLs */ function coercePath(url) { if (isFileURL(url)) return url.replace(/^file:\/+/, '/'); else // assume relative return path.resolve(process.cwd(), url); } exports.coercePath = coercePath; var absURLRegEx = /^[^\/]+:\/\//; function normalizePath(loader, path) { var curPath; if (loader.paths[path][0] == '.') curPath = decodeURI(url.resolve(toFileURL(process.cwd()) + '/', loader.paths[path])); else curPath = decodeURI(url.resolve(loader.baseURL, loader.paths[path])); if (loader.defaultJSExtensions && curPath.substr(curPath.length - 3, 3) != '.js') curPath += '.js'; return curPath; } exports.getCanonicalName = getCanonicalName; function getCanonicalName(loader, normalized) { // remove the plugin part first var plugin; if (loader.pluginFirst) { var pluginIndex = normalized.indexOf('!'); if (pluginIndex != -1) { plugin = normalized.substr(0, pluginIndex); normalized = normalized.substr(pluginIndex + 1); } } else { var pluginIndex = normalized.lastIndexOf('!'); if (pluginIndex != -1) { plugin = normalized.substr(pluginIndex + 1); normalized = normalized.substr(0, pluginIndex); } } // now just reverse apply paths rules to get canonical name var pathMatch; // first check exact path matches for (var p in loader.paths) { if (loader.paths[p].indexOf('*') != -1) continue; var curPath = normalizePath(loader, p); if (normalized === curPath) { // always stop on first exact match pathMatch = p; break; } } // then wildcard matches var pathMatchLength = 0; var curMatchlength; if (!pathMatch) for (var p in loader.paths) { if (loader.paths[p].indexOf('*') == -1) continue; // normalize the output path var curPath = normalizePath(loader, p); // do reverse match var wIndex = curPath.indexOf('*'); if (normalized.substr(0, wIndex) === curPath.substr(0, wIndex) && normalized.substr(normalized.length - curPath.length + wIndex + 1) === curPath.substr(wIndex + 1)) { curMatchLength = curPath.split('/').length; if (curMatchLength > pathMatchLength) { pathMatch = p.replace('*', normalized.substr(wIndex, normalized.length - curPath.length + 1)); pathMatchLength = curMatchLength; } } } // when no path was matched, act like the standard rule is *: baseURL/* if (!pathMatch) { if (normalized.substr(0, loader.baseURL.length) == loader.baseURL) pathMatch = normalized.substr(loader.baseURL.length); else if (normalized.match(absURLRegEx)) throw 'Unable to calculate canonical name to bundle ' + normalized; else pathMatch = normalized; } if (plugin) { if (loader.pluginFirst) { pathMatch = getCanonicalName(loader, plugin) + '!' + pathMatch; } else { pathMatch += '!' + getCanonicalName(loader, plugin); } } return pathMatch; } exports.getAlias = getAlias function getAlias(loader, canonicalName) { var bestAlias; function getBestAlias(mapped) { return canonicalName.substr(0, mapped.length) == mapped && (canonicalName.length == mapped.length || canonicalName[mapped.length + 1] == '/'); } Object.keys(loader.map).forEach(function(alias) { if (getBestAlias(loader.map[alias])) bestAlias = alias; }); if (bestAlias) return bestAlias; Object.keys(loader.packages).forEach(function(pkg) { Object.keys(loader.packages[pkg].map || {}).forEach(function(alias) { if (getBestAlias(loader.packages[pkg].map[alias])) bestAlias = alias; }); }); return bestAlias || canonicalName; }
{'content_hash': '461a16a1abe3111bec734ad1c864bb6e', 'timestamp': '', 'source': 'github', 'line_count': 155, 'max_line_length': 111, 'avg_line_length': 28.329032258064515, 'alnum_prop': 0.6406285584149396, 'repo_name': 'synaptek/builder', 'id': '93a55949e9728d5bc127000b355ec4bd5d83af27', 'size': '4391', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/utils.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '7636'}, {'name': 'JavaScript', 'bytes': '113223'}]}
package org.bitcoins.server import akka.actor.ActorSystem import akka.http.scaladsl.server._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer import org.bitcoins.node.Node case class NodeRoutes(node: Node)(implicit system: ActorSystem) extends ServerRoute { implicit val materializer = ActorMaterializer() def handleCommand: PartialFunction[ServerCommand, StandardRoute] = { case ServerCommand("getpeers", _) => complete { Server.httpSuccess("TODO implement getpeers") } } }
{'content_hash': 'd057f744080eb16e27dd188a803ff6ea', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 70, 'avg_line_length': 28.736842105263158, 'alnum_prop': 0.7545787545787546, 'repo_name': 'bitcoin-s/bitcoin-s-core', 'id': 'c5db4d25695457a687cb9936687b2d53ada05d40', 'size': '546', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/server/src/main/scala/org/bitcoins/server/NodeRoutes.scala', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2266'}, {'name': 'Dockerfile', 'bytes': '148'}, {'name': 'Java', 'bytes': '44689'}, {'name': 'JavaScript', 'bytes': '22991'}, {'name': 'Scala', 'bytes': '2222831'}, {'name': 'Shell', 'bytes': '804'}]}
Node.js - klaw ============== <a href="https://standardjs.com" style="float: right; padding: 0 0 20px 20px;"><img src="https://cdn.rawgit.com/feross/standard/master/sticker.svg" alt="JavaScript Standard Style" width="100" align="right"></a> A Node.js file system walker extracted from [fs-extra](https://github.com/jprichardson/node-fs-extra). [![npm Package](https://img.shields.io/npm/v/klaw.svg?style=flat-square)](https://www.npmjs.org/package/klaw) [![build status](https://api.travis-ci.org/jprichardson/node-klaw.svg)](http://travis-ci.org/jprichardson/node-klaw) [![windows build status](https://ci.appveyor.com/api/projects/status/github/jprichardson/node-klaw?branch=master&svg=true)](https://ci.appveyor.com/project/jprichardson/node-klaw/branch/master) Install ------- npm i --save klaw If you're using Typescript, we've got [types](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/11492/files): npm i --save-dev @types/klaw Name ---- `klaw` is `walk` backwards :p Sync ---- If you need the same functionality but synchronous, you can use [klaw-sync](https://github.com/manidlou/node-klaw-sync). Usage ----- ### klaw(directory, [options]) Returns a [Readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable) that iterates through every file and directory starting with `dir` as the root. Every `read()` or `data` event returns an object with two properties: `path` and `stats`. `path` is the full path of the file and `stats` is an instance of [fs.Stats](https://nodejs.org/api/fs.html#fs_class_fs_stats). - `directory`: The directory to recursively walk. Type `string`. - `options`: [Readable stream options](https://nodejs.org/api/stream.html#stream_new_stream_readable_options) and the following: - `queueMethod` (`string`, default: `'shift'`): Either `'shift'` or `'pop'`. On `readdir()` array, call either `shift()` or `pop()`. - `pathSorter` (`function`, default: `undefined`): Sorting [function for Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). - `fs` (`object`, default: [`graceful-fs`](https://github.com/isaacs/node-graceful-fs)): Use this to hook into the `fs` methods or to use [`mock-fs`](https://github.com/tschaub/mock-fs) - `filter` (`function`, default: `undefined`): Filtering [function for Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) - `depthLimit` (`number`, default: `undefined`): The number of times to recurse before stopping. -1 for unlimited. - `preserveSymlinks` (`boolean`, default: `false`): Whether symlinks should be followed or treated as items themselves. If true, symlinks will be returned as items in their own right. If false, the linked item will be returned and potentially recursed into, in its stead. **Streams 1 (push) example:** ```js const klaw = require('klaw') const items = [] // files, directories, symlinks, etc klaw('/some/dir') .on('data', item => items.push(item.path)) .on('end', () => console.dir(items)) // => [ ... array of files] ``` **Streams 2 & 3 (pull) example:** ```js const klaw = require('klaw') const items = [] // files, directories, symlinks, etc klaw('/some/dir') .on('readable', function () { let item while ((item = this.read())) { items.push(item.path) } }) .on('end', () => console.dir(items)) // => [ ... array of files] ``` **```for-await-of``` example:** ```js for await (const file of klaw('/some/dir')) { console.log(file) } ``` ### Error Handling Listen for the `error` event. Example: ```js const klaw = require('klaw') klaw('/some/dir') .on('readable', function () { let item while ((item = this.read())) { // do something with the file } }) .on('error', (err, item) => { console.log(err.message) console.log(item.path) // the file the error occurred on }) .on('end', () => console.dir(items)) // => [ ... array of files] ``` ### Aggregation / Filtering / Executing Actions (Through Streams) On many occasions you may want to filter files based upon size, extension, etc. Or you may want to aggregate stats on certain file types. Or maybe you want to perform an action on certain file types. You should use the module [`through2`](https://www.npmjs.com/package/through2) to easily accomplish this. Install `through2`: npm i --save through2 **Example (skipping directories):** ```js const klaw = require('klaw') const through2 = require('through2') const excludeDirFilter = through2.obj(function (item, enc, next) { if (!item.stats.isDirectory()) this.push(item) next() }) const items = [] // files, directories, symlinks, etc klaw('/some/dir') .pipe(excludeDirFilter) .on('data', item => items.push(item.path)) .on('end', () => console.dir(items)) // => [ ... array of files without directories] ``` **Example (ignore hidden directories):** ```js const klaw = require('klaw') const path = require('path') const filterFunc = item => { const basename = path.basename(item) return basename === '.' || basename[0] !== '.' } klaw('/some/dir', { filter: filterFunc }) .on('data', item => { // only items of none hidden folders will reach here }) ``` **Example (totaling size of PNG files):** ```js const klaw = require('klaw') const path = require('path') const through2 = require('through2') let totalPngsInBytes = 0 const aggregatePngSize = through2.obj(function (item, enc, next) { if (path.extname(item.path) === '.png') { totalPngsInBytes += item.stats.size } this.push(item) next() }) klaw('/some/dir') .pipe(aggregatePngSize) .on('data', item => items.push(item.path)) .on('end', () => console.dir(totalPngsInBytes)) // => total of all pngs (bytes) ``` **Example (deleting all .tmp files):** ```js const fs = require('fs') const klaw = require('klaw') const through2 = require('through2') const deleteAction = through2.obj(function (item, enc, next) { this.push(item) if (path.extname(item.path) === '.tmp') { item.deleted = true fs.unlink(item.path, next) } else { item.deleted = false next() } }) const deletedFiles = [] klaw('/some/dir') .pipe(deleteAction) .on('data', item => { if (!item.deleted) return deletedFiles.push(item.path) }) .on('end', () => console.dir(deletedFiles)) // => all deleted files ``` You can even chain a bunch of these filters and aggregators together. By using multiple pipes. **Example (using multiple filters / aggregators):** ```js klaw('/some/dir') .pipe(filterCertainFiles) .pipe(deleteSomeOtherFiles) .on('end', () => console.log('all done!')) ``` **Example passing (piping) through errors:** Node.js does not `pipe()` errors. This means that the error on one stream, like `klaw` will not pipe through to the next. If you want to do this, do the following: ```js const klaw = require('klaw') const through2 = require('through2') const excludeDirFilter = through2.obj(function (item, enc, next) { if (!item.stats.isDirectory()) this.push(item) next() }) const items = [] // files, directories, symlinks, etc klaw('/some/dir') .on('error', err => excludeDirFilter.emit('error', err)) // forward the error on .pipe(excludeDirFilter) .on('data', item => items.push(item.path)) .on('end', () => console.dir(items)) // => [ ... array of files without directories] ``` ### Searching Strategy Pass in options for `queueMethod`, `pathSorter`, and `depthLimit` to affect how the file system is recursively iterated. See the code for more details, it's less than 50 lines :) License ------- MIT Copyright (c) 2015 [JP Richardson](https://github.com/jprichardson)
{'content_hash': 'c40fc12d4ab5dceefb1c12fadbedf6c9', 'timestamp': '', 'source': 'github', 'line_count': 261, 'max_line_length': 273, 'avg_line_length': 29.448275862068964, 'alnum_prop': 0.6731720010408535, 'repo_name': 'jprichardson/node-klaw', 'id': '58639696d86cee533eac91a2beb816ce134ce8a3', 'size': '7686', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '11194'}]}
``` diff +namespace System.Drawing.Printing { + public enum Duplex { + Default = -1, + Horizontal = 3, + Simplex = 1, + Vertical = 2, + } + public class InvalidPrinterException : SystemException { + public InvalidPrinterException(PrinterSettings settings); + protected InvalidPrinterException(SerializationInfo info, StreamingContext context); + public override void GetObjectData(SerializationInfo info, StreamingContext context); + } + public class Margins : ICloneable { + public Margins(); + public Margins(int left, int right, int top, int bottom); + public int Bottom { get; set; } + public int Left { get; set; } + public int Right { get; set; } + public int Top { get; set; } + public object Clone(); + public override bool Equals(object obj); + public override int GetHashCode(); + public static bool operator ==(Margins m1, Margins m2); + public static bool operator !=(Margins m1, Margins m2); + public override string ToString(); + } + public class PageSettings : ICloneable { + public PageSettings(); + public PageSettings(PrinterSettings printerSettings); + public Rectangle Bounds { get; } + public bool Color { get; set; } + public float HardMarginX { get; } + public float HardMarginY { get; } + public bool Landscape { get; set; } + public Margins Margins { get; set; } + public PaperSize PaperSize { get; set; } + public PaperSource PaperSource { get; set; } + public RectangleF PrintableArea { get; } + public PrinterResolution PrinterResolution { get; set; } + public PrinterSettings PrinterSettings { get; set; } + public object Clone(); + public void CopyToHdevmode(IntPtr hdevmode); + public void SetHdevmode(IntPtr hdevmode); + public override string ToString(); + } + public enum PaperKind { + A2 = 66, + A3 = 8, + A3Extra = 63, + A3ExtraTransverse = 68, + A3Rotated = 76, + A3Transverse = 67, + A4 = 9, + A4Extra = 53, + A4Plus = 60, + A4Rotated = 77, + A4Small = 10, + A4Transverse = 55, + A5 = 11, + A5Extra = 64, + A5Rotated = 78, + A5Transverse = 61, + A6 = 70, + A6Rotated = 83, + APlus = 57, + B4 = 12, + B4Envelope = 33, + B4JisRotated = 79, + B5 = 13, + B5Envelope = 34, + B5Extra = 65, + B5JisRotated = 80, + B5Transverse = 62, + B6Envelope = 35, + B6Jis = 88, + B6JisRotated = 89, + BPlus = 58, + C3Envelope = 29, + C4Envelope = 30, + C5Envelope = 28, + C65Envelope = 32, + C6Envelope = 31, + CSheet = 24, + Custom = 0, + DLEnvelope = 27, + DSheet = 25, + ESheet = 26, + Executive = 7, + Folio = 14, + GermanLegalFanfold = 41, + GermanStandardFanfold = 40, + InviteEnvelope = 47, + IsoB4 = 42, + ItalyEnvelope = 36, + JapaneseDoublePostcard = 69, + JapaneseDoublePostcardRotated = 82, + JapaneseEnvelopeChouNumber3 = 73, + JapaneseEnvelopeChouNumber3Rotated = 86, + JapaneseEnvelopeChouNumber4 = 74, + JapaneseEnvelopeChouNumber4Rotated = 87, + JapaneseEnvelopeKakuNumber2 = 71, + JapaneseEnvelopeKakuNumber2Rotated = 84, + JapaneseEnvelopeKakuNumber3 = 72, + JapaneseEnvelopeKakuNumber3Rotated = 85, + JapaneseEnvelopeYouNumber4 = 91, + JapaneseEnvelopeYouNumber4Rotated = 92, + JapanesePostcard = 43, + JapanesePostcardRotated = 81, + Ledger = 4, + Legal = 5, + LegalExtra = 51, + Letter = 1, + LetterExtra = 50, + LetterExtraTransverse = 56, + LetterPlus = 59, + LetterRotated = 75, + LetterSmall = 2, + LetterTransverse = 54, + MonarchEnvelope = 37, + Note = 18, + Number10Envelope = 20, + Number11Envelope = 21, + Number12Envelope = 22, + Number14Envelope = 23, + Number9Envelope = 19, + PersonalEnvelope = 38, + Prc16K = 93, + Prc16KRotated = 106, + Prc32K = 94, + Prc32KBig = 95, + Prc32KBigRotated = 108, + Prc32KRotated = 107, + PrcEnvelopeNumber1 = 96, + PrcEnvelopeNumber10 = 105, + PrcEnvelopeNumber10Rotated = 118, + PrcEnvelopeNumber1Rotated = 109, + PrcEnvelopeNumber2 = 97, + PrcEnvelopeNumber2Rotated = 110, + PrcEnvelopeNumber3 = 98, + PrcEnvelopeNumber3Rotated = 111, + PrcEnvelopeNumber4 = 99, + PrcEnvelopeNumber4Rotated = 112, + PrcEnvelopeNumber5 = 100, + PrcEnvelopeNumber5Rotated = 113, + PrcEnvelopeNumber6 = 101, + PrcEnvelopeNumber6Rotated = 114, + PrcEnvelopeNumber7 = 102, + PrcEnvelopeNumber7Rotated = 115, + PrcEnvelopeNumber8 = 103, + PrcEnvelopeNumber8Rotated = 116, + PrcEnvelopeNumber9 = 104, + PrcEnvelopeNumber9Rotated = 117, + Quarto = 15, + Standard10x11 = 45, + Standard10x14 = 16, + Standard11x17 = 17, + Standard12x11 = 90, + Standard15x11 = 46, + Standard9x11 = 44, + Statement = 6, + Tabloid = 3, + TabloidExtra = 52, + USStandardFanfold = 39, + } + public class PaperSize { + public PaperSize(); + public PaperSize(string name, int width, int height); + public int Height { get; set; } + public PaperKind Kind { get; } + public string PaperName { get; set; } + public int RawKind { get; set; } + public int Width { get; set; } + public override string ToString(); + } + public class PaperSource { + public PaperSource(); + public PaperSourceKind Kind { get; } + public int RawKind { get; set; } + public string SourceName { get; set; } + public override string ToString(); + } + public enum PaperSourceKind { + AutomaticFeed = 7, + Cassette = 14, + Custom = 257, + Envelope = 5, + FormSource = 15, + LargeCapacity = 11, + LargeFormat = 10, + Lower = 2, + Manual = 4, + ManualFeed = 6, + Middle = 3, + SmallFormat = 9, + TractorFeed = 8, + Upper = 1, + } + public sealed class PreviewPageInfo { + public PreviewPageInfo(Image image, Size physicalSize); + public Image Image { get; } + public Size PhysicalSize { get; } + } + public class PreviewPrintController : PrintController { + public PreviewPrintController(); + public override bool IsPreview { get; } + public virtual bool UseAntiAlias { get; set; } + public PreviewPageInfo[] GetPreviewPageInfo(); + public override void OnEndPage(PrintDocument document, PrintPageEventArgs e); + public override void OnEndPrint(PrintDocument document, PrintEventArgs e); + public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e); + public override void OnStartPrint(PrintDocument document, PrintEventArgs e); + } + public enum PrintAction { + PrintToFile = 0, + PrintToPreview = 1, + PrintToPrinter = 2, + } + public abstract class PrintController { + protected PrintController(); + public virtual bool IsPreview { get; } + public virtual void OnEndPage(PrintDocument document, PrintPageEventArgs e); + public virtual void OnEndPrint(PrintDocument document, PrintEventArgs e); + public virtual Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e); + public virtual void OnStartPrint(PrintDocument document, PrintEventArgs e); + } + public class PrintDocument : Component { + public PrintDocument(); + public PageSettings DefaultPageSettings { get; set; } + public string DocumentName { get; set; } + public bool OriginAtMargins { get; set; } + public PrintController PrintController { get; set; } + public PrinterSettings PrinterSettings { get; set; } + public event PrintEventHandler BeginPrint; + public event PrintEventHandler EndPrint; + public event PrintPageEventHandler PrintPage; + public event QueryPageSettingsEventHandler QueryPageSettings; + protected virtual void OnBeginPrint(PrintEventArgs e); + protected virtual void OnEndPrint(PrintEventArgs e); + protected virtual void OnPrintPage(PrintPageEventArgs e); + protected virtual void OnQueryPageSettings(QueryPageSettingsEventArgs e); + public void Print(); + public override string ToString(); + } + public class PrinterResolution { + public PrinterResolution(); + public PrinterResolutionKind Kind { get; set; } + public int X { get; set; } + public int Y { get; set; } + public override string ToString(); + } + public enum PrinterResolutionKind { + Custom = 0, + Draft = -1, + High = -4, + Low = -2, + Medium = -3, + } + public class PrinterSettings : ICloneable { + public PrinterSettings(); + public bool CanDuplex { get; } + public bool Collate { get; set; } + public short Copies { get; set; } + public PageSettings DefaultPageSettings { get; } + public Duplex Duplex { get; set; } + public int FromPage { get; set; } + public static PrinterSettings.StringCollection InstalledPrinters { get; } + public bool IsDefaultPrinter { get; } + public bool IsPlotter { get; } + public bool IsValid { get; } + public int LandscapeAngle { get; } + public int MaximumCopies { get; } + public int MaximumPage { get; set; } + public int MinimumPage { get; set; } + public PrinterSettings.PaperSizeCollection PaperSizes { get; } + public PrinterSettings.PaperSourceCollection PaperSources { get; } + public string PrinterName { get; set; } + public PrinterSettings.PrinterResolutionCollection PrinterResolutions { get; } + public string PrintFileName { get; set; } + public PrintRange PrintRange { get; set; } + public bool PrintToFile { get; set; } + public bool SupportsColor { get; } + public int ToPage { get; set; } + public object Clone(); + public Graphics CreateMeasurementGraphics(); + public Graphics CreateMeasurementGraphics(bool honorOriginAtMargins); + public Graphics CreateMeasurementGraphics(PageSettings pageSettings); + public Graphics CreateMeasurementGraphics(PageSettings pageSettings, bool honorOriginAtMargins); + public IntPtr GetHdevmode(); + public IntPtr GetHdevmode(PageSettings pageSettings); + public IntPtr GetHdevnames(); + public bool IsDirectPrintingSupported(Image image); + public bool IsDirectPrintingSupported(ImageFormat imageFormat); + public void SetHdevmode(IntPtr hdevmode); + public void SetHdevnames(IntPtr hdevnames); + public override string ToString(); + public class PaperSizeCollection : ICollection, IEnumerable { + public PaperSizeCollection(PaperSize[] array); + public int Count { get; } + int System.Collections.ICollection.Count { get; } + bool System.Collections.ICollection.IsSynchronized { get; } + object System.Collections.ICollection.SyncRoot { get; } + public virtual PaperSize this[int index] { get; } + public int Add(PaperSize paperSize); + public void CopyTo(PaperSize[] paperSizes, int index); + public IEnumerator GetEnumerator(); + void System.Collections.ICollection.CopyTo(Array array, int index); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + public class PaperSourceCollection : ICollection, IEnumerable { + public PaperSourceCollection(PaperSource[] array); + public int Count { get; } + int System.Collections.ICollection.Count { get; } + bool System.Collections.ICollection.IsSynchronized { get; } + object System.Collections.ICollection.SyncRoot { get; } + public virtual PaperSource this[int index] { get; } + public int Add(PaperSource paperSource); + public void CopyTo(PaperSource[] paperSources, int index); + public IEnumerator GetEnumerator(); + void System.Collections.ICollection.CopyTo(Array array, int index); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + public class PrinterResolutionCollection : ICollection, IEnumerable { + public PrinterResolutionCollection(PrinterResolution[] array); + public int Count { get; } + int System.Collections.ICollection.Count { get; } + bool System.Collections.ICollection.IsSynchronized { get; } + object System.Collections.ICollection.SyncRoot { get; } + public virtual PrinterResolution this[int index] { get; } + public int Add(PrinterResolution printerResolution); + public void CopyTo(PrinterResolution[] printerResolutions, int index); + public IEnumerator GetEnumerator(); + void System.Collections.ICollection.CopyTo(Array array, int index); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + public class StringCollection : ICollection, IEnumerable { + public StringCollection(string[] array); + public int Count { get; } + int System.Collections.ICollection.Count { get; } + bool System.Collections.ICollection.IsSynchronized { get; } + object System.Collections.ICollection.SyncRoot { get; } + public virtual string this[int index] { get; } + public int Add(string value); + public void CopyTo(string[] strings, int index); + public IEnumerator GetEnumerator(); + void System.Collections.ICollection.CopyTo(Array array, int index); + IEnumerator System.Collections.IEnumerable.GetEnumerator(); + } + } + public enum PrinterUnit { + Display = 0, + HundredthsOfAMillimeter = 2, + TenthsOfAMillimeter = 3, + ThousandthsOfAnInch = 1, + } + public sealed class PrinterUnitConvert { + public static double Convert(double value, PrinterUnit fromUnit, PrinterUnit toUnit); + public static Point Convert(Point value, PrinterUnit fromUnit, PrinterUnit toUnit); + public static Margins Convert(Margins value, PrinterUnit fromUnit, PrinterUnit toUnit); + public static Rectangle Convert(Rectangle value, PrinterUnit fromUnit, PrinterUnit toUnit); + public static Size Convert(Size value, PrinterUnit fromUnit, PrinterUnit toUnit); + public static int Convert(int value, PrinterUnit fromUnit, PrinterUnit toUnit); + } + public class PrintEventArgs : CancelEventArgs { + public PrintEventArgs(); + public PrintAction PrintAction { get; } + } + public delegate void PrintEventHandler(object sender, PrintEventArgs e); + public sealed class PrintingPermission : CodeAccessPermission, IUnrestrictedPermission { + public PrintingPermission(PrintingPermissionLevel printingLevel); + public PrintingPermission(PermissionState state); + public PrintingPermissionLevel Level { get; set; } + public override IPermission Copy(); + public override void FromXml(SecurityElement element); + public override IPermission Intersect(IPermission target); + public override bool IsSubsetOf(IPermission target); + public bool IsUnrestricted(); + public override SecurityElement ToXml(); + public override IPermission Union(IPermission target); + } + public sealed class PrintingPermissionAttribute : CodeAccessSecurityAttribute { + public PrintingPermissionAttribute(SecurityAction action); + public PrintingPermissionLevel Level { get; set; } + public override IPermission CreatePermission(); + } + public enum PrintingPermissionLevel { + AllPrinting = 3, + DefaultPrinting = 2, + NoPrinting = 0, + SafePrinting = 1, + } + public class PrintPageEventArgs : EventArgs { + public PrintPageEventArgs(Graphics graphics, Rectangle marginBounds, Rectangle pageBounds, PageSettings pageSettings); + public bool Cancel { get; set; } + public Graphics Graphics { get; } + public bool HasMorePages { get; set; } + public Rectangle MarginBounds { get; } + public Rectangle PageBounds { get; } + public PageSettings PageSettings { get; } + } + public delegate void PrintPageEventHandler(object sender, PrintPageEventArgs e); + public enum PrintRange { + AllPages = 0, + CurrentPage = 4194304, + Selection = 1, + SomePages = 2, + } + public class QueryPageSettingsEventArgs : PrintEventArgs { + public QueryPageSettingsEventArgs(PageSettings pageSettings); + public PageSettings PageSettings { get; set; } + } + public delegate void QueryPageSettingsEventHandler(object sender, QueryPageSettingsEventArgs e); + public class StandardPrintController : PrintController { + public StandardPrintController(); + public override void OnEndPage(PrintDocument document, PrintPageEventArgs e); + public override void OnEndPrint(PrintDocument document, PrintEventArgs e); + public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e); + public override void OnStartPrint(PrintDocument document, PrintEventArgs e); + } +} ```
{'content_hash': 'e1fc4d3ca5e16fbf35837899d48cd483', 'timestamp': '', 'source': 'github', 'line_count': 422, 'max_line_length': 127, 'avg_line_length': 42.86492890995261, 'alnum_prop': 0.6315993145005252, 'repo_name': 'ericstj/standard', 'id': '243b64840b63c39b6fa170dde097b3b34bf51c31', 'size': '18116', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'docs/comparisons/netstandard2.0_vs_netcoreapp2.0/System.Drawing.Printing.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '11626'}, {'name': 'C#', 'bytes': '24604928'}, {'name': 'CMake', 'bytes': '9153'}, {'name': 'PowerShell', 'bytes': '69131'}, {'name': 'Shell', 'bytes': '64844'}]}
using System; using System.IO; using Dapper; using Newtonsoft.Json; namespace SteamDatabaseBackend { static class Settings { private static SettingsJson _current = new SettingsJson(); public static bool IsFullRun { get; private set; } public static SettingsJson Current { get { return _current; } } public static void Load() { string settingsFile = Path.Combine(Application.Path, "settings.json"); if (!File.Exists(settingsFile)) { throw new FileNotFoundException("settings.json file does not exist. Rename and edit settings.json.default file."); } _current = JsonConvert.DeserializeObject<SettingsJson>(File.ReadAllText(settingsFile), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }) ?? new SettingsJson(); } public static void Initialize() { if (string.IsNullOrWhiteSpace(Current.Steam.Username) || string.IsNullOrWhiteSpace(Current.Steam.Password)) { throw new InvalidDataException("Missing Steam credentials in settings file"); } // Test database connection, it will throw if connection is unable to be made using (var connection = Database.GetConnection()) { // Clear GC status table while we're at it connection.Execute("DELETE FROM `GC`"); } if (Current.FullRun != FullRunState.None) { IsFullRun = true; Log.WriteInfo("Settings", "Running full update with option \"{0}\"", Current.FullRun); // Don't log full runs, regardless of setting Current.LogToFile = false; // Don't connect to IRC while doing a full run Current.IRC.Enabled = false; } else if (!Current.LogToFile) { Log.WriteInfo("Settings", "File logging is disabled"); } Current.IRC.Enabled = CanConnectToIRC(); } private static bool CanConnectToIRC() { if (!Current.IRC.Enabled) { Log.WriteWarn("Settings", "IRC is disabled in settings"); return false; } if (string.IsNullOrEmpty(Current.IRC.Server) || Current.IRC.Port <= 0) { Log.WriteWarn("Settings", "Missing IRC details in settings file, not connecting"); return false; } if (string.IsNullOrWhiteSpace(Current.IRC.Nickname)) { Log.WriteError("Settings", "Missing IRC nickname in settings file, not connecting"); return false; } if (string.IsNullOrWhiteSpace(Current.IRC.Password)) { Current.IRC.Password = null; } return true; } } }
{'content_hash': 'e61ab38354f48856c25bb877b19e8cbd', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 205, 'avg_line_length': 31.20408163265306, 'alnum_prop': 0.5464355788096795, 'repo_name': 'SGColdSun/SteamDatabaseBackend', 'id': '70755525e2a0bc01e3cf4d62208a44cce04e2600', 'size': '3226', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Util/Settings.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '284296'}, {'name': 'Shell', 'bytes': '452'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.robust.norms.LeastSquares.psi_deriv &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/_sphinx_javascript_frameworks_compat.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sphinx_highlight.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.robust.norms.LeastSquares.rho" href="statsmodels.robust.norms.LeastSquares.rho.html" /> <link rel="prev" title="statsmodels.robust.norms.LeastSquares.psi" href="statsmodels.robust.norms.LeastSquares.psi.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.robust.norms.LeastSquares.psi_deriv" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels 0.13.3</span> <span class="md-header-nav__topic"> statsmodels.robust.norms.LeastSquares.psi_deriv </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../rlm.html" class="md-tabs__link">Robust Linear Models</a></li> <li class="md-tabs__item"><a href="statsmodels.robust.norms.LeastSquares.html" class="md-tabs__link">statsmodels.robust.norms.LeastSquares</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels 0.13.3</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li> <li class="md-nav__item"> <a href="../other_models.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">othermod</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#generated-statsmodels-robust-norms-leastsquares-psi-deriv--page-root" class="md-nav__link">statsmodels.robust.norms.LeastSquares.psi_deriv</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#statsmodels.robust.norms.LeastSquares.psi_deriv" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">LeastSquares.psi_deriv</span></code></a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.robust.norms.LeastSquares.psi_deriv.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-robust-norms-leastsquares-psi-deriv"> <h1 id="generated-statsmodels-robust-norms-leastsquares-psi-deriv--page-root">statsmodels.robust.norms.LeastSquares.psi_deriv<a class="headerlink" href="#generated-statsmodels-robust-norms-leastsquares-psi-deriv--page-root" title="Permalink to this heading">¶</a></h1> <dl class="py method"> <dt class="sig sig-object py" id="statsmodels.robust.norms.LeastSquares.psi_deriv"> <span class="sig-prename descclassname"><span class="pre">LeastSquares.</span></span><span class="sig-name descname"><span class="pre">psi_deriv</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">z</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/robust/norms.html#LeastSquares.psi_deriv"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.robust.norms.LeastSquares.psi_deriv" title="Permalink to this definition">¶</a></dt> <dd><p>The derivative of the least squares psi function.</p> <dl class="field-list"> <dt class="field-odd">Returns<span class="colon">:</span></dt> <dd class="field-odd"><dl> <dt><strong>psi_deriv</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v1.23)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndarray</span></code></a></span></dt><dd><p>ones(z.shape)</p> </dd> </dl> </dd> </dl> <p class="rubric">Notes</p> <p>Used to estimate the robust covariance matrix.</p> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.robust.norms.LeastSquares.psi.html" title="statsmodels.robust.norms.LeastSquares.psi" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.robust.norms.LeastSquares.psi </span> </div> </a> <a href="statsmodels.robust.norms.LeastSquares.rho.html" title="statsmodels.robust.norms.LeastSquares.rho" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.robust.norms.LeastSquares.rho </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Nov 01, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{'content_hash': '58fcb59dcb5ad9b3b04449f825a38840', 'timestamp': '', 'source': 'github', 'line_count': 516, 'max_line_length': 999, 'avg_line_length': 38.27713178294574, 'alnum_prop': 0.5973874740519467, 'repo_name': 'statsmodels/statsmodels.github.io', 'id': 'bc44c2fca922ef0db0d780919012801fd87b3e05', 'size': '19755', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'v0.13.3/generated/statsmodels.robust.norms.LeastSquares.psi_deriv.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
using System; using CVaS.BL.Common; using CVaS.Shared.Options; using CVaS.Shared.Helpers; using CVaS.Web.Authentication; using CVaS.Web.Installers; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.PlatformAbstractions; using DryIoc; using DryIoc.Microsoft.DependencyInjection; using StackExchange.Profiling.Storage; using Microsoft.Extensions.Caching.Memory; using CVaS.Web.Helpers; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using CVaS.Web.Swagger; namespace CVaS.Web { public class Startup { private readonly IHostingEnvironment _hostingEnvironment; private readonly ModeOptions _modeOptions = new ModeOptions(); public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory) { Configuration = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables() .Build(); loggerFactory .AddConsole(Configuration.GetSection("Logging")) .AddDebug(); _hostingEnvironment = env; } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddCustomOptions(Configuration); Configuration.GetSection("Mode").Bind(_modeOptions); services.AddCustomizedIdentity(); services.AddApiAuthentication(option => { option.AuthenticationScheme = AuthenticationSchemes.ApiKey; option.HeaderScheme = "Simple"; }); services.AddDatabaseServices(Configuration); services.AddStorageServices(Configuration); services.AddCustomizedMvc(); services.AddMemoryCache(); // Inject an implementation of ISwaggerProvider with defaulted settings applied services.AddSwaggerGen(ConfigureSwagger); services.AddMiniProfiler(); //.AddEntityFramework(); if (_modeOptions.IsLocal) { services.AddJobsService(Configuration); } else { services.AddMessageBroker(Configuration); } services.AddTransient<AppContextSeed>(); services.AddSingleton(Configuration); var physicalProvider = _hostingEnvironment.ContentRootFileProvider; // It's null when using ef migrations tools so we need to check first to not to throw exc if (physicalProvider != null) services.AddSingleton(physicalProvider); return new Container(Rules.Default .WithCaptureContainerDisposeStackTrace() .WithoutThrowIfDependencyHasShorterReuseLifespan() .WithImplicitRootOpenScope()) .WithDependencyInjectionAdapter(services, throwIfUnresolved: type => type.Name.EndsWith("Controller")) .ConfigureServiceProvider<WebApiCompositionRoot>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMemoryCache cache, IContainer container) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); if (env.IsDevelopment()) { app.UseMiniProfiler(o => { o.RouteBasePath = "~/profiler"; o.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(); o.Storage = new MemoryCacheStorage(cache, TimeSpan.FromMinutes(20)); }); } app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); c.InjectStylesheet("/lib/swagger-ui-themes/themes/2.x/theme-flattop.css"); }); if (_modeOptions.IsLocal) { ServicesExtensions.InitializeJobs(container); } } private static void ConfigureSwagger(SwaggerGenOptions options) { options.SwaggerDoc("v1", new Info { Version = "v1", Title = "Computer Vision as Service API", Description = "A simple api to run computer vision algorithms.", TermsOfService = "None", Contact = new Contact { Name = "Adam Jež", Email = "[email protected]" } }); options.AddSecurityDefinition("ApiKey", new ApiKeyScheme() { In = "header", Name = "Authorization", Description = "Api Key Authentication", Type = "apiKey" }); options.DocumentFilter<LowercaseDocumentFilter>(); options.OperationFilter<AuthResponsesOperationFilter>(); options.OperationFilter<AddFileParamsFilter>(); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var pathToDoc = System.IO.Path.Combine(basePath, "CVaS.Web.xml"); options.IncludeXmlComments(pathToDoc); } } }
{'content_hash': 'b8679b2703f2562dc9ae00b6419dd1be', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 124, 'avg_line_length': 37.34117647058824, 'alnum_prop': 0.5956206679269062, 'repo_name': 'adamjez/CVaS', 'id': '6d110356d3484513441e444b33569c6c5742a253', 'size': '6351', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/CVaS.Web/Startup.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '350481'}, {'name': 'CSS', 'bytes': '4863'}, {'name': 'JavaScript', 'bytes': '9750'}, {'name': 'PowerShell', 'bytes': '50183'}, {'name': 'Shell', 'bytes': '870'}]}
namespace dp2Circulation { partial class DupForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } this.EventFinish.Dispose(); base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DupForm)); this.label_dupMessage = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBox_recordPath = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.listView_browse = new DigitalPlatform.GUI.ListViewNF(); this.columnHeader_path = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader_sum = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.imageList_dupItemType = new System.Windows.Forms.ImageList(this.components); this.label_message = new System.Windows.Forms.Label(); this.button_search = new System.Windows.Forms.Button(); this.comboBox_projectName = new System.Windows.Forms.ComboBox(); this.button_viewXmlRecord = new System.Windows.Forms.Button(); this.checkBox_includeLowCols = new System.Windows.Forms.CheckBox(); this.checkBox_returnAllRecords = new System.Windows.Forms.CheckBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.checkBox_returnSearchDetail = new System.Windows.Forms.CheckBox(); this.tableLayoutPanel1.SuspendLayout(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.panel3.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // label_dupMessage // this.label_dupMessage.AutoSize = true; this.label_dupMessage.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label_dupMessage.Location = new System.Drawing.Point(3, 425); this.label_dupMessage.Name = "label_dupMessage"; this.label_dupMessage.Size = new System.Drawing.Size(114, 18); this.label_dupMessage.TabIndex = 1; this.label_dupMessage.Text = "尚未查重..."; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(3, 3); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(116, 18); this.label2.TabIndex = 0; this.label2.Text = "查重方案(&P):"; // // textBox_recordPath // this.textBox_recordPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_recordPath.Location = new System.Drawing.Point(142, -2); this.textBox_recordPath.Name = "textBox_recordPath"; this.textBox_recordPath.Size = new System.Drawing.Size(268, 28); this.textBox_recordPath.TabIndex = 1; this.textBox_recordPath.TextChanged += new System.EventHandler(this.textBox_recordPath_TextChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 3); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(134, 18); this.label1.TabIndex = 0; this.label1.Text = "源记录路径(&P):"; // // listView_browse // this.listView_browse.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader_path, this.columnHeader_sum}); this.listView_browse.Dock = System.Windows.Forms.DockStyle.Left; this.listView_browse.FullRowSelect = true; this.listView_browse.HideSelection = false; this.listView_browse.LargeImageList = this.imageList_dupItemType; this.listView_browse.Location = new System.Drawing.Point(0, 72); this.listView_browse.Margin = new System.Windows.Forms.Padding(0); this.listView_browse.Name = "listView_browse"; this.listView_browse.Size = new System.Drawing.Size(451, 303); this.listView_browse.SmallImageList = this.imageList_dupItemType; this.listView_browse.TabIndex = 0; this.listView_browse.UseCompatibleStateImageBehavior = false; this.listView_browse.View = System.Windows.Forms.View.Details; this.listView_browse.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listView_browse_ColumnClick); this.listView_browse.SelectedIndexChanged += new System.EventHandler(this.listView_browse_SelectedIndexChanged); this.listView_browse.DoubleClick += new System.EventHandler(this.listView_browse_DoubleClick); this.listView_browse.MouseUp += new System.Windows.Forms.MouseEventHandler(this.listView_browse_MouseUp); // // columnHeader_path // this.columnHeader_path.Text = "记录路径"; this.columnHeader_path.Width = 120; // // columnHeader_sum // this.columnHeader_sum.Text = "权值和"; this.columnHeader_sum.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.columnHeader_sum.Width = 70; // // imageList_dupItemType // this.imageList_dupItemType.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList_dupItemType.ImageStream"))); this.imageList_dupItemType.TransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.imageList_dupItemType.Images.SetKeyName(0, "undup_type.bmp"); this.imageList_dupItemType.Images.SetKeyName(1, "dup_type.bmp"); // // label_message // this.label_message.AutoSize = true; this.label_message.Location = new System.Drawing.Point(3, 443); this.label_message.Name = "label_message"; this.label_message.Size = new System.Drawing.Size(17, 18); this.label_message.TabIndex = 2; this.label_message.Text = " "; // // button_search // this.button_search.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button_search.Location = new System.Drawing.Point(418, 0); this.button_search.Name = "button_search"; this.button_search.Size = new System.Drawing.Size(112, 33); this.button_search.TabIndex = 2; this.button_search.Text = "查重(&S)"; this.button_search.Click += new System.EventHandler(this.button_search_Click); // // comboBox_projectName // this.comboBox_projectName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboBox_projectName.FormattingEnabled = true; this.comboBox_projectName.Location = new System.Drawing.Point(142, 3); this.comboBox_projectName.Name = "comboBox_projectName"; this.comboBox_projectName.Size = new System.Drawing.Size(268, 26); this.comboBox_projectName.TabIndex = 1; this.comboBox_projectName.DropDown += new System.EventHandler(this.comboBox_projectName_DropDown); // // button_viewXmlRecord // this.button_viewXmlRecord.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button_viewXmlRecord.Location = new System.Drawing.Point(418, 0); this.button_viewXmlRecord.Name = "button_viewXmlRecord"; this.button_viewXmlRecord.Size = new System.Drawing.Size(112, 33); this.button_viewXmlRecord.TabIndex = 2; this.button_viewXmlRecord.Text = "XML..."; this.button_viewXmlRecord.UseVisualStyleBackColor = true; this.button_viewXmlRecord.Click += new System.EventHandler(this.button_viewXmlRecord_Click); // // checkBox_includeLowCols // this.checkBox_includeLowCols.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.checkBox_includeLowCols.AutoSize = true; this.checkBox_includeLowCols.Location = new System.Drawing.Point(4, 4); this.checkBox_includeLowCols.Margin = new System.Windows.Forms.Padding(4); this.checkBox_includeLowCols.Name = "checkBox_includeLowCols"; this.checkBox_includeLowCols.Size = new System.Drawing.Size(295, 22); this.checkBox_includeLowCols.TabIndex = 0; this.checkBox_includeLowCols.Text = "返回低于阈值的记录的浏览列(&B)"; this.checkBox_includeLowCols.UseVisualStyleBackColor = true; // // checkBox_returnAllRecords // this.checkBox_returnAllRecords.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.checkBox_returnAllRecords.AutoSize = true; this.checkBox_returnAllRecords.Location = new System.Drawing.Point(307, 4); this.checkBox_returnAllRecords.Margin = new System.Windows.Forms.Padding(4); this.checkBox_returnAllRecords.Name = "checkBox_returnAllRecords"; this.checkBox_returnAllRecords.Size = new System.Drawing.Size(205, 22); this.checkBox_returnAllRecords.TabIndex = 1; this.checkBox_returnAllRecords.Text = "返回全部命中记录(&A)"; this.checkBox_returnAllRecords.UseVisualStyleBackColor = true; // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSize = true; this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.label_dupMessage, 0, 4); this.tableLayoutPanel1.Controls.Add(this.panel2, 0, 1); this.tableLayoutPanel1.Controls.Add(this.listView_browse, 0, 2); this.tableLayoutPanel1.Controls.Add(this.label_message, 0, 5); this.tableLayoutPanel1.Controls.Add(this.panel3, 0, 3); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(4); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 7; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 3F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(534, 464); this.tableLayoutPanel1.TabIndex = 10; // // panel1 // this.panel1.AutoSize = true; this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.comboBox_projectName); this.panel1.Controls.Add(this.button_search); this.panel1.Dock = System.Windows.Forms.DockStyle.Left; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Margin = new System.Windows.Forms.Padding(0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(848, 36); this.panel1.TabIndex = 0; // // panel2 // this.panel2.AutoSize = true; this.panel2.Controls.Add(this.label1); this.panel2.Controls.Add(this.textBox_recordPath); this.panel2.Controls.Add(this.button_viewXmlRecord); this.panel2.Dock = System.Windows.Forms.DockStyle.Left; this.panel2.Location = new System.Drawing.Point(0, 36); this.panel2.Margin = new System.Windows.Forms.Padding(0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(848, 36); this.panel2.TabIndex = 1; // // panel3 // this.panel3.BackColor = System.Drawing.SystemColors.Control; this.panel3.Controls.Add(this.flowLayoutPanel1); this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; this.panel3.Location = new System.Drawing.Point(0, 375); this.panel3.Margin = new System.Windows.Forms.Padding(0); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(848, 50); this.panel3.TabIndex = 7; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.checkBox_includeLowCols); this.flowLayoutPanel1.Controls.Add(this.checkBox_returnAllRecords); this.flowLayoutPanel1.Controls.Add(this.checkBox_returnSearchDetail); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(848, 50); this.flowLayoutPanel1.TabIndex = 2; // // checkBox_returnSearchDetail // this.checkBox_returnSearchDetail.AutoSize = true; this.checkBox_returnSearchDetail.Location = new System.Drawing.Point(519, 3); this.checkBox_returnSearchDetail.Name = "checkBox_returnSearchDetail"; this.checkBox_returnSearchDetail.Size = new System.Drawing.Size(169, 22); this.checkBox_returnSearchDetail.TabIndex = 2; this.checkBox_returnSearchDetail.Text = "返回检索详情(&S)"; this.checkBox_returnSearchDetail.UseVisualStyleBackColor = true; // // DupForm // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(534, 464); this.Controls.Add(this.tableLayoutPanel1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "DupForm"; this.ShowInTaskbar = false; this.Text = "DupForm"; this.Activated += new System.EventHandler(this.DupForm_Activated); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DupForm_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.DupForm_FormClosed); this.Load += new System.EventHandler(this.DupForm_Load); this.SizeChanged += new System.EventHandler(this.DupForm_SizeChanged); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.panel3.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label_dupMessage; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox_recordPath; private System.Windows.Forms.Label label1; private DigitalPlatform.GUI.ListViewNF listView_browse; private System.Windows.Forms.ColumnHeader columnHeader_path; private System.Windows.Forms.ColumnHeader columnHeader_sum; private System.Windows.Forms.Label label_message; private System.Windows.Forms.Button button_search; private System.Windows.Forms.ComboBox comboBox_projectName; private System.Windows.Forms.Button button_viewXmlRecord; private System.Windows.Forms.ImageList imageList_dupItemType; private System.Windows.Forms.CheckBox checkBox_includeLowCols; private System.Windows.Forms.CheckBox checkBox_returnAllRecords; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.CheckBox checkBox_returnSearchDetail; } }
{'content_hash': '6ba39200f442244557ede07c8794e97c', 'timestamp': '', 'source': 'github', 'line_count': 343, 'max_line_length': 175, 'avg_line_length': 56.48979591836735, 'alnum_prop': 0.6343414533443436, 'repo_name': 'DigitalPlatform/dp2', 'id': '77363cd47cb9b9ce3ebf0e342b5051e17e57388e', 'size': '19480', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dp2Circulation/Dup/DupForm.Designer.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP.NET', 'bytes': '80547'}, {'name': 'Batchfile', 'bytes': '7192'}, {'name': 'C#', 'bytes': '56347865'}, {'name': 'CSS', 'bytes': '818819'}, {'name': 'HTML', 'bytes': '1914736'}, {'name': 'JavaScript', 'bytes': '152102'}, {'name': 'PHP', 'bytes': '30185'}, {'name': 'Roff', 'bytes': '1879'}, {'name': 'Smalltalk', 'bytes': '48625'}, {'name': 'XSLT', 'bytes': '64230'}]}
<?php /* @WebProfiler/Profiler/base_js.html.twig */ class __TwigTemplate_e7980dfb8bff76e82b49ca15a592b08d8e457a6b35170d5e64a247a3d4b200aa extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<script>/*<![CDATA[*/ Sfjs = (function() { \"use strict\"; var noop = function() {}, profilerStorageKey = 'sf2/profiler/', request = function(url, onSuccess, onError, payload, options) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); options = options || {}; options.maxTries = options.maxTries || 0; xhr.open(options.method || 'GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function(state) { if (4 !== xhr.readyState) { return null; } if (xhr.status == 404 && options.maxTries > 1) { setTimeout(function(){ options.maxTries--; request(url, onSuccess, onError, payload, options); }, 500); return null; } if (200 === xhr.status) { (onSuccess || noop)(xhr); } else { (onError || noop)(xhr); } }; xhr.send(payload || ''); }, hasClass = function(el, klass) { return el.className && el.className.match(new RegExp('\\\\b' + klass + '\\\\b')); }, removeClass = function(el, klass) { if (el.className) { el.className = el.className.replace(new RegExp('\\\\b' + klass + '\\\\b'), ' '); } }, addClass = function(el, klass) { if (!hasClass(el, klass)) { el.className += \" \" + klass; } }, getPreference = function(name) { if (!window.localStorage) { return null; } return localStorage.getItem(profilerStorageKey + name); }, setPreference = function(name, value) { if (!window.localStorage) { return null; } localStorage.setItem(profilerStorageKey + name, value); }, requestStack = [], renderAjaxRequests = function() { var requestCounter = document.querySelectorAll('.sf-toolbar-ajax-requests'); if (!requestCounter.length) { return; } var tbodies = document.querySelectorAll('.sf-toolbar-ajax-request-list'); var state = 'ok'; if (tbodies.length) { var tbody = tbodies[0]; var rows = document.createDocumentFragment(); if (requestStack.length) { for (var i = 0; i < requestStack.length; i++) { var request = requestStack[i]; var row = document.createElement('tr'); rows.appendChild(row); var methodCell = document.createElement('td'); methodCell.textContent = request.method; row.appendChild(methodCell); var pathCell = document.createElement('td'); pathCell.className = 'sf-ajax-request-url'; pathCell.textContent = request.url; pathCell.setAttribute('title', request.url); row.appendChild(pathCell); var durationCell = document.createElement('td'); durationCell.className = 'sf-ajax-request-duration'; if (request.duration) { durationCell.textContent = request.duration + \"ms\"; } else { durationCell.textContent = '-'; } row.appendChild(durationCell); row.appendChild(document.createTextNode(' ')); var profilerCell = document.createElement('td'); if (request.profilerUrl) { var profilerLink = document.createElement('a'); profilerLink.setAttribute('href', request.profilerUrl); profilerLink.textContent = request.profile; profilerCell.appendChild(profilerLink); } else { profilerCell.textContent = 'n/a'; } row.appendChild(profilerCell); var requestState = 'ok'; if (request.error) { requestState = 'error'; if (state != \"loading\" && i > requestStack.length - 4) { state = 'error'; } } else if (request.loading) { requestState = 'loading'; state = 'loading' } row.className = 'sf-ajax-request sf-ajax-request-' + requestState; } var infoSpan = document.querySelectorAll(\".sf-toolbar-ajax-info\")[0]; var children = Array.prototype.slice.call(tbody.children); for (var i = 0; i < children.length; i++) { tbody.removeChild(children[i]); } tbody.appendChild(rows); if (infoSpan) { var text = requestStack.length + ' call' + (requestStack.length > 1 ? 's' : ''); infoSpan.textContent = text; } } else { var cell = document.createElement('td'); cell.setAttribute('colspan', '4'); cell.textContent = \"No AJAX requests yet.\"; var row = document.createElement('tr'); row.appendChild(cell); tbody.appendChild(row); } } requestCounter[0].textContent = requestStack.length; var className = 'sf-toolbar-ajax-requests sf-toolbar-status'; if (state == 'ok') { className += ' sf-toolbar-status-green'; } else if (state == 'error') { className += ' sf-toolbar-status-red'; } else { className += ' sf-ajax-request-loading'; } requestCounter[0].className = className; }; var addEventListener; if (document.attachEvent) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, callback); }; } else { addEventListener = function (element, eventName, callback) { element.addEventListener(eventName, callback, false); }; } "; // line 186 if (array_key_exists("excluded_ajax_paths", $context)) { // line 187 echo " var proxied = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url, async, user, pass) { var self = this; /* prevent logging AJAX calls to static and inline files, like templates */ if (url.substr(0, 1) === '/' && !url.match(new RegExp(\""; // line 193 echo twig_escape_filter($this->env, (isset($context["excluded_ajax_paths"]) ? $context["excluded_ajax_paths"] : $this->getContext($context, "excluded_ajax_paths")), "html", null, true); echo "\"))) { var stackElement = { loading: true, error: false, url: url, method: method, start: new Date() }; requestStack.push(stackElement); addEventListener(this, 'readystatechange', function() { if (self.readyState == 4) { stackElement.duration = new Date() - stackElement.start; stackElement.loading = false; stackElement.error = self.status < 200 || self.status >= 400; stackElement.profile = self.getResponseHeader(\"X-Debug-Token\"); stackElement.profilerUrl = self.getResponseHeader(\"X-Debug-Token-Link\"); Sfjs.renderAjaxRequests(); } }); Sfjs.renderAjaxRequests(); } proxied.apply(this, Array.prototype.slice.call(arguments)); }; "; } // line 222 echo " return { hasClass: hasClass, removeClass: removeClass, addClass: addClass, getPreference: getPreference, setPreference: setPreference, addEventListener: addEventListener, request: request, renderAjaxRequests: renderAjaxRequests, load: function(selector, url, onSuccess, onError, options) { var el = document.getElementById(selector); if (el && el.getAttribute('data-sfurl') !== url) { request( url, function(xhr) { el.innerHTML = xhr.responseText; el.setAttribute('data-sfurl', url); removeClass(el, 'loading'); (onSuccess || noop)(xhr, el); }, function(xhr) { (onError || noop)(xhr, el); }, '', options ); } return this; }, toggle: function(selector, elOn, elOff) { var i, style, tmp = elOn.style.display, el = document.getElementById(selector); elOn.style.display = elOff.style.display; elOff.style.display = tmp; if (el) { el.style.display = 'none' === tmp ? 'none' : 'block'; } return this; } } })(); /*]]>*/</script> "; } public function getTemplateName() { return "@WebProfiler/Profiler/base_js.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 248 => 222, 216 => 193, 208 => 187, 206 => 186, 19 => 1,); } }
{'content_hash': 'accaa677207166d3aa8983fcfa7a26b2', 'timestamp': '', 'source': 'github', 'line_count': 322, 'max_line_length': 197, 'avg_line_length': 37.02795031055901, 'alnum_prop': 0.4314350415163969, 'repo_name': 'novikovm/Store', 'id': '87eb58ce6f9be9b0c2501bbea64a2cba081e7680', 'size': '11923', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/cache/dev/twig/e7/98/0dfb8bff76e82b49ca15a592b08d8e457a6b35170d5e64a247a3d4b200aa.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3073'}, {'name': 'CSS', 'bytes': '792'}, {'name': 'JavaScript', 'bytes': '2824'}, {'name': 'PHP', 'bytes': '77153'}]}
 //____________________________________________________________________________ // // Copyright (C) 2019, Mariusz Postol LODZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //____________________________________________________________________________ namespace UAOOI.Networking.Core { /// <summary> /// Enum HandlerState - represents states of an configurable object. /// </summary> public enum HandlerState { /// <summary> /// The handler is not configured and cannot be enabled. /// </summary> NoConfiguration, /// <summary> /// The handler is configured but currently disabled. /// </summary> Disabled, /// <summary> /// The handler is operational. /// </summary> Operational, /// <summary> /// The handler is in an error state, i.e. cannot change the state to Operational. Similar to NoConfiguration state but after an error occurs. /// </summary> Error } }
{'content_hash': '98203845daf7853e0ca239f9d405aa50', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 146, 'avg_line_length': 27.666666666666668, 'alnum_prop': 0.5341365461847389, 'repo_name': 'mpostol/OPC-UA-OOI', 'id': '4876b7e7815269c8f12ab80fe0feee9235e7c47a', 'size': '998', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Networking/Core/HandlerState.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '8495'}, {'name': 'C#', 'bytes': '4749023'}, {'name': 'Vim Snippet', 'bytes': '1008'}]}
#ifdef KROLL_COVERAGE #import "TiBase.h" #import "KrollObject.h" #import "KrollMethod.h" #define COMPONENT_TYPE_PROXIES @"proxies" #define COMPONENT_TYPE_MODULES @"modules" #define COMPONENT_TYPE_OTHER @"other" #define API_TYPE_FUNCTION @"function" #define API_TYPE_PROPERTY @"property" #define COVERAGE_TYPE_GET @"propertyGet" #define COVERAGE_TYPE_SET @"propertySet" #define COVERAGE_TYPE_CALL @"functionCall" #define TOP_LEVEL @"TOP_LEVEL" @protocol KrollCoverage <NSObject> -(void)increment:(NSString*)apiName coverageType:(NSString*)coverageType apiType:(NSString*)apiType; -(NSString*)coverageName; -(NSString*)coverageType; @end @interface KrollCoverageObject : KrollObject <KrollCoverage> { @private NSString *componentName, *componentType; } @property(nonatomic,copy) NSString *componentName; @property(nonatomic,copy) NSString *componentType; +(void)incrementCoverage:(NSString*)componentType_ componentName:(NSString*)componentName_ apiName:(NSString*)apiName_ coverageType:(NSString*)coverageType_ apiType:(NSString*)apiType_; +(void)incrementTopLevelFunctionCall:(NSString*)componentName name:(NSString*)apiName; +(NSDictionary*)dumpCoverage; +(void)releaseCoverage; -(id)initWithTarget:(id)target_ context:(KrollContext*)context_; -(id)initWithTarget:(id)target_ context:(KrollContext*)context_ componentName:(NSString*)componentName_; @end @interface KrollCoverageMethod : KrollMethod <KrollCoverage> { @private NSString *parentName, *parentType; id<KrollCoverage> parent; } @property(nonatomic,copy) NSString *parentName; @property(nonatomic,copy) NSString *parentType; -(id)initWithTarget:(id)target_ context:(KrollContext *)context_ parent:(id<KrollCoverage>)parent_; -(id)initWithTarget:(id)target_ selector:(SEL)selector_ argcount:(int)argcount_ type:(KrollMethodType)type_ name:(id)name_ context:(KrollContext*)context_ parent:(id)parent_; -(id)call:(NSArray*)args; @end #endif
{'content_hash': '21bb573fe092080f36e7572f9593252a', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 185, 'avg_line_length': 31.016129032258064, 'alnum_prop': 0.7795111804472179, 'repo_name': 'AppWerft/SunTracker', 'id': 'a35c96cbe93d2220f17c7fc21f3d721e8b64e370', 'size': '2220', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'build/iphone/Classes/KrollCoverage.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '139582'}, {'name': 'C++', 'bytes': '56872'}, {'name': 'D', 'bytes': '1093222'}, {'name': 'JavaScript', 'bytes': '31672'}, {'name': 'Objective-C', 'bytes': '3310532'}, {'name': 'Shell', 'bytes': '270'}]}
{% extends 'base.html' %} {% block content %} <main class="frontpage"> {% for article in articles %} <section> <h1><a href="{{ article.url }}">{{ article.title }}</a></h1> <time>Published {{ article.locale_date }}</time> <p>{{ article.summary }}</p> </section> {% endfor %} </main> {% endblock %}
{'content_hash': 'd9a765cd0f3bf2cf46dc62c75e9fa255', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 66, 'avg_line_length': 22.466666666666665, 'alnum_prop': 0.5311572700296736, 'repo_name': 'greencoder/scrapester.xyz', 'id': '0091584c04c82a77fd57bb37fb64d8bd61ed4b28', 'size': '337', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'themes/custom/templates/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3508'}, {'name': 'HTML', 'bytes': '2242'}, {'name': 'Python', 'bytes': '1704'}, {'name': 'Shell', 'bytes': '2201'}]}
using namespace cv; using namespace cv::xfeatures2d; using std::cout; using std::endl; const char* keys = "{ help h | | Print help message. }" "{ input1 | box.png | Path to input image 1. }" "{ input2 | box_in_scene.png | Path to input image 2. }"; int main( int argc, char* argv[] ) { CommandLineParser parser( argc, argv, keys ); Mat img_object = imread( samples::findFile( parser.get<String>("input1") ), IMREAD_GRAYSCALE ); Mat img_scene = imread( samples::findFile( parser.get<String>("input2") ), IMREAD_GRAYSCALE ); if ( img_object.empty() || img_scene.empty() ) { cout << "Could not open or find the image!\n" << endl; parser.printMessage(); return -1; } //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors int minHessian = 400; Ptr<SURF> detector = SURF::create( minHessian ); std::vector<KeyPoint> keypoints_object, keypoints_scene; Mat descriptors_object, descriptors_scene; detector->detectAndCompute( img_object, noArray(), keypoints_object, descriptors_object ); detector->detectAndCompute( img_scene, noArray(), keypoints_scene, descriptors_scene ); //-- Step 2: Matching descriptor vectors with a FLANN based matcher // Since SURF is a floating-point descriptor NORM_L2 is used Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(DescriptorMatcher::FLANNBASED); std::vector< std::vector<DMatch> > knn_matches; matcher->knnMatch( descriptors_object, descriptors_scene, knn_matches, 2 ); //-- Filter matches using the Lowe's ratio test const float ratio_thresh = 0.75f; std::vector<DMatch> good_matches; for (size_t i = 0; i < knn_matches.size(); i++) { if (knn_matches[i][0].distance < ratio_thresh * knn_matches[i][1].distance) { good_matches.push_back(knn_matches[i][0]); } } //-- Draw matches Mat img_matches; drawMatches( img_object, keypoints_object, img_scene, keypoints_scene, good_matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //-- Localize the object std::vector<Point2f> obj; std::vector<Point2f> scene; for( size_t i = 0; i < good_matches.size(); i++ ) { //-- Get the keypoints from the good matches obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt ); scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt ); } Mat H = findHomography( obj, scene, RANSAC ); //-- Get the corners from the image_1 ( the object to be "detected" ) std::vector<Point2f> obj_corners(4); obj_corners[0] = Point2f(0, 0); obj_corners[1] = Point2f( (float)img_object.cols, 0 ); obj_corners[2] = Point2f( (float)img_object.cols, (float)img_object.rows ); obj_corners[3] = Point2f( 0, (float)img_object.rows ); std::vector<Point2f> scene_corners(4); perspectiveTransform( obj_corners, scene_corners, H); //-- Draw lines between the corners (the mapped object in the scene - image_2 ) line( img_matches, scene_corners[0] + Point2f((float)img_object.cols, 0), scene_corners[1] + Point2f((float)img_object.cols, 0), Scalar(0, 255, 0), 4 ); line( img_matches, scene_corners[1] + Point2f((float)img_object.cols, 0), scene_corners[2] + Point2f((float)img_object.cols, 0), Scalar( 0, 255, 0), 4 ); line( img_matches, scene_corners[2] + Point2f((float)img_object.cols, 0), scene_corners[3] + Point2f((float)img_object.cols, 0), Scalar( 0, 255, 0), 4 ); line( img_matches, scene_corners[3] + Point2f((float)img_object.cols, 0), scene_corners[0] + Point2f((float)img_object.cols, 0), Scalar( 0, 255, 0), 4 ); //-- Show detected matches imshow("Good Matches & Object detection", img_matches ); waitKey(); return 0; } #else int main() { std::cout << "This tutorial code needs the xfeatures2d contrib module to be run." << std::endl; return 0; } #endif
{'content_hash': '4915b4b4ba5e249df6a02b4b5e3746b4', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 118, 'avg_line_length': 41.704081632653065, 'alnum_prop': 0.6359187668216295, 'repo_name': 'opencv/opencv', 'id': '2aa0bcd9cbb9c2eaafdc85aaa38e3577440360ed', 'size': '4329', 'binary': False, 'copies': '2', 'ref': 'refs/heads/4.x', 'path': 'samples/cpp/tutorial_code/features2D/feature_homography/SURF_FLANN_matching_homography_Demo.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AIDL', 'bytes': '1986'}, {'name': 'Batchfile', 'bytes': '1498'}, {'name': 'C', 'bytes': '1543870'}, {'name': 'C++', 'bytes': '35975082'}, {'name': 'CMake', 'bytes': '1010867'}, {'name': 'Cuda', 'bytes': '333437'}, {'name': 'Dockerfile', 'bytes': '309'}, {'name': 'HTML', 'bytes': '40027'}, {'name': 'Java', 'bytes': '774232'}, {'name': 'JavaScript', 'bytes': '233673'}, {'name': 'Kotlin', 'bytes': '5204'}, {'name': 'Objective-C', 'bytes': '100731'}, {'name': 'Objective-C++', 'bytes': '392600'}, {'name': 'Perl', 'bytes': '15865'}, {'name': 'PowerShell', 'bytes': '14591'}, {'name': 'Prolog', 'bytes': '843'}, {'name': 'Python', 'bytes': '1038154'}, {'name': 'Shell', 'bytes': '22738'}, {'name': 'Swift', 'bytes': '301765'}, {'name': 'TeX', 'bytes': '3530'}]}
<!--MENU DE ADMINISTRADOR--> <?php /* obtiene la ruta del proyecto*/ $rutaBase = base_url(); ?> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo $rutaBase.'resources/imagenes/im2.png'; ?>"><img src="<?php echo $rutaBase.'resources/imagenes/im2.png'; ?>" height="180%" width="60%" ></a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a id="drop1" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Enlace 1 </a> </li> <li class="dropdown"> <a id="drop2" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Enlace 2 <span class="caret"></span> </a> <ul class="dropdown-menu" aria-labelledby="drop4"> <li><a href="#">Lista 2.1</a></li> <li><a href="#">Lista 2.2</a></li> <li><a href="#">Lista 2.3</a></li> <li role="separator" class="divider"></li> <li><a href="#">Lista 2.4</a></li> </ul> </li> <li class="dropdown"> <a id="drop1" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Enlace 3 <span class="caret"></span> </a> <ul class="dropdown-menu" aria-labelledby="drop1"> <li><a href="#">Lista 1</a></li> <li><a href="#">Lista 2</a></li> <li><a href="#">Lista 3</a></li> <li role="separator" class="divider"></li> <li><a href="#">Lista 4</a></li> </ul> </li> <li class="dropdown"> <a id="drop1" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Enlace 4 <span class="caret"></span> </a> <ul class="dropdown-menu" aria-labelledby="drop1"> <li><a href="#">Lista 1</a></li> <li><a href="#">Lista 2</a></li> <li><a href="#">Lista 3</a></li> <li role="separator" class="divider"></li> <li><a href="#">Lista 4</a></li> </ul> </li> <li id="fat-menu" class="dropdown"> <a id="drop3" href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Administrador <span class="caret"></span> </a> <ul class="dropdown-menu" aria-labelledby="drop3"> <!--Se modifica la ruta segun el nombre del controlador--> <li><a href="<?php echo $rutaBase.'index.php/vistas/usuario';?>">Usuario</a></li> </ul> </li> </ul> </div><!-- /.nav-collapse --> </div><!-- /.container-fluid -->
{'content_hash': '8e86765499f12e3b10035ae66a376e36', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 187, 'avg_line_length': 42.07954545454545, 'alnum_prop': 0.497164461247637, 'repo_name': 'DaniGeraldine/Layout', 'id': 'a2971000e138fe0850d3766c426f3631579b419e', 'size': '3703', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/views/menu_admin.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '240'}, {'name': 'CSS', 'bytes': '12194'}, {'name': 'HTML', 'bytes': '5372956'}, {'name': 'JavaScript', 'bytes': '51459'}, {'name': 'PHP', 'bytes': '1735671'}]}
use std::cmp; use std::fmt::{self, Formatter}; use std::mem::{self, ManuallyDrop}; use std::num::NonZeroU32; use std::ops::{Deref, DerefMut}; #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] use std::sync::atomic::Ordering; use glutin::context::{NotCurrentContext, PossiblyCurrentContext}; use glutin::prelude::*; use glutin::surface::{Rect as DamageRect, Surface, SwapInterval, WindowSurface}; use log::{debug, info, warn}; use parking_lot::MutexGuard; use serde::{Deserialize, Serialize}; use winit::dpi::PhysicalSize; use winit::event::ModifiersState; use winit::window::CursorIcon; use crossfont::{self, Rasterize, Rasterizer}; use unicode_width::UnicodeWidthChar; use alacritty_terminal::ansi::{CursorShape, NamedColor}; use alacritty_terminal::config::MAX_SCROLLBACK_LINES; use alacritty_terminal::event::{EventListener, OnResize, WindowSize}; use alacritty_terminal::grid::Dimensions as TermDimensions; use alacritty_terminal::index::{Column, Direction, Line, Point}; use alacritty_terminal::selection::{Selection, SelectionRange}; use alacritty_terminal::term::cell::Flags; use alacritty_terminal::term::color::Rgb; use alacritty_terminal::term::{self, Term, TermDamage, TermMode, MIN_COLUMNS, MIN_SCREEN_LINES}; use crate::config::font::Font; use crate::config::window::Dimensions; #[cfg(not(windows))] use crate::config::window::StartupMode; use crate::config::UiConfig; use crate::display::bell::VisualBell; use crate::display::color::List; use crate::display::content::{RenderableContent, RenderableCursor}; use crate::display::cursor::IntoRects; use crate::display::damage::RenderDamageIterator; use crate::display::hint::{HintMatch, HintState}; use crate::display::meter::Meter; use crate::display::window::Window; use crate::event::{Mouse, SearchState}; use crate::message_bar::{MessageBuffer, MessageType}; use crate::renderer::rects::{RenderLine, RenderLines, RenderRect}; use crate::renderer::{self, GlyphCache, Renderer}; use crate::string::{ShortenDirection, StrShortener}; pub mod content; pub mod cursor; pub mod hint; pub mod window; mod bell; mod color; mod damage; mod meter; /// Label for the forward terminal search bar. const FORWARD_SEARCH_LABEL: &str = "Search: "; /// Label for the backward terminal search bar. const BACKWARD_SEARCH_LABEL: &str = "Backward Search: "; /// The character used to shorten the visible text like uri preview or search regex. const SHORTENER: char = '…'; /// Color which is used to highlight damaged rects when debugging. const DAMAGE_RECT_COLOR: Rgb = Rgb { r: 255, g: 0, b: 255 }; #[derive(Debug)] pub enum Error { /// Error with window management. Window(window::Error), /// Error dealing with fonts. Font(crossfont::Error), /// Error in renderer. Render(renderer::Error), /// Error during context operations. Context(glutin::error::Error), } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Window(err) => err.source(), Error::Font(err) => err.source(), Error::Render(err) => err.source(), Error::Context(err) => err.source(), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::Window(err) => err.fmt(f), Error::Font(err) => err.fmt(f), Error::Render(err) => err.fmt(f), Error::Context(err) => err.fmt(f), } } } impl From<window::Error> for Error { fn from(val: window::Error) -> Self { Error::Window(val) } } impl From<crossfont::Error> for Error { fn from(val: crossfont::Error) -> Self { Error::Font(val) } } impl From<renderer::Error> for Error { fn from(val: renderer::Error) -> Self { Error::Render(val) } } impl From<glutin::error::Error> for Error { fn from(val: glutin::error::Error) -> Self { Error::Context(val) } } /// Terminal size info. #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)] pub struct SizeInfo<T = f32> { /// Terminal window width. width: T, /// Terminal window height. height: T, /// Width of individual cell. cell_width: T, /// Height of individual cell. cell_height: T, /// Horizontal window padding. padding_x: T, /// Vertical window padding. padding_y: T, /// Number of lines in the viewport. screen_lines: usize, /// Number of columns in the viewport. columns: usize, } impl From<SizeInfo<f32>> for SizeInfo<u32> { fn from(size_info: SizeInfo<f32>) -> Self { Self { width: size_info.width as u32, height: size_info.height as u32, cell_width: size_info.cell_width as u32, cell_height: size_info.cell_height as u32, padding_x: size_info.padding_x as u32, padding_y: size_info.padding_y as u32, screen_lines: size_info.screen_lines, columns: size_info.screen_lines, } } } impl From<SizeInfo<f32>> for WindowSize { fn from(size_info: SizeInfo<f32>) -> Self { Self { num_cols: size_info.columns() as u16, num_lines: size_info.screen_lines() as u16, cell_width: size_info.cell_width() as u16, cell_height: size_info.cell_height() as u16, } } } impl<T: Clone + Copy> SizeInfo<T> { #[inline] pub fn width(&self) -> T { self.width } #[inline] pub fn height(&self) -> T { self.height } #[inline] pub fn cell_width(&self) -> T { self.cell_width } #[inline] pub fn cell_height(&self) -> T { self.cell_height } #[inline] pub fn padding_x(&self) -> T { self.padding_x } #[inline] pub fn padding_y(&self) -> T { self.padding_y } } impl SizeInfo<f32> { #[allow(clippy::too_many_arguments)] pub fn new( width: f32, height: f32, cell_width: f32, cell_height: f32, mut padding_x: f32, mut padding_y: f32, dynamic_padding: bool, ) -> SizeInfo { if dynamic_padding { padding_x = Self::dynamic_padding(padding_x.floor(), width, cell_width); padding_y = Self::dynamic_padding(padding_y.floor(), height, cell_height); } let lines = (height - 2. * padding_y) / cell_height; let screen_lines = cmp::max(lines as usize, MIN_SCREEN_LINES); let columns = (width - 2. * padding_x) / cell_width; let columns = cmp::max(columns as usize, MIN_COLUMNS); SizeInfo { width, height, cell_width, cell_height, padding_x: padding_x.floor(), padding_y: padding_y.floor(), screen_lines, columns, } } #[inline] pub fn reserve_lines(&mut self, count: usize) { self.screen_lines = cmp::max(self.screen_lines.saturating_sub(count), MIN_SCREEN_LINES); } /// Check if coordinates are inside the terminal grid. /// /// The padding, message bar or search are not counted as part of the grid. #[inline] pub fn contains_point(&self, x: usize, y: usize) -> bool { x <= (self.padding_x + self.columns as f32 * self.cell_width) as usize && x > self.padding_x as usize && y <= (self.padding_y + self.screen_lines as f32 * self.cell_height) as usize && y > self.padding_y as usize } /// Calculate padding to spread it evenly around the terminal content. #[inline] fn dynamic_padding(padding: f32, dimension: f32, cell_dimension: f32) -> f32 { padding + ((dimension - 2. * padding) % cell_dimension) / 2. } } impl TermDimensions for SizeInfo { #[inline] fn columns(&self) -> usize { self.columns } #[inline] fn screen_lines(&self) -> usize { self.screen_lines } #[inline] fn total_lines(&self) -> usize { self.screen_lines() } } #[derive(Default, Clone, Debug, PartialEq, Eq)] pub struct DisplayUpdate { pub dirty: bool, dimensions: Option<PhysicalSize<u32>>, cursor_dirty: bool, font: Option<Font>, } impl DisplayUpdate { pub fn dimensions(&self) -> Option<PhysicalSize<u32>> { self.dimensions } pub fn font(&self) -> Option<&Font> { self.font.as_ref() } pub fn cursor_dirty(&self) -> bool { self.cursor_dirty } pub fn set_dimensions(&mut self, dimensions: PhysicalSize<u32>) { self.dimensions = Some(dimensions); self.dirty = true; } pub fn set_font(&mut self, font: Font) { self.font = Some(font); self.dirty = true; } pub fn set_cursor_dirty(&mut self) { self.cursor_dirty = true; self.dirty = true; } } /// The display wraps a window, font rasterizer, and GPU renderer. pub struct Display { pub window: Window, pub size_info: SizeInfo, /// Hint highlighted by the mouse. pub highlighted_hint: Option<HintMatch>, /// Hint highlighted by the vi mode cursor. pub vi_highlighted_hint: Option<HintMatch>, pub is_wayland: bool, /// UI cursor visibility for blinking. pub cursor_hidden: bool, pub visual_bell: VisualBell, /// Mapped RGB values for each terminal color. pub colors: List, /// State of the keyboard hints. pub hint_state: HintState, /// Unprocessed display updates. pub pending_update: DisplayUpdate, /// The renderer update that takes place only once before the actual rendering. pub pending_renderer_update: Option<RendererUpdate>, /// The ime on the given display. pub ime: Ime, // Mouse point position when highlighting hints. hint_mouse_point: Option<Point>, renderer: ManuallyDrop<Renderer>, surface: ManuallyDrop<Surface<WindowSurface>>, context: ManuallyDrop<Replaceable<PossiblyCurrentContext>>, debug_damage: bool, damage_rects: Vec<DamageRect>, next_frame_damage_rects: Vec<DamageRect>, glyph_cache: GlyphCache, meter: Meter, } impl Display { pub fn new( window: Window, gl_context: NotCurrentContext, config: &UiConfig, ) -> Result<Display, Error> { #[cfg(any(not(feature = "wayland"), target_os = "macos", windows))] let is_wayland = false; #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] let is_wayland = window.wayland_surface().is_some(); let scale_factor = window.scale_factor as f32; let rasterizer = Rasterizer::new(scale_factor)?; debug!("Loading \"{}\" font", &config.font.normal().family); let mut glyph_cache = GlyphCache::new(rasterizer, &config.font)?; let metrics = glyph_cache.font_metrics(); let (cell_width, cell_height) = compute_cell_size(config, &metrics); // Resize the window to account for the user configured size. if let Some(dimensions) = config.window.dimensions() { let size = window_size(config, dimensions, cell_width, cell_height, scale_factor); window.set_inner_size(size); } // Create the GL surface to draw into. let surface = renderer::platform::create_gl_surface( &gl_context, window.inner_size(), window.raw_window_handle(), )?; // Make the context current. let context = gl_context.make_current(&surface)?; // Create renderer. let mut renderer = Renderer::new(&context)?; // Load font common glyphs to accelerate rendering. debug!("Filling glyph cache with common glyphs"); renderer.with_loader(|mut api| { glyph_cache.reset_glyph_cache(&mut api); }); let padding = config.window.padding(window.scale_factor as f32); let viewport_size = window.inner_size(); // Create new size with at least one column and row. let size_info = SizeInfo::new( viewport_size.width as f32, viewport_size.height as f32, cell_width, cell_height, padding.0, padding.1, config.window.dynamic_padding && config.window.dimensions().is_none(), ); info!("Cell size: {} x {}", cell_width, cell_height); info!("Padding: {} x {}", size_info.padding_x(), size_info.padding_y()); info!("Width: {}, Height: {}", size_info.width(), size_info.height()); // Update OpenGL projection. renderer.resize(&size_info); // Clear screen. let background_color = config.colors.primary.background; renderer.clear(background_color, config.window_opacity()); // Disable shadows for transparent windows on macOS. #[cfg(target_os = "macos")] window.set_has_shadow(config.window_opacity() >= 1.0); // On Wayland we can safely ignore this call, since the window isn't visible until you // actually draw something into it and commit those changes. #[cfg(not(any(target_os = "macos", windows)))] if !is_wayland { surface.swap_buffers(&context).expect("failed to swap buffers."); renderer.finish(); } window.set_visible(true); #[allow(clippy::single_match)] #[cfg(not(windows))] match config.window.startup_mode { #[cfg(target_os = "macos")] StartupMode::SimpleFullscreen => window.set_simple_fullscreen(true), #[cfg(not(any(target_os = "macos", windows)))] StartupMode::Maximized if !is_wayland => window.set_maximized(true), _ => (), } let hint_state = HintState::new(config.hints.alphabet()); let debug_damage = config.debug.highlight_damage; let (damage_rects, next_frame_damage_rects) = if is_wayland || debug_damage { let vec = Vec::with_capacity(size_info.screen_lines()); (vec.clone(), vec) } else { (Vec::new(), Vec::new()) }; // We use vsync everywhere except wayland. if !is_wayland { if let Err(err) = surface.set_swap_interval(&context, SwapInterval::Wait(NonZeroU32::new(1).unwrap())) { warn!("Error setting vsync: {:?}", err); } } Ok(Self { window, context: ManuallyDrop::new(Replaceable::new(context)), surface: ManuallyDrop::new(surface), renderer: ManuallyDrop::new(renderer), glyph_cache, hint_state, meter: Meter::new(), size_info, ime: Ime::new(), highlighted_hint: None, vi_highlighted_hint: None, is_wayland, cursor_hidden: false, visual_bell: VisualBell::from(&config.bell), colors: List::from(&config.colors), pending_update: Default::default(), pending_renderer_update: Default::default(), debug_damage, damage_rects, next_frame_damage_rects, hint_mouse_point: None, }) } #[inline] pub fn gl_context(&self) -> &PossiblyCurrentContext { self.context.get() } pub fn make_not_current(&mut self) { if self.context.get().is_current() { self.context.replace_with(|context| { context .make_not_current() .expect("failed to disable context") .treat_as_possibly_current() }); } } pub fn make_current(&self) { if !self.context.get().is_current() { self.context.make_current(&self.surface).expect("failed to make context current") } } fn swap_buffers(&self) { #[allow(clippy::single_match)] match (self.surface.deref(), &self.context.get()) { #[cfg(not(any(target_os = "macos", windows)))] (Surface::Egl(surface), PossiblyCurrentContext::Egl(context)) if self.is_wayland && !self.debug_damage => { surface.swap_buffers_with_damage(context, &self.damage_rects) }, (surface, context) => surface.swap_buffers(context), } .expect("failed to swap buffers."); } /// Update font size and cell dimensions. /// /// This will return a tuple of the cell width and height. fn update_font_size( glyph_cache: &mut GlyphCache, scale_factor: f64, config: &UiConfig, font: &Font, ) -> (f32, f32) { let _ = glyph_cache.update_font_size(font, scale_factor); // Compute new cell sizes. compute_cell_size(config, &glyph_cache.font_metrics()) } /// Reset glyph cache. fn reset_glyph_cache(&mut self) { let cache = &mut self.glyph_cache; self.renderer.with_loader(|mut api| { cache.reset_glyph_cache(&mut api); }); } /// Process update events. /// /// XXX: this function must not call to any `OpenGL` related tasks. Only logical update /// of the state is being performed here. Rendering update takes part right before the /// actual rendering. pub fn handle_update<T>( &mut self, terminal: &mut Term<T>, pty_resize_handle: &mut dyn OnResize, message_buffer: &MessageBuffer, search_active: bool, config: &UiConfig, ) where T: EventListener, { let pending_update = mem::take(&mut self.pending_update); let (mut cell_width, mut cell_height) = (self.size_info.cell_width(), self.size_info.cell_height()); if pending_update.font().is_some() || pending_update.cursor_dirty() { let renderer_update = self.pending_renderer_update.get_or_insert(Default::default()); renderer_update.clear_font_cache = true } // Update font size and cell dimensions. if let Some(font) = pending_update.font() { let scale_factor = self.window.scale_factor; let cell_dimensions = Self::update_font_size(&mut self.glyph_cache, scale_factor, config, font); cell_width = cell_dimensions.0; cell_height = cell_dimensions.1; info!("Cell size: {} x {}", cell_width, cell_height); } let (mut width, mut height) = (self.size_info.width(), self.size_info.height()); if let Some(dimensions) = pending_update.dimensions() { width = dimensions.width as f32; height = dimensions.height as f32; let renderer_update = self.pending_renderer_update.get_or_insert(Default::default()); renderer_update.resize = true } let padding = config.window.padding(self.window.scale_factor as f32); self.size_info = SizeInfo::new( width, height, cell_width, cell_height, padding.0, padding.1, config.window.dynamic_padding, ); // Update number of column/lines in the viewport. let message_bar_lines = message_buffer.message().map_or(0, |m| m.text(&self.size_info).len()); let search_lines = usize::from(search_active); self.size_info.reserve_lines(message_bar_lines + search_lines); // Resize PTY. pty_resize_handle.on_resize(self.size_info.into()); // Resize terminal. terminal.resize(self.size_info); } /// Update the state of the renderer. /// /// NOTE: The update to the renderer is split from the display update on purpose, since /// on some platforms, like Wayland, resize and other OpenGL operations must be performed /// right before rendering, otherwise they could lock the back buffer resulting in /// rendering with the buffer of old size. /// /// This also resolves any flickering, since the resize is now synced with frame callbacks. pub fn process_renderer_update(&mut self) { let renderer_update = match self.pending_renderer_update.take() { Some(renderer_update) => renderer_update, _ => return, }; // Resize renderer. if renderer_update.resize { let width = NonZeroU32::new(self.size_info.width() as u32).unwrap(); let height = NonZeroU32::new(self.size_info.height() as u32).unwrap(); self.surface.resize(&self.context, width, height); } // Ensure we're modifying the correct OpenGL context. self.make_current(); if renderer_update.clear_font_cache { self.reset_glyph_cache(); } self.renderer.resize(&self.size_info); if self.collect_damage() { let lines = self.size_info.screen_lines(); if lines > self.damage_rects.len() { self.damage_rects.reserve(lines); } else { self.damage_rects.shrink_to(lines); } } info!("Padding: {} x {}", self.size_info.padding_x(), self.size_info.padding_y()); info!("Width: {}, Height: {}", self.size_info.width(), self.size_info.height()); // Damage the entire screen after processing update. self.fully_damage(); } /// Damage the entire window. fn fully_damage(&mut self) { let screen_rect = DamageRect::new(0, 0, self.size_info.width() as i32, self.size_info.height() as i32); self.damage_rects.push(screen_rect); } fn update_damage<T: EventListener>( &mut self, terminal: &mut MutexGuard<'_, Term<T>>, selection_range: Option<SelectionRange>, search_state: &SearchState, ) { let requires_full_damage = self.visual_bell.intensity() != 0. || self.hint_state.active() || search_state.regex().is_some(); if requires_full_damage { terminal.mark_fully_damaged(); } self.damage_highlighted_hints(terminal); match terminal.damage(selection_range) { TermDamage::Full => self.fully_damage(), TermDamage::Partial(damaged_lines) => { let damaged_rects = RenderDamageIterator::new(damaged_lines, self.size_info.into()); for damaged_rect in damaged_rects { self.damage_rects.push(damaged_rect); } }, } terminal.reset_damage(); // Ensure that the content requiring full damage is cleaned up again on the next frame. if requires_full_damage { terminal.mark_fully_damaged(); } // Damage highlighted hints for the next frame as well, so we'll clear them. self.damage_highlighted_hints(terminal); } /// Draw the screen. /// /// A reference to Term whose state is being drawn must be provided. /// /// This call may block if vsync is enabled. pub fn draw<T: EventListener>( &mut self, mut terminal: MutexGuard<'_, Term<T>>, message_buffer: &MessageBuffer, config: &UiConfig, search_state: &SearchState, ) { // Collect renderable content before the terminal is dropped. let mut content = RenderableContent::new(config, self, &terminal, search_state); let mut grid_cells = Vec::new(); for cell in &mut content { grid_cells.push(cell); } let selection_range = content.selection_range(); let foreground_color = content.color(NamedColor::Foreground as usize); let background_color = content.color(NamedColor::Background as usize); let display_offset = content.display_offset(); let cursor = content.cursor(); let cursor_point = terminal.grid().cursor.point; let total_lines = terminal.grid().total_lines(); let metrics = self.glyph_cache.font_metrics(); let size_info = self.size_info; let vi_mode = terminal.mode().contains(TermMode::VI); let vi_cursor_point = if vi_mode { Some(terminal.vi_mode_cursor.point) } else { None }; if self.collect_damage() { self.update_damage(&mut terminal, selection_range, search_state); } // Drop terminal as early as possible to free lock. drop(terminal); // Make sure this window's OpenGL context is active. self.make_current(); self.renderer.clear(background_color, config.window_opacity()); let mut lines = RenderLines::new(); // Optimize loop hint comparator. let has_highlighted_hint = self.highlighted_hint.is_some() || self.vi_highlighted_hint.is_some(); // Draw grid. { let _sampler = self.meter.sampler(); // Ensure macOS hasn't reset our viewport. #[cfg(target_os = "macos")] self.renderer.set_viewport(&size_info); let glyph_cache = &mut self.glyph_cache; let highlighted_hint = &self.highlighted_hint; let vi_highlighted_hint = &self.vi_highlighted_hint; self.renderer.draw_cells( &size_info, glyph_cache, grid_cells.into_iter().map(|mut cell| { // Underline hints hovered by mouse or vi mode cursor. let point = term::viewport_to_point(display_offset, cell.point); if has_highlighted_hint { let hyperlink = cell.extra.as_ref().and_then(|extra| extra.hyperlink.as_ref()); if highlighted_hint .as_ref() .map_or(false, |hint| hint.should_highlight(point, hyperlink)) || vi_highlighted_hint .as_ref() .map_or(false, |hint| hint.should_highlight(point, hyperlink)) { cell.flags.insert(Flags::UNDERLINE); } } // Update underline/strikeout. lines.update(&cell); cell }), ); } let mut rects = lines.rects(&metrics, &size_info); if let Some(vi_cursor_point) = vi_cursor_point { // Indicate vi mode by showing the cursor's position in the top right corner. let line = (-vi_cursor_point.line.0 + size_info.bottommost_line().0) as usize; let obstructed_column = Some(vi_cursor_point) .filter(|point| point.line == -(display_offset as i32)) .map(|point| point.column); self.draw_line_indicator(config, total_lines, obstructed_column, line); } else if search_state.regex().is_some() { // Show current display offset in vi-less search to indicate match position. self.draw_line_indicator(config, total_lines, None, display_offset); }; // Draw cursor. rects.extend(cursor.rects(&size_info, config.terminal_config.cursor.thickness())); // Push visual bell after url/underline/strikeout rects. let visual_bell_intensity = self.visual_bell.intensity(); if visual_bell_intensity != 0. { let visual_bell_rect = RenderRect::new( 0., 0., size_info.width(), size_info.height(), config.bell.color, visual_bell_intensity as f32, ); rects.push(visual_bell_rect); } // Handle IME positioning and search bar rendering. let ime_position = match search_state.regex() { Some(regex) => { let search_label = match search_state.direction() { Direction::Right => FORWARD_SEARCH_LABEL, Direction::Left => BACKWARD_SEARCH_LABEL, }; let search_text = Self::format_search(regex, search_label, size_info.columns()); // Render the search bar. self.draw_search(config, &search_text); // Draw search bar cursor. let line = size_info.screen_lines(); let column = Column(search_text.chars().count() - 1); // Add cursor to search bar if IME is not active. if self.ime.preedit().is_none() { let fg = config.colors.footer_bar_foreground(); let shape = CursorShape::Underline; let cursor = RenderableCursor::new(Point::new(line, column), shape, fg, false); rects.extend( cursor.rects(&size_info, config.terminal_config.cursor.thickness()), ); } Some(Point::new(line, column)) }, None => { let num_lines = self.size_info.screen_lines(); term::point_to_viewport(display_offset, cursor_point) .filter(|point| point.line < num_lines) }, }; // Handle IME. if self.ime.is_enabled() { if let Some(point) = ime_position { let (fg, bg) = if search_state.regex().is_some() { (config.colors.footer_bar_foreground(), config.colors.footer_bar_background()) } else { (foreground_color, background_color) }; self.draw_ime_preview(point, fg, bg, &mut rects, config); } } if self.debug_damage { self.highlight_damage(&mut rects); } if let Some(message) = message_buffer.message() { let search_offset = usize::from(search_state.regex().is_some()); let text = message.text(&size_info); // Create a new rectangle for the background. let start_line = size_info.screen_lines() + search_offset; let y = size_info.cell_height().mul_add(start_line as f32, size_info.padding_y()); let bg = match message.ty() { MessageType::Error => config.colors.normal.red, MessageType::Warning => config.colors.normal.yellow, }; let message_bar_rect = RenderRect::new(0., y, size_info.width(), size_info.height() - y, bg, 1.); // Push message_bar in the end, so it'll be above all other content. rects.push(message_bar_rect); // Draw rectangles. self.renderer.draw_rects(&size_info, &metrics, rects); // Relay messages to the user. let glyph_cache = &mut self.glyph_cache; let fg = config.colors.primary.background; for (i, message_text) in text.iter().enumerate() { let point = Point::new(start_line + i, Column(0)); self.renderer.draw_string( point, fg, bg, message_text.chars(), &size_info, glyph_cache, ); } } else { // Draw rectangles. self.renderer.draw_rects(&size_info, &metrics, rects); } self.draw_render_timer(config); // Draw hyperlink uri preview. if has_highlighted_hint { let cursor_point = vi_cursor_point.or(Some(cursor_point)); self.draw_hyperlink_preview(config, cursor_point, display_offset); } // Frame event should be requested before swaping buffers, since it requires surface // `commit`, which is done by swap buffers under the hood. #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] self.request_frame(&self.window); // Clearing debug highlights from the previous frame requires full redraw. self.swap_buffers(); #[cfg(all(feature = "x11", not(any(target_os = "macos", windows))))] if !self.is_wayland { // On X11 `swap_buffers` does not block for vsync. However the next OpenGl command // will block to synchronize (this is `glClear` in Alacritty), which causes a // permanent one frame delay. self.renderer.finish(); } self.damage_rects.clear(); // Append damage rects we've enqueued for the next frame. mem::swap(&mut self.damage_rects, &mut self.next_frame_damage_rects); } /// Update to a new configuration. pub fn update_config(&mut self, config: &UiConfig) { self.debug_damage = config.debug.highlight_damage; self.visual_bell.update_config(&config.bell); self.colors = List::from(&config.colors); } /// Update the mouse/vi mode cursor hint highlighting. /// /// This will return whether the highlighted hints changed. pub fn update_highlighted_hints<T>( &mut self, term: &Term<T>, config: &UiConfig, mouse: &Mouse, modifiers: ModifiersState, ) -> bool { // Update vi mode cursor hint. let vi_highlighted_hint = if term.mode().contains(TermMode::VI) { let mods = ModifiersState::all(); let point = term.vi_mode_cursor.point; hint::highlighted_at(term, config, point, mods) } else { None }; let mut dirty = vi_highlighted_hint != self.vi_highlighted_hint; self.vi_highlighted_hint = vi_highlighted_hint; // Abort if mouse highlighting conditions are not met. if !mouse.inside_text_area || !term.selection.as_ref().map_or(true, Selection::is_empty) { dirty |= self.highlighted_hint.is_some(); self.highlighted_hint = None; return dirty; } // Find highlighted hint at mouse position. let point = mouse.point(&self.size_info, term.grid().display_offset()); let highlighted_hint = hint::highlighted_at(term, config, point, modifiers); // Update cursor shape. if highlighted_hint.is_some() { // If mouse changed the line, we should update the hyperlink preview, since the // highlighted hint could be disrupted by the old preview. dirty = self.hint_mouse_point.map_or(false, |p| p.line != point.line); self.hint_mouse_point = Some(point); self.window.set_mouse_cursor(CursorIcon::Hand); } else if self.highlighted_hint.is_some() { self.hint_mouse_point = None; if term.mode().intersects(TermMode::MOUSE_MODE) && !term.mode().contains(TermMode::VI) { self.window.set_mouse_cursor(CursorIcon::Default); } else { self.window.set_mouse_cursor(CursorIcon::Text); } } dirty |= self.highlighted_hint != highlighted_hint; self.highlighted_hint = highlighted_hint; dirty } #[inline(never)] fn draw_ime_preview( &mut self, point: Point<usize>, fg: Rgb, bg: Rgb, rects: &mut Vec<RenderRect>, config: &UiConfig, ) { let preedit = match self.ime.preedit() { Some(preedit) => preedit, None => { // In case we don't have preedit, just set the popup point. self.window.update_ime_position(point, &self.size_info); return; }, }; let num_cols = self.size_info.columns(); // Get the visible preedit. let visible_text: String = match (preedit.cursor_byte_offset, preedit.cursor_end_offset) { (Some(byte_offset), Some(end_offset)) if end_offset > num_cols => StrShortener::new( &preedit.text[byte_offset..], num_cols, ShortenDirection::Right, Some(SHORTENER), ), _ => { StrShortener::new(&preedit.text, num_cols, ShortenDirection::Left, Some(SHORTENER)) }, } .collect(); let visible_len = visible_text.chars().count(); let end = cmp::min(point.column.0 + visible_len, num_cols); let start = end.saturating_sub(visible_len); let start = Point::new(point.line, Column(start)); let end = Point::new(point.line, Column(end - 1)); let glyph_cache = &mut self.glyph_cache; let metrics = glyph_cache.font_metrics(); self.renderer.draw_string( start, fg, bg, visible_text.chars(), &self.size_info, glyph_cache, ); if self.collect_damage() { let damage = self.damage_from_point(Point::new(start.line, Column(0)), num_cols as u32); self.damage_rects.push(damage); self.next_frame_damage_rects.push(damage); } // Add underline for preedit text. let underline = RenderLine { start, end, color: fg }; rects.extend(underline.rects(Flags::UNDERLINE, &metrics, &self.size_info)); let ime_popup_point = match preedit.cursor_end_offset { Some(cursor_end_offset) if cursor_end_offset != 0 => { let is_wide = preedit.text[preedit.cursor_byte_offset.unwrap_or_default()..] .chars() .next() .map(|ch| ch.width() == Some(2)) .unwrap_or_default(); let cursor_column = Column( (end.column.0 as isize - cursor_end_offset as isize + 1).max(0) as usize, ); let cursor_point = Point::new(point.line, cursor_column); let cursor = RenderableCursor::new(cursor_point, CursorShape::HollowBlock, fg, is_wide); rects.extend( cursor.rects(&self.size_info, config.terminal_config.cursor.thickness()), ); cursor_point }, _ => end, }; self.window.update_ime_position(ime_popup_point, &self.size_info); } /// Format search regex to account for the cursor and fullwidth characters. fn format_search(search_regex: &str, search_label: &str, max_width: usize) -> String { let label_len = search_label.len(); // Skip `search_regex` formatting if only label is visible. if label_len > max_width { return search_label[..max_width].to_owned(); } // The search string consists of `search_label` + `search_regex` + `cursor`. let mut bar_text = String::from(search_label); bar_text.extend(StrShortener::new( search_regex, max_width.wrapping_sub(label_len + 1), ShortenDirection::Left, Some(SHORTENER), )); // Add place for cursor. bar_text.push(' '); bar_text } /// Draw preview for the currently highlighted `Hyperlink`. #[inline(never)] fn draw_hyperlink_preview( &mut self, config: &UiConfig, cursor_point: Option<Point>, display_offset: usize, ) { let num_cols = self.size_info.columns(); let uris: Vec<_> = self .highlighted_hint .iter() .chain(&self.vi_highlighted_hint) .filter_map(|hint| hint.hyperlink().map(|hyperlink| hyperlink.uri())) .map(|uri| StrShortener::new(uri, num_cols, ShortenDirection::Right, Some(SHORTENER))) .collect(); if uris.is_empty() { return; } // The maximum amount of protected lines including the ones we'll show preview on. let max_protected_lines = uris.len() * 2; // Lines we shouldn't shouldn't show preview on, because it'll obscure the highlighted // hint. let mut protected_lines = Vec::with_capacity(max_protected_lines); if self.size_info.screen_lines() >= max_protected_lines { // Prefer to show preview even when it'll likely obscure the highlighted hint, when // there's no place left for it. protected_lines.push(self.hint_mouse_point.map(|point| point.line)); protected_lines.push(cursor_point.map(|point| point.line)); } // Find the line in viewport we can draw preview on without obscuring protected lines. let viewport_bottom = self.size_info.bottommost_line() - Line(display_offset as i32); let viewport_top = viewport_bottom - (self.size_info.screen_lines() - 1); let uri_lines = (viewport_top.0..=viewport_bottom.0) .rev() .map(|line| Some(Line(line))) .filter_map(|line| { if protected_lines.contains(&line) { None } else { protected_lines.push(line); line } }) .take(uris.len()) .flat_map(|line| term::point_to_viewport(display_offset, Point::new(line, Column(0)))); let fg = config.colors.footer_bar_foreground(); let bg = config.colors.footer_bar_background(); for (uri, point) in uris.into_iter().zip(uri_lines) { // Damage the uri preview. if self.collect_damage() { let uri_preview_damage = self.damage_from_point(point, num_cols as u32); self.damage_rects.push(uri_preview_damage); // Damage the uri preview for the next frame as well. self.next_frame_damage_rects.push(uri_preview_damage); } self.renderer.draw_string(point, fg, bg, uri, &self.size_info, &mut self.glyph_cache); } } /// Draw current search regex. #[inline(never)] fn draw_search(&mut self, config: &UiConfig, text: &str) { // Assure text length is at least num_cols. let num_cols = self.size_info.columns(); let text = format!("{:<1$}", text, num_cols); let point = Point::new(self.size_info.screen_lines(), Column(0)); let fg = config.colors.footer_bar_foreground(); let bg = config.colors.footer_bar_background(); self.renderer.draw_string( point, fg, bg, text.chars(), &self.size_info, &mut self.glyph_cache, ); } /// Draw render timer. #[inline(never)] fn draw_render_timer(&mut self, config: &UiConfig) { if !config.debug.render_timer { return; } let timing = format!("{:.3} usec", self.meter.average()); let point = Point::new(self.size_info.screen_lines().saturating_sub(2), Column(0)); let fg = config.colors.primary.background; let bg = config.colors.normal.red; if self.collect_damage() { // Damage the entire line. let render_timer_damage = self.damage_from_point(point, self.size_info.columns() as u32); self.damage_rects.push(render_timer_damage); // Damage the render timer for the next frame. self.next_frame_damage_rects.push(render_timer_damage) } let glyph_cache = &mut self.glyph_cache; self.renderer.draw_string(point, fg, bg, timing.chars(), &self.size_info, glyph_cache); } /// Draw an indicator for the position of a line in history. #[inline(never)] fn draw_line_indicator( &mut self, config: &UiConfig, total_lines: usize, obstructed_column: Option<Column>, line: usize, ) { const fn num_digits(mut number: u32) -> usize { let mut res = 0; loop { number /= 10; res += 1; if number == 0 { break res; } } } let text = format!("[{}/{}]", line, total_lines - 1); let column = Column(self.size_info.columns().saturating_sub(text.len())); let point = Point::new(0, column); // Damage the maximum possible length of the format text, which could be achieved when // using `MAX_SCROLLBACK_LINES` as current and total lines adding a `3` for formatting. const MAX_SIZE: usize = 2 * num_digits(MAX_SCROLLBACK_LINES) + 3; let damage_point = Point::new(0, Column(self.size_info.columns().saturating_sub(MAX_SIZE))); if self.collect_damage() { self.damage_rects.push(self.damage_from_point(damage_point, MAX_SIZE as u32)); } let colors = &config.colors; let fg = colors.line_indicator.foreground.unwrap_or(colors.primary.background); let bg = colors.line_indicator.background.unwrap_or(colors.primary.foreground); // Do not render anything if it would obscure the vi mode cursor. if obstructed_column.map_or(true, |obstructed_column| obstructed_column < column) { let glyph_cache = &mut self.glyph_cache; self.renderer.draw_string(point, fg, bg, text.chars(), &self.size_info, glyph_cache); } } /// Damage `len` starting from a `point`. /// /// This method also enqueues damage for the next frame automatically. fn damage_from_point(&self, point: Point<usize>, len: u32) -> DamageRect { let size_info: SizeInfo<u32> = self.size_info.into(); let x = size_info.padding_x() + point.column.0 as u32 * size_info.cell_width(); let y_top = size_info.height() - size_info.padding_y(); let y = y_top - (point.line as u32 + 1) * size_info.cell_height(); let width = len * size_info.cell_width(); DamageRect::new(x as i32, y as i32, width as i32, size_info.cell_height() as i32) } /// Damage currently highlighted `Display` hints. #[inline] fn damage_highlighted_hints<T: EventListener>(&self, terminal: &mut Term<T>) { let display_offset = terminal.grid().display_offset(); let last_visible_line = terminal.screen_lines() - 1; for hint in self.highlighted_hint.iter().chain(&self.vi_highlighted_hint) { for point in (hint.bounds().start().line.0..=hint.bounds().end().line.0).flat_map(|line| { term::point_to_viewport(display_offset, Point::new(Line(line), Column(0))) .filter(|point| point.line <= last_visible_line) }) { terminal.damage_line(point.line, 0, terminal.columns() - 1); } } } /// Returns `true` if damage information should be collected, `false` otherwise. #[inline] fn collect_damage(&self) -> bool { self.is_wayland || self.debug_damage } /// Highlight damaged rects. /// /// This function is for debug purposes only. fn highlight_damage(&self, render_rects: &mut Vec<RenderRect>) { for damage_rect in &self.damage_rects { let x = damage_rect.x as f32; let height = damage_rect.height as f32; let width = damage_rect.width as f32; let y = self.size_info.height() - damage_rect.y as f32 - height; let render_rect = RenderRect::new(x, y, width, height, DAMAGE_RECT_COLOR, 0.5); render_rects.push(render_rect); } } /// Requst a new frame for a window on Wayland. #[inline] #[cfg(all(feature = "wayland", not(any(target_os = "macos", windows))))] fn request_frame(&self, window: &Window) { let surface = match window.wayland_surface() { Some(surface) => surface, None => return, }; let should_draw = self.window.should_draw.clone(); // Mark that window was drawn. should_draw.store(false, Ordering::Relaxed); // Request a new frame. surface.frame().quick_assign(move |_, _, _| { should_draw.store(true, Ordering::Relaxed); }); } } impl Drop for Display { fn drop(&mut self) { // Switch OpenGL context before dropping, otherwise objects (like programs) from other // contexts might be deleted during droping renderer. self.make_current(); unsafe { ManuallyDrop::drop(&mut self.renderer); ManuallyDrop::drop(&mut self.context); ManuallyDrop::drop(&mut self.surface); } } } /// Input method state. #[derive(Debug, Default)] pub struct Ime { /// Whether the IME is enabled. enabled: bool, /// Current IME preedit. preedit: Option<Preedit>, } impl Ime { pub fn new() -> Self { Default::default() } #[inline] pub fn set_enabled(&mut self, is_enabled: bool) { if is_enabled { self.enabled = is_enabled } else { // Clear state when disabling IME. *self = Default::default(); } } #[inline] pub fn is_enabled(&self) -> bool { self.enabled } #[inline] pub fn set_preedit(&mut self, preedit: Option<Preedit>) { self.preedit = preedit; } #[inline] pub fn preedit(&self) -> Option<&Preedit> { self.preedit.as_ref() } } #[derive(Debug, Default, PartialEq, Eq)] pub struct Preedit { /// The preedit text. text: String, /// Byte offset for cursor start into the preedit text. /// /// `None` means that the cursor is invisible. cursor_byte_offset: Option<usize>, /// The cursor offset from the end of the preedit in char width. cursor_end_offset: Option<usize>, } impl Preedit { pub fn new(text: String, cursor_byte_offset: Option<usize>) -> Self { let cursor_end_offset = if let Some(byte_offset) = cursor_byte_offset { // Convert byte offset into char offset. let cursor_end_offset = text[byte_offset..].chars().fold(0, |acc, ch| acc + ch.width().unwrap_or(1)); Some(cursor_end_offset) } else { None }; Self { text, cursor_byte_offset, cursor_end_offset } } } /// Pending renderer updates. /// /// All renderer updates are cached to be applied just before rendering, to avoid platform-specific /// rendering issues. #[derive(Debug, Default, Copy, Clone)] pub struct RendererUpdate { /// Should resize the window. resize: bool, /// Clear font caches. clear_font_cache: bool, } /// Struct for safe in-place replacement. /// /// This struct allows easily replacing struct fields that provide `self -> Self` methods in-place, /// without having to deal with constantly unwrapping the underlying [`Option`]. struct Replaceable<T>(Option<T>); impl<T> Replaceable<T> { pub fn new(inner: T) -> Self { Self(Some(inner)) } /// Replace the contents of the container. pub fn replace_with<F: FnMut(T) -> T>(&mut self, f: F) { self.0 = self.0.take().map(f); } /// Get immutable access to the wrapped value. pub fn get(&self) -> &T { self.0.as_ref().unwrap() } /// Get mutable access to the wrapped value. pub fn get_mut(&mut self) -> &mut T { self.0.as_mut().unwrap() } } impl<T> Deref for Replaceable<T> { type Target = T; fn deref(&self) -> &Self::Target { self.get() } } impl<T> DerefMut for Replaceable<T> { fn deref_mut(&mut self) -> &mut Self::Target { self.get_mut() } } /// Calculate the cell dimensions based on font metrics. /// /// This will return a tuple of the cell width and height. #[inline] fn compute_cell_size(config: &UiConfig, metrics: &crossfont::Metrics) -> (f32, f32) { let offset_x = f64::from(config.font.offset.x); let offset_y = f64::from(config.font.offset.y); ( (metrics.average_advance + offset_x).floor().max(1.) as f32, (metrics.line_height + offset_y).floor().max(1.) as f32, ) } /// Calculate the size of the window given padding, terminal dimensions and cell size. fn window_size( config: &UiConfig, dimensions: Dimensions, cell_width: f32, cell_height: f32, scale_factor: f32, ) -> PhysicalSize<u32> { let padding = config.window.padding(scale_factor); let grid_width = cell_width * dimensions.columns.0.max(MIN_COLUMNS) as f32; let grid_height = cell_height * dimensions.lines.max(MIN_SCREEN_LINES) as f32; let width = (padding.0).mul_add(2., grid_width).floor(); let height = (padding.1).mul_add(2., grid_height).floor(); PhysicalSize::new(width as u32, height as u32) }
{'content_hash': 'a4697cd42cc8718268e032ff3db99615', 'timestamp': '', 'source': 'github', 'line_count': 1554, 'max_line_length': 100, 'avg_line_length': 34.072072072072075, 'alnum_prop': 0.5720140515222483, 'repo_name': 'alacritty/alacritty', 'id': 'ed1b1fc53b3001294cbeb0f89825332d79f639ed', 'size': '53047', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'alacritty/src/display/mod.rs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '10739'}, {'name': 'Makefile', 'bytes': '2941'}, {'name': 'Roff', 'bytes': '4196'}, {'name': 'Rust', 'bytes': '1011078'}, {'name': 'Shell', 'bytes': '17333'}]}
""" WSGI config for django_calendar project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_calendar.settings") application = get_wsgi_application()
{'content_hash': 'a16031a488f80c25cd19334dcc2f1bd4', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 78, 'avg_line_length': 25.4375, 'alnum_prop': 0.773955773955774, 'repo_name': 'psycane/django-calendar', 'id': 'e98ed05c9cc29a3c6c4ab5585b3cbd6fbbe9768c', 'size': '407', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'django_calendar/wsgi.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4683'}, {'name': 'HTML', 'bytes': '4914'}, {'name': 'JavaScript', 'bytes': '12531'}, {'name': 'Python', 'bytes': '26928'}]}
var request = require('request'); var fs = require('fs'); var YOUR_ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"; var YOUR_PRODUCT_ID = 0; var that = { baseUrl: "https://api.particle.io", GENERIC_PUBLIC_KEY: "-----BEGIN PUBLIC KEY-----\n" + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBLiA/XITqywdja3J2dCPLfqcU\n" + "jdacNaGBys6Xz1TJCyq4NSUtr8RU7AkWP3e/ePKp5Lg/vJnEBo1Z8gPR1QMWAWup\n" + "Gqz+S9DxIBwCIeVXovZE6ZFRZ6m0dsCBnZ36UuME2vBS70cL6yzfu71fRDeGg4Lh\n" + "yr+GNspjRSDkqgeBUQIDAQAB\n" + "-----END PUBLIC KEY-----", sendPublicKey: function (deviceID, keyFilename) { if (!deviceID || deviceID == "") { console.error("device id was invalid"); return; } var keyStr; if (!keyFilename || (keyFilename == "") || !fs.existsSync(keyFilename)) { console.log("using generic public key"); keyStr = that.GENERIC_PUBLIC_KEY; } else { keyStr = fs.readFileSync(keyFilename).toString(); } console.log('attempting to add a new public key for device ' + deviceID); request({ uri: that.baseUrl + "/v1/provisioning/" + deviceID, method: "POST", form: { deviceID: deviceID, publicKey: keyStr.toString(), order: "script_" + ((new Date()).getTime()), filename: "script", access_token: YOUR_ACCESS_TOKEN, product_id: YOUR_PRODUCT_ID }, json: true }, function (error, response, body) { if (error || body.error) { console.log("Provisioning Error: ", error || body.error); } else { console.log("Success - Device Provisioned!"); } }); } }; var args = process.argv; if (YOUR_ACCESS_TOKEN == "YOUR_ACCESS_TOKEN") { console.error("Please edit main.js, and change YOUR_ACCESS_TOKEN to your access token" ); return; } if (YOUR_PRODUCT_ID == 0) { console.error("Please edit main.js, and change PRODUCT_ID to your product id"); return; } if (args.length < 3) { var helpLines = [ "Please include deviceID, and an optional keyfile", "", "Example: ", " node main.js SOME_DEVICE_ID ", " node main.js SOME_DEVICE_ID SOME_KEY_FILE" ]; console.log(helpLines.join("\n")); } else { var deviceID = args[2]; var keyFile = (args.length >= 4) ? args[3] : null; that.sendPublicKey(deviceID, keyFile); }
{'content_hash': '7c1ac1b6a0f9e0783bb44cfef7d57808', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 90, 'avg_line_length': 24.41111111111111, 'alnum_prop': 0.6536185707783341, 'repo_name': 'spark/device-provisioning-helper', 'id': '9bca5e64beffdc328f606b4b3e96a70d091d447d', 'size': '2197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'main.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '2197'}]}
**NeedsWork** | [#roslyn/57589](https://github.com/dotnet/roslyn/issues/57589#issuecomment-985038558) ## API Review * Most of the generator examples we've seen as motivating examples are v1 generators that, when factored into incremental generators, have perfectly fine performance. * Doesn't help with Hot Reload or EnC scenarios, which need full implementation results * Only for the application of edits, not for things like intellisense * Workaround is available: register 2 generators, one that registers partials with empty bodies, one that provides the real implementation with our existing API * If you did it this way, it would require partial consistency, whereas the ReferenceSourceOnly version could make it harder to ensure that these things line up. Would have errors * Might have been nice if we had done a slightly different design. What if we just did RegisterSourceOutput, and put a flag on it? * Would that cause us to have to run generators twice, even if they didn't check that flag? * Can RegisterReferenceSourceOutput actually change the reference assembly output? * They probably can do that, so we're ok * Might need a slightly better name * We'll bikeshed over this when we have perf data. ### Conclusion We think the API shape is reasonable (modulo the name), but we would like data on whether it actually helps our motivating generators before shipping the API for real.
{'content_hash': 'd0ba96751db263345a4729d034a1db86', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 167, 'avg_line_length': 72.2, 'alnum_prop': 0.7721606648199446, 'repo_name': 'dotnet/apireviews', 'id': '30b5ebe97d7e50646d7ee76920ec08f15477b034', 'size': '1522', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': '2021/12-02-roslyn-reviews/README.md', 'mode': '33188', 'license': 'mit', 'language': []}
<html><body> <h4>Windows 10 x64 (18362.388)</h4><br> <h2>_POP_DIRECTED_DRIPS_PROBLEM_DEVICE_REASON</h2> <font face="arial"> DirectedDripsProblemDeviceReasonSpecialDevice = 0n0<br> DirectedDripsProblemDeviceReasonNoDfx = 0n1<br> DirectedDripsProblemDeviceReasonNoPs4 = 0n2<br> DirectedDripsProblemDeviceReasonNoPs4Root = 0n3<br> DirectedDripsProblemDeviceReasonComponentContraint = 0n4<br> DirectedDripsProblemDeviceReasonDfxFailure = 0n5<br> DirectedDripsProblemDeviceReasonMax = 0n6<br> </font></body></html>
{'content_hash': '95c5587e3ced469161099f905be5ea78', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 77, 'avg_line_length': 49.0, 'alnum_prop': 0.7792207792207793, 'repo_name': 'epikcraw/ggool', 'id': 'd13d2b4f4077782f120c45b7eb37ab2d73c5dce0', 'size': '539', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/Windows 10 x64 (18362.388)/_POP_DIRECTED_DRIPS_PROBLEM_DEVICE_REASON.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '17631902'}, {'name': 'JavaScript', 'bytes': '552'}]}
! ! Copyright 2016 ARTED developers ! ! Licensed under the Apache License, Version 2.0 (the "License"); ! you may not use this file except in compliance with the License. ! You may obtain a copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0 ! ! Unless required by applicable law or agreed to in writing, software ! distributed under the License is distributed on an "AS IS" BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ! See the License for the specific language governing permissions and ! limitations under the License. ! module PSE_band_calc_variables integer :: Nsym_point, NB_band_calc real(8),allocatable :: b0_band_vec(:), band_Cvec_d(:,:) character(10),allocatable :: Name_sym_point(:) integer,allocatable :: Ndist_band(:) end module PSE_band_calc_variables
{'content_hash': '3eda86fb5b3be9ae65c9b0db17d32ec2', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 75, 'avg_line_length': 36.78260869565217, 'alnum_prop': 0.7328605200945626, 'repo_name': 'ARTED/ARTED_noc', 'id': '2ad5931a1ba8a20cb345029017293c965d7cd740', 'size': '846', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/PSE_band_calc_variables.f90', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Fortran', 'bytes': '244698'}, {'name': 'Makefile', 'bytes': '1442'}]}
package bazaar4idea.command; import com.intellij.openapi.project.Project; import bazaar4idea.BzrFile; import org.jetbrains.annotations.NotNull; import java.util.Arrays; public class BzrAddCommand { private final Project project; public BzrAddCommand(Project project) { this.project = project; } public void execute(@NotNull BzrFile bzrFile) { ShellCommandService.getInstance(project) .execute(bzrFile.getRepo(), "add", Arrays.asList(bzrFile.getRelativePath())); } }
{'content_hash': 'ad150684411f5749bab1ec6d39934762', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 85, 'avg_line_length': 22.681818181818183, 'alnum_prop': 0.7555110220440882, 'repo_name': 'bwrsandman/bzr4j', 'id': '049a9d6a6d276749409d009c405228f7e7e28471', 'size': '1083', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/intellij/src/main/java/bazaar4idea/command/BzrAddCommand.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1044148'}, {'name': 'Shell', 'bytes': '31'}]}
namespace TehPers.FishingOverhaul.Api { /// <summary> /// The state of the treasure in the fishing minigame. /// </summary> public enum TreasureState { /// <summary> /// No treasure can be caught. /// </summary> None, /// <summary> /// Treasure can be caught, but it has not yet been caught. /// </summary> NotCaught, /// <summary> /// Treasure was caught. /// </summary> Caught, } }
{'content_hash': '6f75e275c7ae88341ad5fe89bba1a5cd', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 67, 'avg_line_length': 24.0, 'alnum_prop': 0.503968253968254, 'repo_name': 'TehPers/StardewValleyMods', 'id': 'f769c399f89d6b23132204fb4c23e1dcecdfa231', 'size': '506', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/TehPers.FishingOverhaul.Api/TreasureState.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '743286'}, {'name': 'PowerShell', 'bytes': '861'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.12"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Tempest: Tempest::slot Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="style.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="icon.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Tempest </div> </td> <td> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.12 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('class_tempest_1_1slot.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#pro-methods">Protected Member Functions</a> &#124; <a href="#friends">Friends</a> &#124; <a href="class_tempest_1_1slot-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">Tempest::slot Class Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for Tempest::slot:</div> <div class="dyncontent"> <div class="center"> <img src="class_tempest_1_1slot.png" usemap="#Tempest::slot_map" alt=""/> <map id="Tempest::slot_map" name="Tempest::slot_map"> <area href="class_tempest_1_1_list_delegate.html" title="The ListDelegate class provides items to display in list or other collection. " alt="Tempest::ListDelegate" shape="rect" coords="876,56,1304,80"/> <area href="class_tempest_1_1_menu.html" alt="Tempest::Menu" shape="rect" coords="1314,56,1742,80"/> <area href="class_tempest_1_1_widget.html" alt="Tempest::Widget" shape="rect" coords="1752,56,2180,80"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; bool &gt;" shape="rect" coords="438,112,866,136"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; const std::u16string &amp;&gt;" shape="rect" coords="438,168,866,192"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; const std::u16string, const Tempest::Rect &amp;&gt;" shape="rect" coords="438,224,866,248"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; const Tempest::Menu::Declarator &amp;, Tempest::Widget &amp;&gt;" shape="rect" coords="438,280,866,304"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; int &gt;" shape="rect" coords="438,336,866,360"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; int, int &gt;" shape="rect" coords="438,392,866,416"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; ShowMode &gt;" shape="rect" coords="438,448,866,472"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; size_t &gt;" shape="rect" coords="438,504,866,528"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; size_t, Tempest::Widget *&gt;" shape="rect" coords="438,560,866,584"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; State &gt;" shape="rect" coords="438,616,866,640"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; Tempest::Font &gt;" shape="rect" coords="438,672,866,696"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; Tempest::Orientation &gt;" shape="rect" coords="438,728,866,752"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; Tempest::UiMetrics &gt;" shape="rect" coords="438,784,866,808"/> <area href="class_tempest_1_1signal.html" alt="Tempest::signal&lt; Tempest::Widget *&gt;" shape="rect" coords="438,840,866,864"/> <area href="class_tempest_1_1signal.html" title="signal class, for signals and slots system. " alt="Tempest::signal&lt; Args &gt;" shape="rect" coords="438,896,866,920"/> <area href="class_tempest_1_1_abstract_list_delegate.html" alt="Tempest::AbstractListDelegate&lt; T, std::vector&lt; T &gt;, Ctrl &gt;" shape="rect" coords="1314,112,1742,136"/> <area href="class_tempest_1_1_abstract_list_delegate.html" alt="Tempest::AbstractListDelegate&lt; T, VT, Ctrl &gt;" shape="rect" coords="1314,168,1742,192"/> <area href="class_tempest_1_1_abstract_list_box.html" alt="Tempest::AbstractListBox" shape="rect" coords="2190,112,2618,136"/> <area href="class_tempest_1_1_button.html" alt="Tempest::Button" shape="rect" coords="2190,168,2618,192"/> <area href="class_tempest_1_1_image.html" alt="Tempest::Image&lt; InTexture &gt;" shape="rect" coords="2190,224,2618,248"/> <area href="class_tempest_1_1_label.html" alt="Tempest::Label" shape="rect" coords="2190,280,2618,304"/> <area href="class_tempest_1_1_line_edit.html" alt="Tempest::LineEdit" shape="rect" coords="2190,336,2618,360"/> <area href="class_tempest_1_1_list_view.html" alt="Tempest::ListView" shape="rect" coords="2190,392,2618,416"/> <area href="class_tempest_1_1_panel.html" alt="Tempest::Panel" shape="rect" coords="2190,448,2618,472"/> <area href="class_tempest_1_1_scroll_bar.html" alt="Tempest::ScrollBar" shape="rect" coords="2190,504,2618,528"/> <area href="struct_tempest_1_1_scroll_bar_1_1_central_widget.html" alt="Tempest::ScrollBar::CentralWidget" shape="rect" coords="2190,560,2618,584"/> <area href="class_tempest_1_1_scroll_widget.html" alt="Tempest::ScrollWidget" shape="rect" coords="2190,616,2618,640"/> <area href="class_tempest_1_1_stacked_widget.html" alt="Tempest::StackedWidget" shape="rect" coords="2190,672,2618,696"/> <area href="class_tempest_1_1_surface.html" alt="Tempest::Surface" shape="rect" coords="2190,728,2618,752"/> <area href="class_tempest_1_1_window.html" alt="Tempest::Window" shape="rect" coords="2190,784,2618,808"/> <area href="class_tempest_1_1_window_overlay.html" alt="Tempest::WindowOverlay" shape="rect" coords="2190,840,2618,864"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a> Protected Member Functions</h2></td></tr> <tr class="memitem:a560d84cb8d2504b2dfb251c0e46a793e"><td class="memItemLeft" align="right" valign="top"><a id="a560d84cb8d2504b2dfb251c0e46a793e"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>slot</b> (const <a class="el" href="class_tempest_1_1slot.html">slot</a> &amp;other)</td></tr> <tr class="separator:a560d84cb8d2504b2dfb251c0e46a793e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:adde8e77fdbe24660b6155b0fa7d12647"><td class="memItemLeft" align="right" valign="top"><a id="adde8e77fdbe24660b6155b0fa7d12647"></a> <a class="el" href="class_tempest_1_1slot.html">slot</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><b>operator=</b> (<a class="el" href="class_tempest_1_1slot.html">slot</a> &amp;other)</td></tr> <tr class="separator:adde8e77fdbe24660b6155b0fa7d12647"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a> Friends</h2></td></tr> <tr class="memitem:a4d8dd8d7128a1ee29556fc24f581b420"><td class="memItemLeft" align="right" valign="top"><a id="a4d8dd8d7128a1ee29556fc24f581b420"></a> class&#160;</td><td class="memItemRight" valign="bottom"><b>Detail::signalBase</b></td></tr> <tr class="separator:a4d8dd8d7128a1ee29556fc24f581b420"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af9add2352f0d4e501677b8a511a74475"><td class="memTemplParams" colspan="2"><a id="af9add2352f0d4e501677b8a511a74475"></a> template&lt;class ... Args&gt; </td></tr> <tr class="memitem:af9add2352f0d4e501677b8a511a74475"><td class="memTemplItemLeft" align="right" valign="top">class&#160;</td><td class="memTemplItemRight" valign="bottom"><b>Tempest::signal</b></td></tr> <tr class="separator:af9add2352f0d4e501677b8a511a74475"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this class was generated from the following file:<ul> <li><a class="el" href="signal__slot_8h_source.html">signal_slot.h</a></li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><b>Tempest</b></li><li class="navelem"><a class="el" href="class_tempest_1_1slot.html">slot</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.12 </li> </ul> </div> </body> </html>
{'content_hash': '0de2227a8d18087cb449f0f240a2625a', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 210, 'avg_line_length': 63.71508379888268, 'alnum_prop': 0.695572117492328, 'repo_name': 'enotio/Tempest', 'id': '550f9721a23c54564c6ef3e53e09682518965ce4', 'size': '11405', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/class_tempest_1_1slot.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '209674'}, {'name': 'C++', 'bytes': '997335'}, {'name': 'CSS', 'bytes': '26404'}, {'name': 'Java', 'bytes': '10502'}, {'name': 'Makefile', 'bytes': '3047'}, {'name': 'Objective-C', 'bytes': '387'}, {'name': 'Objective-C++', 'bytes': '50885'}, {'name': 'QML', 'bytes': '1647'}, {'name': 'QMake', 'bytes': '11871'}]}
module Spree class LoyaltyPointsDebitTransaction < LoyaltyPointsTransaction after_create :update_user_balance before_create :update_balance private def update_user_balance user.decrement(:loyalty_points_balance, loyalty_points) user.save! end def update_balance self.balance = user.loyalty_points_balance - loyalty_points end end end
{'content_hash': 'db25e7b6e44319a11b2559effa97fd3e', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 67, 'avg_line_length': 22.27777777777778, 'alnum_prop': 0.6957605985037406, 'repo_name': 'Hrom512/spree-loyalty-points', 'id': '9c3cf591e4a5bdb15eb2cf8479dc86f8c25d6510', 'size': '401', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/models/spree/loyalty_points_debit_transaction.rb', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '144'}, {'name': 'HTML', 'bytes': '5990'}, {'name': 'JavaScript', 'bytes': '3911'}, {'name': 'Ruby', 'bytes': '109616'}]}
#ifndef QMITKXNATTREEMODEL_H #define QMITKXNATTREEMODEL_H // CTK includes #include <ctkXnatTreeModel.h> // MITK includes #include "MitkXNATExports.h" namespace mitk { class DataNode; } class MITKXNAT_EXPORT QmitkXnatTreeModel : public ctkXnatTreeModel { Q_OBJECT public: QmitkXnatTreeModel(); virtual QVariant data(const QModelIndex& index, int role) const; virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); using QAbstractItemModel::supportedDropActions; virtual Qt::DropActions supportedDropActions(); virtual Qt::ItemFlags flags(const QModelIndex &index) const; ctkXnatObject* GetXnatObjectFromUrl(const QString&); signals: void ResourceDropped(const QList<mitk::DataNode*>&, ctkXnatObject*, const QModelIndex&); private: ctkXnatObject *InternalGetXnatObjectFromUrl(const QString &xnatObjectType, const QString &url, ctkXnatObject *parent); }; #endif // QMITKXNATTREEMODEL_H
{'content_hash': '8e43d960931d1547c0b3c8f4b6e3d2c3', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 122, 'avg_line_length': 23.547619047619047, 'alnum_prop': 0.7785642062689585, 'repo_name': 'NifTK/MITK', 'id': '90ae8788864fd54b315e56d3d726fdfcceeb254d', 'size': '1487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/niftk', 'path': 'Modules/XNAT/include/QmitkXnatTreeModel.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '2343401'}, {'name': 'C++', 'bytes': '28797565'}, {'name': 'CMake', 'bytes': '864932'}, {'name': 'CSS', 'bytes': '117579'}, {'name': 'HTML', 'bytes': '101835'}, {'name': 'JavaScript', 'bytes': '167070'}, {'name': 'Makefile', 'bytes': '25077'}, {'name': 'Objective-C', 'bytes': '476388'}, {'name': 'Python', 'bytes': '62916'}, {'name': 'QMake', 'bytes': '5583'}, {'name': 'Shell', 'bytes': '1261'}]}
/** @file @ingroup pgm @brief opengm extensions */ #ifndef PGMLINK_PGM_H #define PGMLINK_PGM_H #include <vector> #include <pgmlink/ext_opengm/loss_hamming.hxx> #include <opengm/graphicalmodel/graphicalmodel.hxx> #include <pgmlink/ext_opengm/loglinearmodel.hxx> #include <opengm/inference/inference.hxx> #include <opengm/functions/explicit_function.hxx> #include <pgmlink/ext_opengm/decorator_weighted.hxx> #include <pgmlink/ext_opengm/indicator_function.hxx> #include <opengm/operations/adder.hxx> #include <opengm/utilities/metaprogramming.hxx> #include "pgmlink/hypotheses.h" #include "pgmlink/graph.h" #include "pgmlink/util.h" namespace pgmlink { namespace pgm { using boost::shared_ptr; //typedef opengm::GraphicalModel<double, opengm::Adder> OpengmModel; typedef opengm::ExplicitFunction<double> ExplicitFunction; typedef opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<double> > FeatureFunction; typedef opengm::HammingFunction<double> LossFunction; typedef opengm::LoglinearModel<double, opengm::meta::TypeList<ExplicitFunction, opengm::meta::TypeList<FeatureFunction, opengm::meta::TypeList<LossFunction, opengm::meta::ListEnd > > > > OpengmModel; template <typename OGM_FUNCTION> class OpengmFactor { public: typedef OGM_FUNCTION FunctionType; OpengmFactor( const FunctionType&, const std::vector<size_t>& ogm_var_indices ); template <typename ITER> OpengmFactor( const FunctionType&, ITER first_ogm_idx, ITER last_ogm_idx ); typename FunctionType::ValueType get_value( std::vector<size_t> coords ) const; template <typename OGM_GRAPHICAL_MODEL> void add_to( OGM_GRAPHICAL_MODEL& ) const; FunctionType& function() { return ogmfunction_; } const FunctionType& function() const { return ogmfunction_; } const std::vector<size_t>& var_indices() const { return vi_; } const std::vector<size_t>& var_order() const { return order_; } protected: FunctionType ogmfunction_; std::vector<size_t> vi_; std::vector<size_t> order_; }; template <typename VALUE> class OpengmExplicitFactor : public OpengmFactor<opengm::ExplicitFunction<VALUE> > { public: typedef typename OpengmFactor<opengm::ExplicitFunction<VALUE> >::FunctionType FunctionType; OpengmExplicitFactor( const std::vector<size_t>& ogm_var_indices, VALUE init=0, size_t states_per_var=2 ); template <typename ITER> OpengmExplicitFactor( ITER first_ogm_idx, ITER last_ogm_idx, VALUE init=0, size_t states_per_var=2 ); void set_value( std::vector<size_t> coords, VALUE v); private: void init_( VALUE init, size_t states_per_var ); }; template <typename VALUE> class OpengmWeightedFeature : public OpengmFactor< opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<VALUE> > > { public: typedef typename opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<VALUE> > FunctionType; template<class IT1, class IT2> OpengmWeightedFeature(const std::vector<size_t>& ogm_var_indices, IT1 shapeBegin, IT1 shapeEnd, IT2 indicate, VALUE indicate_value = 1., VALUE weight = 1., VALUE default_value = 0); template <typename OGM_LOGLINEARMODEL> void add_as_feature_to( OGM_LOGLINEARMODEL&, typename OGM_LOGLINEARMODEL::IndexType weight_index ) const; void weight( VALUE w ); VALUE weight() const; void indicate_value( VALUE v ); VALUE indicate_value() const; void default_value( VALUE v ); VALUE default_value() const; }; /** @brief Accessing entries of a Factor/Function that was already added to a graphical model. Manages a pointer to an element of an array-like opengm function (usually opengm::ExplicitFunction). Validity of the pointer is ensured by owning a smart pointer to the full model. Use this class to modify factor elements of an already instantiated opengm graphical model. */ class FactorEntry { public: FactorEntry() : entry_(NULL) {} FactorEntry( shared_ptr<OpengmModel> m, /**< has to be valid */ OpengmModel::ValueType* entry /**< has to point into the opengm model to ensure the same lifetime */ ) : m_(m), entry_(entry) {} void set( OpengmModel::ValueType ); OpengmModel::ValueType get() const; shared_ptr<OpengmModel> model() const { return m_; } private: shared_ptr<OpengmModel> m_; OpengmModel::ValueType* entry_; }; /******************/ /* Implementation */ /******************/ //// //// class OpengmFactor //// template <typename OGM_FUNCTION> OpengmFactor<OGM_FUNCTION>::OpengmFactor( const FunctionType& f, const std::vector<size_t>& ogm_var_indices ) : ogmfunction_(f), vi_(ogm_var_indices) { // store sorted order of indices indexsorter::sort_indices( vi_.begin(), vi_.end(), order_ ); } template <typename OGM_FUNCTION> template< typename ITER > OpengmFactor<OGM_FUNCTION>::OpengmFactor( const FunctionType& f, ITER first_ogm_idx, ITER last_ogm_idx ) : ogmfunction_(f), vi_(first_ogm_idx, last_ogm_idx) { // store sorted order of indices indexsorter::sort_indices( vi_.begin(), vi_.end(), order_ ); } template <typename OGM_FUNCTION> typename OpengmFactor<OGM_FUNCTION>::FunctionType::ValueType OpengmFactor<OGM_FUNCTION>::get_value( std::vector<size_t> coords ) const { if( coords.size() != vi_.size() ) { throw std::invalid_argument("OpengmFactor::get_value(): coordinate dimension differs from factor dimension"); } indexsorter::reorder( coords, order_ ); return ogmfunction_(coords.begin()); } template <typename OGM_FUNCTION> template <typename OGM_GRAPHICAL_MODEL> void OpengmFactor<OGM_FUNCTION>::add_to( OGM_GRAPHICAL_MODEL& m ) const { std::vector<size_t> sorted_vi(vi_); std::sort(sorted_vi.begin(), sorted_vi.end()); // opengm expects a monotonic increasing sequence if(!(m.isValidIndexSequence(sorted_vi.begin(), sorted_vi.end()))) { throw std::runtime_error("OpengmExplicitFactor::add_to(): invalid index sequence"); } typename OGM_GRAPHICAL_MODEL::FunctionIdentifier id=m.addFunction( ogmfunction_ ); m.addFactor(id, sorted_vi.begin(), sorted_vi.end()); } //// //// class OpengmExplicitFactor //// template <typename VALUE> OpengmExplicitFactor<VALUE>::OpengmExplicitFactor( const std::vector<size_t>& ogm_var_indices, VALUE init, size_t states_per_var ) : OpengmFactor<opengm::ExplicitFunction<VALUE> >(opengm::ExplicitFunction<VALUE>(), ogm_var_indices) { init_( init, states_per_var ); } template <typename VALUE> template< typename ITER > OpengmExplicitFactor<VALUE>::OpengmExplicitFactor( ITER first_ogm_idx, ITER last_ogm_idx, VALUE init, size_t states_per_var ) : OpengmFactor<opengm::ExplicitFunction<VALUE> >(opengm::ExplicitFunction<VALUE>(),first_ogm_idx, last_ogm_idx) { init_( init, states_per_var ); } template <typename VALUE> void OpengmExplicitFactor<VALUE>::set_value( std::vector<size_t> coords, VALUE v) { if( coords.size() != this->vi_.size() ) { throw std::invalid_argument("OpengmExplicitFactor::set_value(): coordinate dimension differs from factor dimension"); } typename opengm::ExplicitFunction<VALUE>::iterator element( this->ogmfunction_ ); size_t index; indexsorter::reorder( coords, this->order_ ); this->ogmfunction_.coordinatesToIndex(coords.begin(), index); element[index] = v; } template <typename VALUE> void OpengmExplicitFactor<VALUE>::init_( VALUE init, size_t states_per_var ) { std::vector<size_t> shape( this->vi_.size(), states_per_var ); this->ogmfunction_ = opengm::ExplicitFunction<VALUE>( shape.begin(), shape.end(), init ); } //// //// class OpengmWeightedFeature //// template<class VALUE> template<class IT1, class IT2> OpengmWeightedFeature<VALUE>::OpengmWeightedFeature( const std::vector<size_t>& ogm_var_indices, IT1 shapeBegin, IT1 shapeEnd, IT2 indicate, VALUE indicate_value, VALUE weight, VALUE default_value) : OpengmFactor<FunctionType >(FunctionType(new opengm::IndicatorFunction<VALUE>( shapeBegin, shapeEnd, indicate, indicate_value, default_value), weight) , ogm_var_indices) { // replace function with a sorted variant std::vector<size_t> sorted_shape( shapeBegin, shapeEnd ); indexsorter::reorder( sorted_shape, this->order_ ); std::vector<size_t> sorted_indicate( this->ogmfunction_.innerFunction()->indicate() ); indexsorter::reorder( sorted_indicate, this->order_ ); this->ogmfunction_ = FunctionType(new opengm::IndicatorFunction<VALUE>( sorted_shape.begin(), sorted_shape.end(), sorted_indicate.begin(), indicate_value, default_value), weight); } template<class VALUE> template <typename OGM_LOGLINEARMODEL> void OpengmWeightedFeature<VALUE>::add_as_feature_to( OGM_LOGLINEARMODEL& m, typename OGM_LOGLINEARMODEL::IndexType weight_index ) const { std::vector<size_t> sorted_vi(this->vi_); std::sort(sorted_vi.begin(), sorted_vi.end()); // opengm expects a monotonic increasing sequence if(!(m.isValidIndexSequence(sorted_vi.begin(), sorted_vi.end()))) { throw std::runtime_error("OpengmExplicitFactor::add_to(): invalid index sequence"); } typename OGM_LOGLINEARMODEL::FunctionIdentifier id=m.addFeature( this->ogmfunction_, weight_index ); m.addFactor(id, sorted_vi.begin(), sorted_vi.end()); } template<class VALUE> void OpengmWeightedFeature<VALUE>::weight( VALUE w ) { this->ogmfunction_.weight(w); } template<class VALUE> VALUE OpengmWeightedFeature<VALUE>::weight() const { return this->ogmfunction_.weight(); } template<class VALUE> void OpengmWeightedFeature<VALUE>::indicate_value( VALUE v ) { this->ogmfunction_.innerFunction()->indicate_value(v); } template<class VALUE> VALUE OpengmWeightedFeature<VALUE>::indicate_value() const { return this->ogmfunction_.innerFunction()->indicate_value(); } template<class VALUE> void OpengmWeightedFeature<VALUE>::default_value( VALUE v ) { this->ogmfunction_.innerFunction()->default_value(v); } template<class VALUE> VALUE OpengmWeightedFeature<VALUE>::default_value() const { return this->ogmfunction_.innerFunction()->default_value(); } } /* namespace pgm */ } /* namespace pgmlink */ #endif /* PGMLINK_PGM_H */
{'content_hash': '3015b75121017203bb32dacffbecb1c6', 'timestamp': '', 'source': 'github', 'line_count': 298, 'max_line_length': 140, 'avg_line_length': 35.486577181208055, 'alnum_prop': 0.689645390070922, 'repo_name': 'bekaus/pgmlink', 'id': '578e09d65d234881d4fc9a41fa979bc8cb5ebaae', 'size': '10575', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/pgmlink/pgm.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '248858'}, {'name': 'Python', 'bytes': '2086'}]}
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Chelsea+Market|Harmattan|Rancho" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> <link rel="stylesheet" href="/style/style.css"> <link rel="apple-touch-icon" sizes="180x180" href="/src/img/icons/trailTracker_icon-180.png" /> <link rel="manifest" href=“/src/img/icons/manifest.json” /> <link rel="icon" type="image/png" href="/src/img/icons/trailTracker_icon-32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="/src/img/icons/trailTracker_icon-16.png" sizes="16x16" /> <!-- <script src="https://maps.googleapis.com/maps/api/js"></script> --> </head> <body> <div id="container"></div> </body> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> <script src="/bundle.js"></script> </html>
{'content_hash': 'c51d8e082dd9ea83435a68ee98bd536d', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 220, 'avg_line_length': 73.24, 'alnum_prop': 0.744401966138722, 'repo_name': 'JohnDHamm/trail-tracker-react', 'id': '351b83d94a1680b568b226c7d397a91bb84a8530', 'size': '1835', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1795'}, {'name': 'HTML', 'bytes': '1835'}, {'name': 'JavaScript', 'bytes': '50673'}]}
module Carto module OauthProvider module Scopes class DataservicesScope < DefaultScope def initialize(service, description) super('dataservices', service, CATEGORY_MONEY, description) @grant_key = :services end def add_to_api_key_grants(grants, _user = nil) super(grants) ensure_includes_apis(grants, ['sql']) end end end end end
{'content_hash': 'e22bf14c52f34c9c5360a286847f2e72', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 69, 'avg_line_length': 25.11764705882353, 'alnum_prop': 0.6088992974238876, 'repo_name': 'CartoDB/cartodb', 'id': '102eecd84e40824fe0b967e92389e4005b32b7dc', 'size': '427', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/carto/oauth_provider/scopes/dataservices_scope.rb', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '7083'}, {'name': 'EJS', 'bytes': '311401'}, {'name': 'HTML', 'bytes': '6933668'}, {'name': 'JavaScript', 'bytes': '9784580'}, {'name': 'Jupyter Notebook', 'bytes': '47684'}, {'name': 'Makefile', 'bytes': '14050'}, {'name': 'Mustache', 'bytes': '30410'}, {'name': 'PLpgSQL', 'bytes': '1233'}, {'name': 'Procfile', 'bytes': '189'}, {'name': 'Python', 'bytes': '10350'}, {'name': 'Ruby', 'bytes': '6995180'}, {'name': 'SCSS', 'bytes': '1454540'}, {'name': 'Shell', 'bytes': '14538'}, {'name': 'Smarty', 'bytes': '654458'}, {'name': 'Vue', 'bytes': '755091'}]}
import isAngle from './isAngle' import isColor from './isColor' import isCubicBezier from './isCubicBezier' import isFrames from './isFrames' import isGlobal from './isGlobal' import isImage from './isImage' import isLength from './isLength' import isLengthPercentage from './isLengthPercentage' import isNumber from './isNumber' import isOpacity from './isOpacity' import isPercentage from './isPercentage' import isPosition from './isPosition' import isRepeat from './isRepeat' import isSize from './isSize' import isSteps from './isSteps' import isSvgLength from './isSvgLength' import isTime from './isTime' export { isAngle, isColor, isCubicBezier, isFrames, isGlobal, isImage, isLength, isLengthPercentage, isNumber, isOpacity, isPercentage, isPosition, isRepeat, isSize, isSteps, isSvgLength, isTime, }
{'content_hash': '677677d4bb72047a7ef1ba2d49629e08', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 53, 'avg_line_length': 22.83783783783784, 'alnum_prop': 0.7514792899408284, 'repo_name': 'rofrischmann/bredon', 'id': '4edcbaba4ce63c30098c104686a3ffd89d832494', 'size': '845', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/bredon-validate/src/types/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '137500'}, {'name': 'JavaScript', 'bytes': '321255'}, {'name': 'Shell', 'bytes': '682'}]}
/*------------------------------------------------------------------------- * Script contains key operations for the Remote Control. * * DEPENDENCIES * - Logger.js *-------------------------------------------------------------------------*/ /** Flag to indicate whether the remote button is pressed or not.*/ var isMouseDown = false; /** Latest key to be send.*/ var latest_key; /** Latest key event which is to be send. */ var latest_event; /** Function invoked when the DOM is ready.*/ $(function() { $("#skeyboard,#shard-power,#skeyhelp").tooltip({ show: { effect: "slideDown", delay: 2000 }, hide: { effect: "puff", } }); /* Captures mouse out event for the DOM body and if holdkey action is in-progress (isMouseDown = true), it will generate * a mouseup event on the latest key to complete the hold action.*/ $('body').mouseout(function() { if (isMouseDown) { clickRemoteButton(latest_event, latest_key, false); } }); /* Creates a tabbed interface for trace and event logs. */ $('.traceTab').tabs({ /* Invoked when a tab widget is selected. */ activate : function(event, ui) { var container; var index = ui.newTab.index(); if( index === 0) { container = $(getVisibleTraceContainer()+' .traceDisp'); } else if(index === 1) { container = $(getVisibleTraceContainer()+' .eventDisp'); } doAutoScrolling(container); } }); }); /** Constant regex pattern for Non blinking keys. Applicable for hold actions. */ var non_blinking_key_pattern = /VOL(UP|DN)|CH(UP|DN)/; /** * Sends a key to the server to be forwarded to the stb * @param key The name of the key to send */ function sendKey(key) { if ($('#faded').css('display') == 'none') { var deviceIds = LayoutUtil.getCheckedDevices(); var keyPattern = "Key:"+ key; updateEventLog("Pressed remote key ["+ keyPattern +", Action:SENDKEY]", deviceIds); var remoteType = HTMLUtil.getParameterByName("remoteType"); remoteType = (remoteType != null) ? remoteType.toUpperCase() : null; var keyPayload = { deviceIds : deviceIds, key : key, remoteType : remoteType }; var posting = $.post(CXT_PATH + '/sendKey', keyPayload); validatePostEvent(posting, keyPattern); } } /** * Called when a key is clicked. This will blink the image and then send the key to the stb * @param image The image that was clicked and will blink * @param key The key to send to the stb */ function clickKey(image, key) { if(isBlinkAllowed(key)) { blink(image); } sendKey(key); } /** * Called when a key is holded for a duration. The image for the key will blink and then send the key along with * hold duration to the stb. * * @param image The image that was clicked and will blink * @param key The key to send to the stb * @param holdTime time in milliseconds the key is pressed. */ function holdIRKey(image, key, holdTime) { if(isBlinkAllowed(key)) { blink(image); } holdKey(key, holdTime); } /** * Blink keys only for key patterns which are NOT defined by * 'non_blinking_key_pattern' variable. For those keys flashing of button is * handled separately. Unlike other remote types BCM-7437-1 remote has separate * image for Chup, Chdn, Volup and Voldn. So these key patterns are also handled * here (ignoring non_blinking_key_pattern) if the remote type is BCM-7437-1. * Since the blinking of GENERIC remote is handled separately, isBlinkingAllowed * should return false, if remote type is GENERIC. * * @param keyName * currently sending key name. * @returns true if flashing of button is allowed. False otherwise. */ function isBlinkAllowed(keyName) { var remoteType = StandardRemote.getRemoteName(); var isBlinkingKey = non_blinking_key_pattern.test(keyName) ? false : true; var status = isBlinkingKey; if ('BCM-7437-1' == remoteType) { status = true; } else if ('GENERIC' == remoteType) { status = false; } return status; } /** * Sends a key to the server to be forwarded to the stb * @param key The name of the key to send * @param holdTime time in milliseconds the key is holded */ function holdKey(key, holdTime) { var deviceIds = LayoutUtil.getCheckedDevices(); var keyPattern = "Key:"+ key; updateEventLog("Pressed remote key ["+ keyPattern +", Action:HOLDKEY, TimeInMillis:"+ holdTime+"]", deviceIds) var remoteType = HTMLUtil.getParameterByName("remoteType"); remoteType = (remoteType != null) ? remoteType.toUpperCase() : null; if ($('#faded').css('display') == 'none') { var keyPayload = { deviceIds : deviceIds, key : key, holdTime : holdTime, remoteType : remoteType }; var posting = $.post(CXT_PATH + '/holdKey', keyPayload); validatePostEvent(posting, keyPattern); } } function sendKeyFromList() { var key = $('#keySelection').find(":selected").text(); sendKey(key); } /** * Since chup and chdn and volup and voldn share an image then this method is called and determines which region is clicked. * @param img The image that was clicked * @param key The name of the key to send (VOL or CH) * @param clickY user clicked position(from top) in the page * @param isMouseDown flag to indicate whether key pressed or not. The button will blink only during the * release of the key. * @returns key pattern to be sent to the Rack. */ function getKeyForVolCh(img, key, clickY, isMouseDown) { var iconHeight = $(img).height()/2; // Actual image mid pixel in the page. var boundary = $(img).offset().top + iconHeight; var clickedTop = clickY < boundary; var top = clickedTop ? 0 : iconHeight; var keySuffix = clickedTop ? 'UP' : 'DN'; if(!isMouseDown) { blinkRegion($(img)[0], 0, top, $(img).width(), iconHeight); } return (key + keySuffix); } var keyMap = new Array(); keyMap[13] = 'SELECT'; // enter keyMap[38] = 'UP'; // up keyMap[40] = 'DOWN'; // down keyMap[37] = 'LEFT'; // left keyMap[39] = 'RIGHT'; // right keyMap[65] = 'A'; // a keyMap[66] = 'B'; // b keyMap[67] = 'C'; // c keyMap[68] = 'D'; // d keyMap[8] = 'LAST'; // backspace keyMap[189] = 'CHDN'; // + keyMap[187] = 'CHUP'; // - keyMap[33] = 'PGUP'; // Page Up keyMap[34] = 'PGDN'; // Page Down keyMap[71] = 'GUIDE'; // g keyMap[77] = 'MENU'; // m keyMap[73] = 'INFO'; // i keyMap[27] = 'EXIT'; // esc keyMap[48] = 'ZERO'; // 0 keyMap[49] = 'ONE'; // 1 keyMap[50] = 'TWO'; // 2 keyMap[51] = 'THREE'; // 3 keyMap[52] = 'FOUR'; // 4 keyMap[53] = 'FIVE'; // 5 keyMap[54] = 'SIX'; // 6 keyMap[55] = 'SEVEN'; // 7 keyMap[56] = 'EIGHT'; // 8 keyMap[57] = 'NINE'; // 9 keyMap[112] = 'FAV_1'; // Fav 1 keyMap[113] = 'FAV_2'; // Fav 2 keyMap[114] = 'FAV_3'; // Fav 3 keyMap[115] = 'FAV_4'; // Fav 4 /** Key code for '=' which is mapped to CHUP */ var CHUP_KEY_CODE = 187; /** Key code for '-' which is mapped to CHDN */ var CHDN_KEY_CODE = 189; /** Key codes of Fav1, Fav2,Fav3 and Fav4 which are mapped to FAV_1, FAV_2, FAV_3, FAV_4 */ var FAV_CHANNEL_CODES = [112, 113, 114, 115]; /** Key codes of buttons that are not available in BCM-7437-1 remote (PGUP, PGDN, A, B, C, D) */ var KEY_CODES_NOT_SUPPORTED_BY_BCM_7437_1_REMOTE = [33, 34, 65, 66, 67, 68]; $(window).keydown(function(event) { var editingText = $(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea"; if (!editingText && hotKeysOn && !event.ctrlKey) { var keyCode = event.which; var key = keyMap[keyCode]; if (key != null) { var rem = $('#standardRemoteDiv').is(':hidden') ? 'm' : 's'; var remoteType = StandardRemote.getRemoteName(); /** For CHUP and CHDN, one single image is used. So blink the proper area in UI depends on the Pressed key.*/ if((keyCode === CHUP_KEY_CODE || keyCode === CHDN_KEY_CODE) && (remoteType != 'BCM-7437-1')) { var chElement = $("#sch")[0]; var iconHeight = $(chElement).height()/2; var iconWidth = $(chElement).width(); if(keyCode === CHUP_KEY_CODE) { blinkRegion($(chElement)[0], 0, 0, iconWidth, iconHeight); } else { blinkRegion($(chElement)[0], 0, iconHeight, iconWidth, iconHeight); } } validateClickedKey(rem, key, keyCode, remoteType); event.preventDefault(); } } }); function validateClickedKey (rem, key, keyCode, remoteType){ if ((FAV_CHANNEL_CODES.indexOf(keyCode) > -1) && remoteType != 'BCM-7437-1') { // Do nothing, do not send key press } else if ((KEY_CODES_NOT_SUPPORTED_BY_BCM_7437_1_REMOTE.indexOf(keyCode) > -1) && remoteType =='BCM-7437-1'){ // Do nothing, do not send key press } else { clickKey(document.getElementById(rem + key.toLowerCase()), key); } } var hotKeysOn = true; function clickKeyboard(img) { hotKeysOn = !hotKeysOn; img.src = CXT_PATH + "/images/keyboard" + (hotKeysOn ? "Sel" : "") + ".png"; updateKeyboardQHelp(hotKeysOn); } /** Constant to store the time in milliseconds for a single key press. */ var single_keypress_time = 100; /** Delay in milliseconds used to distinguish between a normal click from the hold key event. If a key is * is pressed for more than 500ms, then it is assumed as a hold action.*/ var delay_for_hold_action = 500; /** Interval timer variable for hold action */ var intervalTimer; /** Timeout timer variable for hold action.*/ var timeOut; /** Holds the time at which the key is pressed. */ var startTime = 0; /** Holds the time at which the key is released. */ var endTime = 0; /** * Method which handles the click events and distinguish between normal click and hold action. * If a key is pressed for < 500ms, then it is assumed as a normal single click action. If the click, * duration is more than 500ms then it will identify it as a hold event and compute the hold time in milliseconds. * * General rule for computation is : <b>For every 100ms there will be 1 key press.</b> * * @param e click event * @param key key value to be sent to the IRClient * @param isDown Flag to indicate whehter key press or key release. */ function clickRemoteButton(e, key, isDown) { latest_event = e; latest_key = key; var image = latest_event.target; if (isDown) { isMouseDown = true; startTime = Date.now(); clearTimers(); $('#hold_panel').text(''); clickTime = Date.now() - startTime; // Setup a timeout timer to update the repeat count values. // The counter updation starts ONLY AFTER (500 - current clickTime) timeOut = setTimeout(function () { updateCounter(e); }, (delay_for_hold_action - clickTime)); } // end of key down action else { // Trigger the key up action only if valid mouse down action exists. if(isMouseDown){ isMouseDown = false; endTime = Date.now(); // clear all timers which are asynchronously updating the repeat counts. clearTimers(); // Compute the key hold time. var holdTimeInMillis = endTime - startTime; $('#hold_panel').hide("slow"); if (holdTimeInMillis > delay_for_hold_action) { // Press and hold key holdIRKey(image, key, holdTimeInMillis); } else { // Normal click clickKey(image, key); } // reset starttime and endtime variables. startTime = 0; endTime = 0; } } } /** * Method to asynchronously update the repeat counter for the hold action. * @param e click event */ function updateCounter(e) { // Default repeat count value. In order to have a hold event there should be a minimum of // 500 ms. For every 100ms there will be 1 key. So setting 5 as default repeat count. repeatCount = 5; // Computing currently clicked position in the screen to draw the counter panel. posX = e.pageX; posY = e.pageY; // Increment counter in every 100ms, until the timers are cleared. intervalTimer = setInterval(function () { repeatCount++; drawOverlay(posX, posY, repeatCount); }, single_keypress_time); } /** * Draw the counter panel overlay. * @param posX currently clicked X position * @param posY currently clicked Y position * @param repeatCount repeat count for the key. */ function drawOverlay(posX, posY, repeatCount) { $('#hold_panel').css('left', posX + 10); $('#hold_panel').css('top', posY + 5); $('#hold_panel').show("fast"); $('#hold_panel').text(repeatCount + ' repeats '); } /** * Clear all the previously existing timeout and interval timers. */ function clearTimers() { clearInterval(intervalTimer); clearTimeout(timeOut); } /** * Used to display or hide the keyboard to remote key mapping overlay * @param e click event * @param status determines whether to show or hide the overlay. */ function displayKeyMappingOverlay(e, status) { var image = e.target; if(status) { blink(image); $("#keymap_panel").show("slow") } else { $("#keymap_panel").hide("slow") } } /** * Display keyboard quick help button only if the keyboard mode is active. * @param isVisible indicate whether keyboard mode is currently active or not. */ function updateKeyboardQHelp(isVisible) { if(isVisible) { $("#skeyhelp").show(); } else { $("#skeyhelp").hide(); } } /** * Helper method to verify the post event response. * @param posting event response * @param keyPattern key pattern sent to the server. */ function validatePostEvent(posting, keyPattern) { posting.done(function( data ) { updateEventLog( "Successfully sent ["+ keyPattern +"]", null); }); posting.fail(function(jqXHR, textStatus, errorThrown){ updateEventLog( "Error while sending ["+ keyPattern + "]", null); updateEventLog( errorThrown +". Status: "+ jqXHR.status, null); }); }
{'content_hash': '2a281ad304a3ff01d708c8d5d187de18', 'timestamp': '', 'source': 'github', 'line_count': 445, 'max_line_length': 127, 'avg_line_length': 32.62247191011236, 'alnum_prop': 0.6104567059309775, 'repo_name': 'trentontrees/dawg', 'id': '3a168ab362a980f1924fbf861edff1246366862c', 'size': '15140', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'libraries/dawg-show/src/main/webapp/js/keys.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '35085'}, {'name': 'Java', 'bytes': '1200331'}, {'name': 'JavaScript', 'bytes': '368052'}, {'name': 'Makefile', 'bytes': '1790'}, {'name': 'Ruby', 'bytes': '1270'}, {'name': 'Shell', 'bytes': '593'}]}
//================================================================================================= //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedVector.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/StrictlyLowerMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatsvecmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'SLDbVCb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::StrictlyLowerMatrix< blaze::DynamicMatrix<TypeB> > SLDb; typedef blaze::CompressedVector<TypeB> VCb; // Creator type definitions typedef blazetest::Creator<SLDb> CSLDb; typedef blazetest::Creator<VCb> CVCb; // Running tests with large matrices and vectors for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=i; ++j ) { RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( i ), CVCb( i, j ) ); } } // Running tests with large matrices and vectors RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( 67UL ), CVCb( 67UL, 7UL ) ); RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( 127UL ), CVCb( 127UL, 13UL ) ); RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( 64UL ), CVCb( 64UL, 8UL ) ); RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( 128UL ), CVCb( 128UL, 16UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse vector multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
{'content_hash': 'a4a62324f0986d2d5d22917ed860a25c', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 99, 'avg_line_length': 37.625, 'alnum_prop': 0.4148671096345515, 'repo_name': 'wdv4758h/blaze-lib', 'id': '8a15b52d43b4f85d24cbcb3a2a4e3b59495dd62e', 'size': '4292', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'blazetest/src/mathtest/dmatsvecmult/SLDbVCb.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '108199'}, {'name': 'C++', 'bytes': '63280462'}, {'name': 'Makefile', 'bytes': '520048'}, {'name': 'Objective-C', 'bytes': '9874'}, {'name': 'Shell', 'bytes': '551420'}]}
using System; using UnityEngine; using Vexe.Runtime.Extensions; using Vexe.Runtime.Helpers; using Vexe.Runtime.Types; using Random = UnityEngine.Random; namespace Vexe.Editor.Drawers { public abstract class BetterVectorDrawer<T, A> : AttributeDrawer<T, A> where A : DrawnAttribute { private const string kBtnReset = "0"; private const string kBtnNormalize = "1"; private const string kBtnRandomize = "r"; private Func<string, T, T> _getField; protected static float rand() { return Random.Range(-100, 100); } public override void OnGUI() { using (gui.Horizontal()) { if (_getField == null) _getField = GetField(); var current = memberValue; var newValue = _getField(displayText, current); { if (!VectorEquals(current, newValue)) memberValue = newValue; } gui.Space(12f); Foldout(); gui.Space(-10f); } if (foldout) { using (gui.Horizontal()) { DoButtons(); gui.Space(25f); } } } private void DoButtons() { gui.FlexibleSpace(); var option = Layout.sHeight(13f); if (gui.MiniButton("Copy", "Copy vector value", option)) Copy(); if (gui.MiniButton("Paste", "Paste vector value", option)) memberValue = Paste(); if (gui.MiniButton(kBtnRandomize, "Randomize values between [-100, 100]", MiniButtonStyle.ModMid, option)) memberValue = Randomize(); if (gui.MiniButton(kBtnNormalize, "Normalize", MiniButtonStyle.ModMid, option)) memberValue = Normalize(); if (gui.MiniButton(kBtnReset, "Reset", MiniButtonStyle.ModRight, option)) memberValue = Reset(); } protected abstract Func<string, T, T> GetField(); protected abstract bool VectorEquals(T left, T right); protected abstract T Reset(); protected abstract T Normalize(); protected abstract T Randomize(); protected abstract T Paste(); protected abstract void Copy(); } public class BetterV2Drawer : BetterVectorDrawer<Vector2, BetterV2Attribute> { protected override void Copy() { int key = RuntimeHelper.CombineHashCodes(id, "Clip"); prefs.SetV2(key, memberValue); } protected override Vector2 Paste() { int key = RuntimeHelper.CombineHashCodes(id, "Clip"); return prefs.GetV2(key, memberValue); } protected override Vector2 Randomize() { return new Vector2(rand(), rand()); } protected override Vector2 Normalize() { return Vector2.one; } protected override Vector2 Reset() { return Vector2.zero; } protected override Func<string, Vector2, Vector2> GetField() { return gui.Vector2Field; } protected override bool VectorEquals(Vector2 left, Vector2 right) { return left.ApproxEqual(right); } } public class BetterV3Drawer : BetterVectorDrawer<Vector3, BetterV3Attribute> { protected override void Copy() { int key = RuntimeHelper.CombineHashCodes(id, "Clip"); prefs.SetV3(key, memberValue); } protected override Vector3 Paste() { int key = RuntimeHelper.CombineHashCodes(id, "Clip"); return prefs.GetV3(key, memberValue); } protected override Vector3 Randomize() { return new Vector3(rand(), rand(), rand()); } protected override Vector3 Normalize() { return Vector3.one; } protected override Vector3 Reset() { return Vector3.zero; } protected override Func<string, Vector3, Vector3> GetField() { return gui.Vector3Field; } protected override bool VectorEquals(Vector3 left, Vector3 right) { return left.ApproxEqual(right); } } }
{'content_hash': 'a1678282e99d9f79fcc6ae3d689593a3', 'timestamp': '', 'source': 'github', 'line_count': 162, 'max_line_length': 109, 'avg_line_length': 21.753086419753085, 'alnum_prop': 0.6816118047673099, 'repo_name': 'laicasaane/VFW', 'id': '35dc95b09b3066aac813a9f6969067be5e8d7c5b', 'size': '3524', 'binary': False, 'copies': '1', 'ref': 'refs/heads/improved', 'path': 'Assets/Plugins/Editor/Vexe/Drawers/User/BetterVectorDrawer.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '712135'}]}
/* * The Plaid API * The Plaid REST API. Please see https://plaid.com/docs/api for more details. * * The version of the OpenAPI document: 2020-09-14_1.205.3 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.plaid.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.plaid.client.model.Originator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Defines the response schema for &#x60;/transfer/originator/list&#x60; */ @ApiModel(description = "Defines the response schema for `/transfer/originator/list`") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-11-17T17:52:41.932844Z[Etc/UTC]") public class TransferOriginatorListResponse { public static final String SERIALIZED_NAME_ORIGINATORS = "originators"; @SerializedName(SERIALIZED_NAME_ORIGINATORS) private List<Originator> originators = new ArrayList<>(); public static final String SERIALIZED_NAME_REQUEST_ID = "request_id"; @SerializedName(SERIALIZED_NAME_REQUEST_ID) private String requestId; public TransferOriginatorListResponse originators(List<Originator> originators) { this.originators = originators; return this; } public TransferOriginatorListResponse addOriginatorsItem(Originator originatorsItem) { this.originators.add(originatorsItem); return this; } /** * Get originators * @return originators **/ @ApiModelProperty(required = true, value = "") public List<Originator> getOriginators() { return originators; } public void setOriginators(List<Originator> originators) { this.originators = originators; } public TransferOriginatorListResponse requestId(String requestId) { this.requestId = requestId; return this; } /** * A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive. * @return requestId **/ @ApiModelProperty(required = true, value = "A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive.") public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransferOriginatorListResponse transferOriginatorListResponse = (TransferOriginatorListResponse) o; return Objects.equals(this.originators, transferOriginatorListResponse.originators) && Objects.equals(this.requestId, transferOriginatorListResponse.requestId); } @Override public int hashCode() { return Objects.hash(originators, requestId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TransferOriginatorListResponse {\n"); sb.append(" originators: ").append(toIndentedString(originators)).append("\n"); sb.append(" requestId: ").append(toIndentedString(requestId)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
{'content_hash': '2d1b46f3c2e8b5e3a01127d647c773b4', 'timestamp': '', 'source': 'github', 'line_count': 134, 'max_line_length': 187, 'avg_line_length': 29.432835820895523, 'alnum_prop': 0.7221095334685599, 'repo_name': 'plaid/plaid-java', 'id': '68bccdcee25cfac5d4e7b1d25165776c8c9906d2', 'size': '3944', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/plaid/client/model/TransferOriginatorListResponse.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '170'}, {'name': 'Java', 'bytes': '6218680'}, {'name': 'Mustache', 'bytes': '23285'}]}
require 'omniauth-github-team-member/version' require 'omniauth/strategies/github_team_member'
{'content_hash': '540722b0648ea208ee6e0b84a221da4b', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 48, 'avg_line_length': 47.5, 'alnum_prop': 0.8315789473684211, 'repo_name': 'jonmagic/omniauth-github-team-member', 'id': 'c257bb1255d7ae132b2f2a23cb4290b3d2686d12', 'size': '95', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/omniauth-github-team-member.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '4438'}]}
TFJS uint8 quantized version of the YOLO model (with DarkNet 53 backbone) trained on the CPPE - 5 (Medical Personal Protective Equipment) dataset [1]. <!-- parent-model: rishit-dagli/yolo-cppe5-tfjs/1 --> <!-- asset-path: https://storage.googleapis.com/cppe-5/trained_models/yolo/tfjs/yolo_uint8.tar.gz --> ### Overview The YOLO model was proposed by Redmon et al. in their paper "Yolov3: An incremental improvement" [2]. The YOLO model is trained on the CPPE - 5 dataset we present in our paper "CPPE - 5: Medical Personal Protective Equipment Dataset" [1] which is a new challenging dataset with an aim to facilitate the study of subordinate categorization of medical personal protective equipments. This dataset mostly contains non-iconic images or non-canonical perspectives in their natural context. This allows models to be better at generalizing, being easily deployable to real-world scenarios and often contain other objects in an image as well. We include the training code as well some tools for this model in our paper GitHub repository [3]. Note: In no case should this model be used to engage in any kind of high-risk activities, please [TF Hub Additional Terms of Service](https://tfhub.dev/terms#hra) for more information. ### Usage The saved model can be loaded directly: ```js const model = await tf.loadGraphModel("https://tfhub.dev/rishit-dagli/yolo-cppe5-tfjs/uint8/tfjs/1") ``` The inputs to the models should: - have color values in the range `[0,1]`, following the [common image input](https://www.tensorflow.org/hub/common_signatures/images#input) conventions - the expected size of the input images is height x width = 800 x 1216 pixels - the images should in the `channels_first` format - The shape of the input tensor would ths be `(1, 3, 800, 1216)`, the first dimension represents the batch size The model outputs are: - A tensor of shape `[batch_size, 100, 5]` with the bounding boxes in normalized coordinates. - A tensor of shape `[batch_size, 100]` with the class labels for the bounding boxes. ### Note - This model was quantized using `uint8` quantization. - This model takes fixed-shaped (800 x 1216) inputs. - This model has been converted using the [TensorFlow.js converter API](https://www.tensorflow.org/js/guide/conversion). ### Acknowledgements This is joint work with Ali Mustufa Shaikh. The authors would like to thank Google for supporting this work by providing Google Cloud credits. The authors would also like to thank [Google TPU Research Cloud (TRC) program](https://sites.research.google/trc) for providing access to TPUs. ### References [1] Dagli, Rishit, and Ali Mustufa Shaikh. ‘CPPE-5: Medical Personal Protective Equipment Dataset’. ArXiv:2112.09569 [Cs], Dec. 2021. arXiv.org, http://arxiv.org/abs/2112.09569. [2] Redmon, Joseph, and Ali Farhadi. "Yolov3: An incremental improvement." arXiv preprint arXiv:1804.02767 (2018). [3] https://github.com/Rishit-dagli/CPPE-Dataset
{'content_hash': '1ee062806409dffe7d36fc86ecfc3165', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 634, 'avg_line_length': 61.4375, 'alnum_prop': 0.7653441844693116, 'repo_name': 'tensorflow/tfhub.dev', 'id': '4a2c488381deaaf188e709b18c4bc1ec4555a1b5', 'size': '2997', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/docs/rishit-dagli/yolo-cppe5-tfjs/uint8/tfjs/1.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '160084'}, {'name': 'Starlark', 'bytes': '6838'}]}
<?php session_start(); require("../../MySQLconnect/config.php"); if(!isset($_SESSION['user_id'])) { header('location:../../'); } else { $userid = mysql_real_escape_string($_SESSION['user_id']); } $riskid = mysql_real_escape_string($_GET['risk_id']); $projectid = mysql_real_escape_string($_GET['project_id']); $riskinfo = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['risk_info']))),ENT_QUOTES); $consequence = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['consequence']))),ENT_QUOTES); $chance = mysql_real_escape_string($_GET['chance']); $programme = mysql_real_escape_string($_GET['programme']); $budget = mysql_real_escape_string($_GET['budget']); $she = mysql_real_escape_string($_GET['she']); $timeimpact = mysql_real_escape_string($_GET['impact_t']); $cost = mysql_real_escape_string($_GET['cost']); $costtbd = mysql_real_escape_string($_GET['cost_tbd']); $owner = mysql_real_escape_string($_GET['owner']); $mitigation = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['mitigation']))),ENT_QUOTES); $time=time(); $riskrating = $chance*max($programme,$budget); $oldrecorddetails = mysql_fetch_array(mysql_query("SELECT * FROM risk_log WHERE risk_id='$riskid'")); //check for the ID of the new owner and add them to the system if they do not exist $results = mysql_query("SELECT * FROM users WHERE email='$owner'"); $countrows = mysql_num_rows($results); if($countrows==0) { mysql_query("INSERT INTO users SET email='$owner'"); $results = mysql_query("SELECT * FROM users WHERE email='$owner'"); $ownerid = mysql_fetch_array($results); $ownerid = $ownerid['user_id']; } else { $ownerid = mysql_fetch_array($results); $ownerid = $ownerid['user_id']; } mysql_query("UPDATE risk_log SET risk_info='$riskinfo', consequence='$consequence', chance='$chance', impact_p='$programme', impact_b='$budget', impact_she='$she', impact_t='$timeimpact', e_cost='$cost', e_cost_tbd='$costtbd', owner='$ownerid', mitigation='$mitigation', risk_rating='$riskrating' WHERE risk_id='$riskid'"); $updatecomment1 = ""; $updatecomment2 = ""; $updatecomment3 = ""; $updatecomment4 = ""; $updatecomment5 = ""; $updatecomment6 = ""; $updatecomment7 = ""; $updatecomment8 = ""; $updatecomment9 = ""; $updatecomment10 = ""; $updatecomment11 = ""; $updatecomment12 = ""; $changed = 0; if($oldrecorddetails['risk_info']<>$riskinfo) { $updatecomment1 = "<br />Risk info changed from: " . $oldrecorddetails['risk_info']; $changed = 1; } if($oldrecorddetails['owner']<>$owner) { $updatecomment2 = "<br />Owner changed from: " . $oldrecorddetails['owner']; $changed = 1; } if($oldrecorddetails['consequence']<>$consequence) { $updatecomment3 = "<br />Consequence changed from: " . $oldrecorddetails['consequence']; $changed = 1; } if($oldrecorddetails['impact_p']<>$programme) { $updatecomment4 = "<br />Programme impact changed from: " . $oldrecorddetails['impact_p']; $changed = 1; } if($oldrecorddetails['impact_b']<>$budget) { $updatecomment5 = "<br />Budget impact changed from: " . $oldrecorddetails['impact_b']; $changed = 1; } if($oldrecorddetails['impact_she']<>$she) { $updatecomment6 = "<br />SHE impact changed from: " . $oldrecorddetails['impact_she']; $changed = 1; } if($oldrecorddetails['chance']<>$chance) { $updatecomment7 = "<br />Likelihood changed from: " . $oldrecorddetails['chance']; $changed = 1; } if($oldrecorddetails['risk_rating']<>$riskrating) { $updatecomment8 = "<br />Risk rating changed from: " . $oldrecorddetails['risk_rating']; $changed = 1; } if($oldrecorddetails['impact_t']<>$timeimpact) { $updatecomment9 = "<br />Time impact changed from: " . $oldrecorddetails['impact_t']; $changed = 1; } if($oldrecorddetails['e_cost']<>$cost) { $updatecomment10 = "<br />Estimated cost changed from: " . $oldrecorddetails['e_cost']; $changed = 1; } if($oldrecorddetails['e_cost_tbd']<>$costtbd) { if($costtbd==1) { $updatecomment11 = "<br />Costs to be determined changed to: confirmation needed"; } else { $updatecomment11 = "<br />Costs to be determined changed to: costs confirmed"; } $changed = 1; } if($oldrecorddetails['mitigation']<>$mitigation) { $updatecomment12 = "<br />Mitigation measures changed from: " . $oldrecorddetails['mitigation']; $changed = 1; } if($changed>0) { $updatecomment = $updatecomment1.$updatecomment2.$updatecomment3.$updatecomment4.$updatecomment5.$updatecomment6.$updatecomment7.$updatecomment8.$updatecomment9.$updatecomment10.$updatecomment11.$updatecomment12; mysql_query("INSERT INTO audit_trail_risk_log (project_id, risk_id, comment, user_id) VALUES ('$projectid','$riskid','$updatecomment','$userid')"); } //display the list of daily records require("load_risk_records.php"); ?>
{'content_hash': '043d57789b2864ef93ce78c7accb7a41', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 267, 'avg_line_length': 31.649350649350648, 'alnum_prop': 0.6721378744357817, 'repo_name': 'tomwinslow/Open-Project-Tracker', 'id': 'e53dabec918a440732a15fde41e4dac0904872c3', 'size': '4874', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Ajax/risk_log/update_risk_details.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '28700'}, {'name': 'HTML', 'bytes': '13314'}, {'name': 'JavaScript', 'bytes': '214765'}, {'name': 'PHP', 'bytes': '341361'}]}
//global variables var countriesNeedIDNumber = []; var countriesNeedZipCode = []; $(document).ready(function(){ setCountries(); bindStateInputAndUpdate(); bindUniform(); bindPostcode(); bindCheckbox(); $(document).on('click', '#invoice_address', function(e){ bindCheckbox(); }); }); function setCountries() { if (typeof countries !== 'undefined' && countries) { var countriesPS = []; for (var i in countries) { var id_country = countries[i]['id_country']; if (typeof countries[i]['states'] !== 'undefined' && countries[i]['states'] && countries[i]['contains_states']) { countriesPS[id_country] = []; for (var j in countries[i]['states']) countriesPS[parseInt(id_country)].push({'id' : parseInt(countries[i]['states'][j]['id_state']), 'name' : countries[i]['states'][j]['name']}); } if (typeof countries[i]['need_identification_number'] !== 'undefined' && parseInt(countries[i]['need_identification_number']) > 0) countriesNeedIDNumber.push(parseInt(countries[i]['id_country'])); if (typeof countries[i]['need_zip_code'] !== 'undefined' && parseInt(countries[i]['need_zip_code']) > 0) countriesNeedZipCode[parseInt(countries[i]['id_country'])] = countries[i]['zip_code_format']; } } countries = countriesPS; } function bindCheckbox() { if ($('#invoice_address:checked').length > 0) { $('#opc_invoice_address').slideDown('slow'); if ($('#company_invoice').val() == '') $('#vat_number_block_invoice').hide(); bindUniform(); } else $('#opc_invoice_address').slideUp('slow'); } function bindUniform() { $("select.form-control,input[type='radio'],input[type='checkbox']").uniform(); } function bindPostcode() { $(document).on('keyup', 'input[name=postcode]', function(e) { $(this).val($(this).val().toUpperCase()); }); } function bindStateInputAndUpdate() { $('.id_state, .dni, .postcode').css({'display':'none'}); updateState(); updateNeedIDNumber(); updateZipCode(); $(document).on('change', '#id_country', function(e) { updateState(); updateNeedIDNumber(); updateZipCode(); }); if ($('#id_country_invoice').length !== 0) { $(document).on('change', '#id_country_invoice', function(e) { updateState('invoice'); updateNeedIDNumber('invoice'); updateZipCode('invoice'); }); updateState('invoice'); updateNeedIDNumber('invoice'); updateZipCode('invoice'); } if (typeof idSelectedState !== 'undefined' && idSelectedState) $('.id_state option[value=' + idSelectedState + ']').prop('selected', true); if (typeof idSelectedStateInvoice !== 'undefined' && idSelectedStateInvoice) $('.id_state_invoice option[value=' + idSelectedStateInvoice + ']').prop('selected', true); } function updateState(suffix) { $('#id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '')+' option:not(:first-child)').remove(); if (typeof countries !== 'undefined') var states = countries[parseInt($('#id_country' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).val())]; if (typeof states !== 'undefined') { $(states).each(function(key, item){ $('#id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).append('<option value="' + parseInt(item.id) + '">' + item.name + '</option>'); }); $('.id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '') + ':hidden').fadeIn('slow'); $('#id_state, #id_state_invoice').uniform(); } else $('.id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).fadeOut('fast'); } function updateNeedIDNumber(suffix) { var idCountry = parseInt($('#id_country' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).val()); if (typeof countriesNeedIDNumber !== 'undefined' && in_array(idCountry, countriesNeedIDNumber)) { $('.dni' + (typeof suffix !== 'undefined' ? '_' + suffix : '') + ':hidden').fadeIn('slow'); $('#dni').uniform(); } else $('.dni' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).fadeOut('fast'); } function updateZipCode(suffix) { var idCountry = parseInt($('#id_country' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).val()); if (typeof countriesNeedZipCode !== 'undefined' && typeof countriesNeedZipCode[idCountry] !== 'undefined') { $('.postcode' + (typeof suffix !== 'undefined' ? '_' + suffix : '') + ':hidden').fadeIn('slow'); $('#postcode').uniform(); } else $('.postcode'+(typeof suffix !== 'undefined' ? '_' + suffix : '')).fadeOut('fast'); }
{'content_hash': 'eba19d0ef655c08eca67ace7547259e6', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 151, 'avg_line_length': 31.690647482014388, 'alnum_prop': 0.6204313280363224, 'repo_name': 'rannor/ranno-bootstrap', 'id': '13ac28153b39cf38c37ea1198cb4e96a10105e07', 'size': '5373', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'js/tools/statesManagement.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '411867'}, {'name': 'JavaScript', 'bytes': '370528'}, {'name': 'PHP', 'bytes': '168531'}, {'name': 'Ruby', 'bytes': '770'}]}
webhookr ======== Go-lang HTTP multiplexer
{'content_hash': 'c0f5bc92f9daf6d13b1a3e9aa7bdcd57', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 24, 'avg_line_length': 11.0, 'alnum_prop': 0.6590909090909091, 'repo_name': 'vongrippen/webhookr', 'id': 'adf387922a5b38024e554a781a126918d5dcfa59', 'size': '44', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': []}
package com.piggymetrics.statistics.service; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.piggymetrics.statistics.domain.Account; import com.piggymetrics.statistics.domain.Currency; import com.piggymetrics.statistics.domain.Item; import com.piggymetrics.statistics.domain.Saving; import com.piggymetrics.statistics.domain.TimePeriod; import com.piggymetrics.statistics.domain.timeseries.DataPoint; import com.piggymetrics.statistics.domain.timeseries.ItemMetric; import com.piggymetrics.statistics.domain.timeseries.StatisticMetric; import com.piggymetrics.statistics.repository.DataPointRepository; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.Mockito.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; public class StatisticsServiceImplTest { @InjectMocks private StatisticsServiceImpl statisticsService; @Mock private ExchangeRatesServiceImpl ratesService; @Mock private DataPointRepository repository; @Before public void setup() { initMocks(this); } @Test public void shouldFindDataPointListByAccountName() { final List<DataPoint> list = ImmutableList.of(new DataPoint()); when(repository.findByIdAccount("test")).thenReturn(list); List<DataPoint> result = statisticsService.findByAccountName("test"); assertEquals(list, result); } @Test(expected = IllegalArgumentException.class) public void shouldFailToFindDataPointWhenAccountNameIsNull() { statisticsService.findByAccountName(null); } @Test(expected = IllegalArgumentException.class) public void shouldFailToFindDataPointWhenAccountNameIsEmpty() { statisticsService.findByAccountName(""); } @Test public void shouldSaveDataPoint() { /** * Given */ Item salary = new Item(); salary.setTitle("Salary"); salary.setAmount(new BigDecimal(9100)); salary.setCurrency(Currency.USD); salary.setPeriod(TimePeriod.MONTH); Item grocery = new Item(); grocery.setTitle("Grocery"); grocery.setAmount(new BigDecimal(500)); grocery.setCurrency(Currency.RUB); grocery.setPeriod(TimePeriod.DAY); Item vacation = new Item(); vacation.setTitle("Vacation"); vacation.setAmount(new BigDecimal(3400)); vacation.setCurrency(Currency.EUR); vacation.setPeriod(TimePeriod.YEAR); Saving saving = new Saving(); saving.setAmount(new BigDecimal(1000)); saving.setCurrency(Currency.EUR); saving.setInterest(new BigDecimal(3.2)); saving.setDeposit(true); saving.setCapitalization(false); Account account = new Account(); account.setIncomes(ImmutableList.of(salary)); account.setExpenses(ImmutableList.of(grocery, vacation)); account.setSaving(saving); final Map<Currency, BigDecimal> rates = ImmutableMap.of( Currency.EUR, new BigDecimal("0.8"), Currency.RUB, new BigDecimal("80"), Currency.USD, BigDecimal.ONE ); /** * When */ when(ratesService.convert(any(Currency.class),any(Currency.class),any(BigDecimal.class))) .then(i -> ((BigDecimal)i.getArgument(2)) .divide(rates.get(i.getArgument(0)), 4, RoundingMode.HALF_UP)); when(ratesService.getCurrentRates()).thenReturn(rates); when(repository.save(any(DataPoint.class))).then(returnsFirstArg()); DataPoint dataPoint = statisticsService.save("test", account); /** * Then */ final BigDecimal expectedExpensesAmount = new BigDecimal("17.8861"); final BigDecimal expectedIncomesAmount = new BigDecimal("298.9802"); final BigDecimal expectedSavingAmount = new BigDecimal("1250"); final BigDecimal expectedNormalizedSalaryAmount = new BigDecimal("298.9802"); final BigDecimal expectedNormalizedVacationAmount = new BigDecimal("11.6361"); final BigDecimal expectedNormalizedGroceryAmount = new BigDecimal("6.25"); assertEquals(dataPoint.getId().getAccount(), "test"); assertEquals(dataPoint.getId().getDate(), Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())); assertTrue(expectedExpensesAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.EXPENSES_AMOUNT)) == 0); assertTrue(expectedIncomesAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.INCOMES_AMOUNT)) == 0); assertTrue(expectedSavingAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.SAVING_AMOUNT)) == 0); ItemMetric salaryItemMetric = dataPoint.getIncomes().stream() .filter(i -> i.getTitle().equals(salary.getTitle())) .findFirst().get(); ItemMetric vacationItemMetric = dataPoint.getExpenses().stream() .filter(i -> i.getTitle().equals(vacation.getTitle())) .findFirst().get(); ItemMetric groceryItemMetric = dataPoint.getExpenses().stream() .filter(i -> i.getTitle().equals(grocery.getTitle())) .findFirst().get(); assertTrue(expectedNormalizedSalaryAmount.compareTo(salaryItemMetric.getAmount()) == 0); assertTrue(expectedNormalizedVacationAmount.compareTo(vacationItemMetric.getAmount()) == 0); assertTrue(expectedNormalizedGroceryAmount.compareTo(groceryItemMetric.getAmount()) == 0); assertEquals(rates, dataPoint.getRates()); verify(repository, times(1)).save(dataPoint); } }
{'content_hash': '99512399205f81d0ba6ddfaac1e0c769', 'timestamp': '', 'source': 'github', 'line_count': 167, 'max_line_length': 130, 'avg_line_length': 33.74850299401198, 'alnum_prop': 0.7730660042583393, 'repo_name': 'guanzhenxing/swan', 'id': 'beeef32a8ccc0a844fd160352e55686b8ca12876', 'size': '5636', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'statistics-service/src/test/java/com/piggymetrics/statistics/service/StatisticsServiceImplTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '133089'}]}
""" Project Euler Problem 86: https://projecteuler.net/problem=86 A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F, sits in the opposite corner. By travelling on the surfaces of the room the shortest "straight line" distance from S to F is 10 and the path is shown on the diagram.  However, there are up to three "shortest" path candidates for any given cuboid and the shortest route doesn't always have integer length. It can be shown that there are exactly 2060 distinct cuboids, ignoring rotations, with integer dimensions, up to a maximum size of M by M by M, for which the shortest route has integer length when M = 100. This is the least value of M for which the number of solutions first exceeds two thousand; the number of solutions when M = 99 is 1975. Find the least value of M such that the number of solutions first exceeds one million. Solution: Label the 3 side-lengths of the cuboid a,b,c such that 1 <= a <= b <= c <= M. By conceptually "opening up" the cuboid and laying out its faces on a plane, it can be seen that the shortest distance between 2 opposite corners is sqrt((a+b)^2 + c^2). This distance is an integer if and only if (a+b),c make up the first 2 sides of a pythagorean triplet. The second useful insight is rather than calculate the number of cuboids with integral shortest distance for each maximum cuboid side-length M, we can calculate this number iteratively each time we increase M, as follows. The set of cuboids satisfying this property with maximum side-length M-1 is a subset of the cuboids satisfying the property with maximum side-length M (since any cuboids with side lengths <= M-1 are also <= M). To calculate the number of cuboids in the larger set (corresponding to M) we need only consider the cuboids which have at least one side of length M. Since we have ordered the side lengths a <= b <= c, we can assume that c = M. Then we just need to count the number of pairs a,b satisfying the conditions: sqrt((a+b)^2 + M^2) is integer 1 <= a <= b <= M To count the number of pairs (a,b) satisfying these conditions, write d = a+b. Now we have: 1 <= a <= b <= M => 2 <= d <= 2*M we can actually make the second equality strict, since d = 2*M => d^2 + M^2 = 5M^2 => shortest distance = M * sqrt(5) => not integral. a + b = d => b = d - a and a <= b => a <= d/2 also a <= M => a <= min(M, d//2) a + b = d => a = d - b and b <= M => a >= d - M also a >= 1 => a >= max(1, d - M) So a is in range(max(1, d - M), min(M, d // 2) + 1) For a given d, the number of cuboids satisfying the required property with c = M and a + b = d is the length of this range, which is min(M, d // 2) + 1 - max(1, d - M). In the code below, d is sum_shortest_sides and M is max_cuboid_size. """ from math import sqrt def solution(limit: int = 1000000) -> int: """ Return the least value of M such that there are more than one million cuboids of side lengths 1 <= a,b,c <= M such that the shortest distance between two opposite vertices of the cuboid is integral. >>> solution(100) 24 >>> solution(1000) 72 >>> solution(2000) 100 >>> solution(20000) 288 """ num_cuboids: int = 0 max_cuboid_size: int = 0 sum_shortest_sides: int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2, 2 * max_cuboid_size + 1): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2).is_integer(): num_cuboids += ( min(max_cuboid_size, sum_shortest_sides // 2) - max(1, sum_shortest_sides - max_cuboid_size) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f"{solution() = }")
{'content_hash': '4ec2b80df800a7d14c1403eed27d6525', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 86, 'avg_line_length': 40.22857142857143, 'alnum_prop': 0.5935132575757576, 'repo_name': 'TheAlgorithms/Python', 'id': '064af215c049ecc1de5e7a945c8a7bc444bb874c', 'size': '4226', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'project_euler/problem_086/sol1.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '2601694'}]}
package gov.va.med.srcalc.web.view.admin; import gov.va.med.srcalc.domain.model.MultiSelectOption; import gov.va.med.srcalc.util.ValidationCodes; import gov.va.med.srcalc.util.ValidationUtils2; import org.springframework.validation.*; import com.google.common.collect.ImmutableList; /** * Validates an {@link EditMultiSelectVar} object. */ public class EditMultiSelectVarValidator implements Validator { private final EditBaseVarValidator fBaseValidator = new EditBaseVarValidator(); /** * Returns true if (and only if) the given class is {@link EditMultiSelectVar} * or a subclass. */ @Override public boolean supports(final Class<?> clazz) { return EditMultiSelectVar.class.isAssignableFrom(clazz); } /** * Validates the given object, using error codes from {@link ValidationCodes}. * @param target the object to validate. Must be an instance of {@link * EditMultiSelectVar}. * @throws ClassCastException if the given object is not an EditMultiSelectVar */ @Override public void validate(final Object target, final Errors errors) { final EditMultiSelectVar editVar = (EditMultiSelectVar)target; // First, delegate to EditBaseVarValidator for validating the basic // properties. fBaseValidator.validate(target, errors); // Validate displayType. ValidationUtils.rejectIfEmpty( errors, "displayType", ValidationCodes.NO_VALUE); // Validate options. Use the getTrimmedOptions since that is what // getMultiSelectOptions will ultimately use. (That is, trailing blanks // are omitted.) final ImmutableList<String> options = editVar.getTrimmedOptions(); if (options.isEmpty()) { errors.rejectValue( "options", ValidationCodes.NO_VALUE, "No options specified."); } else if (options.size() > editVar.getMaxOptions()) { errors.rejectValue( "options", ValidationCodes.TOO_LONG, new Object[] { editVar.getMaxOptions() }, "too many options"); } // Iterate using the index here because we need it to specify the field. for (int i = 0; i < options.size(); ++i) { final String fieldName = String.format("options[%d]", i); ValidationUtils.rejectIfEmpty(errors, fieldName, ValidationCodes.NO_VALUE); ValidationUtils2.rejectIfTooLong(errors, fieldName, MultiSelectOption.VALUE_MAX); ValidationUtils2.rejectIfDoesntMatch( errors, fieldName, MultiSelectOption.VALID_VALUE_PATTERN, new Object[] {MultiSelectOption.VALID_VALUE_CHARACTERS}); } } }
{'content_hash': '2da3b750a0a0c8111377ccc34454f702', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 93, 'avg_line_length': 37.467532467532465, 'alnum_prop': 0.6329289428076257, 'repo_name': 'VHAINNOVATIONS/ASRCM', 'id': '094002898cb2a6299f9e150f94404256f2554130', 'size': '2885', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'srcalc/src/main/java/gov/va/med/srcalc/web/view/admin/EditMultiSelectVarValidator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5043'}, {'name': 'CSS', 'bytes': '12887'}, {'name': 'Genshi', 'bytes': '56570'}, {'name': 'Java', 'bytes': '1182363'}, {'name': 'JavaScript', 'bytes': '18075'}]}
#import <UIKit/UIKit.h> @interface UICollectionView (TML) @end
{'content_hash': '388df23f9692a90fde50313160ff784d', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 33, 'avg_line_length': 9.571428571428571, 'alnum_prop': 0.7164179104477612, 'repo_name': 'translationexchange/tml-objc', 'id': 'fa81ddd9ac430cf34294530983024abc2caae12b', 'size': '1975', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Classes/Extensions/UICollectionView+TML.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '343086'}, {'name': 'C++', 'bytes': '19355'}, {'name': 'Objective-C', 'bytes': '1703946'}, {'name': 'Ruby', 'bytes': '10372'}, {'name': 'Shell', 'bytes': '11954'}]}
<?php namespace Plivo\Resources\Message; use Plivo\Exceptions\PlivoValidationException; use Plivo\Exceptions\PlivoRestException; use Plivo\Exceptions\PlivoResponseException; use Plivo\Util\ArrayOperations; use Plivo\MessageClient; use Plivo\Resources\ResourceInterface; /** * Class MessageInterface * @package Plivo\Resources\Message */ class MessageInterface extends ResourceInterface { /** * MessageInterface constructor. * @param MessageClient $plivoClient * @param $authId */ public function __construct(MessageClient $plivoClient, $authId) { parent::__construct($plivoClient); $this->pathParams = [ 'authId' => $authId ]; $this->uri = "Account/".$authId."/Message/"; } /** * @param $messageUuid * @return Message * @throws PlivoValidationException */ public function get($messageUuid) { if (ArrayOperations::checkNull([$messageUuid])) { throw new PlivoValidationException( 'message uuid is mandatory'); } $response = $this->client->fetch( $this->uri . $messageUuid .'/', [] ); // return the object for chain method if ($response->getStatusCode() == 200){ return new Message( $this->client, $response->getContent(), $this->pathParams['authId'], $this->uri); } return json_encode($response->getContent(), JSON_FORCE_OBJECT); } /** * Return a list of messages * @param array $optionalArgs * + Valid arguments * + [string] :subaccount - The id of the subaccount, if message details of the subaccount is needed. * + [string] :message_direction - Filter the results by message direction. The valid inputs are inbound and outbound. * + [string] :message_time - Filter out messages according to the time of completion. The filter can be used in the following five forms: * <br /> message_time: The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received at 2012-03-21 11:47[:30], use message_time=2012-03-21 11:47[:30] * <br /> message_time\__gt: gt stands for greater than. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received after 2012-03-21 11:47, use message_time\__gt=2012-03-21 11:47 * <br /> message_time\__gte: gte stands for greater than or equal. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received after or exactly at 2012-03-21 11:47[:30], use message_time\__gte=2012-03-21 11:47[:30] * <br /> message_time\__lt: lt stands for lesser than. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received before 2012-03-21 11:47, use message_time\__lt=2012-03-21 11:47 * <br /> message_time\__lte: lte stands for lesser than or equal. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received before or exactly at 2012-03-21 11:47[:30], use message_time\__lte=2012-03-21 11:47[:30] * <br /> Note: The above filters can be combined to get messages that were sent/received in a particular time range. The timestamps need to be UTC timestamps. * + [string] :message_state Status value of the message, is one of "queued", "sent", "failed", "delivered", "undelivered" or "rejected" * + [int] :limit Used to display the number of results per page. The maximum number of results that can be fetched is 20. * + [int] :offset Denotes the number of value items by which the results should be offset. Eg:- If the result contains a 1000 values and limit is set to 10 and offset is set to 705, then values 706 through 715 are displayed in the results. This parameter is also used for pagination of the results. * + [string] :error_code Delivery Response code returned by the carrier attempting the delivery. See Supported error codes {https://www.plivo.com/docs/api/message/#standard-plivo-error-codes}. * + [string] : powerpack_id - Filter the results by Powerpack ID. * @return MessageList */ protected function getList($optionalArgs = []) { $response = $this->client->fetch( $this->uri, $optionalArgs ); if(!array_key_exists("error", $response->getContent())) { $messages = []; foreach ($response->getContent()['objects'] as $message) { $newMessage = new Message($this->client, $message, $this->pathParams['authId'], $this->uri); array_push($messages, $newMessage); } return new MessageList($this->client, $response->getContent()['meta'], $messages); } else { throw new PlivoResponseException( $response->getContent()['error'], 0, null, $response->getContent(), $response->getStatusCode() ); } } /** * Send a message * * @param string $src * @param array $dst * @param string $text * @param array $optionalArgs * + Valid arguments * + [string] :type - The type of message. Should be `sms` or `mms`. Defaults to `sms`. * + [string] :url - The URL to which with the status of the message is sent. The following parameters are sent to the URL: * <br /> To - Phone number of the recipient * <br /> From - Phone number of the sender * <br /> Status - Status of the message including "queued", "sent", "failed", "delivered", "undelivered" or "rejected" * <br /> MessageUUID - The unique ID for the message * <br /> ParentMessageUUID - ID of the parent message (see notes about long SMS below) * <br /> PartInfo - Specifies the sequence of the message (useful for long messages split into multiple text messages; see notes about long SMS below) * <br /> TotalRate - Total rate per sms * <br /> TotalAmount - Total cost of sending the sms (TotalRate * Units) * <br /> Units - Number of units into which a long SMS was split * <br /> MCC - Mobile Country Code (see here {https://en.wikipedia.org/wiki/Mobile_country_code} for more details) * <br /> MNC - Mobile Network Code (see here {https://en.wikipedia.org/wiki/Mobile_country_code} for more details) * <br /> ErrorCode - Delivery Response code returned by the carrier attempting the delivery. See Supported error codes {https://www.plivo.com/docs/api/message/#standard-plivo-error-codes}. * + [string] :method - The method used to call the url. Defaults to POST. * + [string] :log - If set to false, the content of this message will not be logged on the Plivo infrastructure and the dst value will be masked (e.g., 141XXXXX528). Default is set to true. * [list] : media_urls - If your sending mms message, you can specify the media urls like ['https://yourmedia_urls/test.jpg','https://test.com/test.gif'] * @return MessageCreateResponse output * @throws PlivoValidationException,PlivoResponseException */ // public function create($src=null, $dst=null, $text=null,array $optionalArgs = [], $powerpackUUID = null) { if (is_array($src)) { $optionalArgs = array_merge($src, $optionalArgs); $src = isset($optionalArgs['src']) ? $optionalArgs['src'] : null; $dst = isset($optionalArgs['dst']) ? $optionalArgs['dst'] : null; $text = isset($optionalArgs['text']) ? $optionalArgs['text'] : null; $powerpackUUID = isset($optionalArgs['powerpackUUID']) ? $optionalArgs['powerpackUUID'] : null; } if (is_array($dst)){ $mandatoryArgs = [ 'dst' => implode('<', $dst), ]; } else { $mandatoryArgs = ['dst' => $dst ]; } if (ArrayOperations::checkNull($mandatoryArgs)) { throw new PlivoValidationException( "Mandatory parameters cannot be null"); } if (is_null($src) && is_null($powerpackUUID)) { throw new PlivoValidationException( "Specify either powerpack_uuid or src in request params to send a message." ); } if (!is_null($src) && !is_null($powerpackUUID)) { throw new PlivoValidationException( "Both powerpack_uuid and src cannot be specified. Specify either powerpack_uuid or src in request params to send a message." ); } $response = $this->client->update( $this->uri, array_merge($mandatoryArgs, $optionalArgs, ['src' => $src, 'powerpack_uuid' => $powerpackUUID, 'text' => $text]) ); $responseContents = $response->getContent(); if(!array_key_exists("error",$responseContents)){ if(array_key_exists("invalid_number", $responseContents)){ return new MessageCreateResponse( $responseContents['message'], $responseContents['message_uuid'], $responseContents['api_id'], $response->getStatusCode(), $responseContents['invalid_number'] ); } else{ return new MessageCreateResponse( $responseContents['message'], $responseContents['message_uuid'], $responseContents['api_id'], $response->getStatusCode(), [] ); } } else { throw new PlivoResponseException( $responseContents['error'], 0, null, $response->getContent(), $response->getStatusCode() ); } } }
{'content_hash': 'f1d26b293a26e6f2bcf24c833cdad0b5', 'timestamp': '', 'source': 'github', 'line_count': 212, 'max_line_length': 305, 'avg_line_length': 48.806603773584904, 'alnum_prop': 0.581907799362134, 'repo_name': 'plivo/plivo-php', 'id': 'cc7048d501d861705954d75e1bb72b168fa5923f', 'size': '10347', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Plivo/Resources/Message/MessageInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Hack', 'bytes': '7'}, {'name': 'PHP', 'bytes': '613664'}]}
using System; using System.Collections.Generic; using System.Linq; using SlimsteMens.Model.Entities; using SlimsteMens.Model.Repositories; namespace SlimsteMens.Model.Services { public class GalleryRoundService { private readonly IRepository<Gallery> _galleryRepository; private readonly Game _game; protected int GalleryNr; public int Correct { get; set; } public IList<Gallery> Galleries { get; set; } public int SecondsOnCorrect { get; set; } public IList<TurnType> PlayedAGallery { get; set; } public IList<TurnType> PlayedCurrentGallery { get; set; } /// <summary> /// Initializes a new instance of the <see cref="GalleryRoundService" /> class. /// </summary> /// <param name="secondsOnCorrect">The seconds on correct.</param> /// <param name="galleryRepository">The gallery repository.</param> /// <param name="game">The game.</param> /// <exception cref="System.ArgumentNullException"> /// galleryRepository /// or /// game /// </exception> /// <exception cref="System.ArgumentException"></exception> public GalleryRoundService(int secondsOnCorrect, IRepository<Gallery> galleryRepository, Game game) { if (galleryRepository == null) throw new ArgumentNullException("galleryRepository"); if (game == null) throw new ArgumentNullException("game"); SecondsOnCorrect = secondsOnCorrect; _galleryRepository = galleryRepository; _game = game; PlayedAGallery = new List<TurnType>(); PlayedCurrentGallery = new List<TurnType>(); GalleryNr = 0; InitializeGalleries(); } /// <summary> /// Retrieves the Next gallery. /// </summary> /// <returns></returns> public Gallery NextGallery() { if (GalleryNr >= Galleries.Count) return null; TurnType turn = _game.NextAndSetTurnByLowestTime(PlayedAGallery); Correct = 0; if (Galleries.Count == 0) return null; PlayedCurrentGallery = new List<TurnType>(); PlayedAGallery.Add(turn); GalleryNr++; return Galleries[GalleryNr - 1]; } private void InitializeGalleries() { List<long> ids; if (_galleryRepository.AsQueryable().Count(c => c.GalleryQuestions.All(g => !g.Played)) >= 3) { ids = _galleryRepository.AsQueryable().Where(c => c.GalleryQuestions.All(g => !g.Played)).Select(s => s.Id).Shuffle().Take(3).ToList(); } else { ids = _galleryRepository.AsQueryable().Select(s => s.Id).Shuffle().Take(3).ToList(); } Galleries = _galleryRepository.Query(g => ids.Any(id => id == g.Id)).Shuffle().ToList(); if (Galleries.Count < 3) throw new InvalidOperationException("Need 3 galleries to continue"); Galleries.ToList().ForEach(g => g.GalleryQuestions.ToList().ForEach(gq => gq.Played = true)); } } }
{'content_hash': 'f7833770a733201ce3d327758b461cf8', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 151, 'avg_line_length': 36.65909090909091, 'alnum_prop': 0.5818350898946063, 'repo_name': 'ArneD/slimste-quiz', 'id': '2e07f73a612ccf67f7291a49430b73dd2952fea4', 'size': '3228', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SlimsteMens.Model/Services/GalleryRoundService.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '392933'}]}
Reflectors ========== [![documentation](http://img.ateliers-pierrot-static.fr/read-the-doc.svg)](http://docs.ateliers-pierrot.fr/reflectors/) [![Code Climate](http://codeclimate.com/github/atelierspierrot/reflectors/badges/gpa.svg)](http://codeclimate.com/github/atelierspierrot/reflectors) Some PHP Reflectors objects to complete the [internal Reflection](http://php.net/manual/book.reflection.php). All objects defined in this package implement the [\Reflector interface](http://php.net/manual/class.reflector.php) and generate a simple output to keep compliant with existing internal reflection objects. Installation ------------ For a complete information about how to install this package and load its namespace, please have a look at [our *USAGE* documentation](http://github.com/atelierspierrot/atelierspierrot/blob/master/USAGE.md). If you are a [Composer](http://getcomposer.org/) user, just add the package to the requirements of your project's `composer.json` manifest file: ```json "atelierspierrot/reflectors": "dev-master" ``` You can use a specific release or the latest release of a major version using the appropriate [version constraint](http://getcomposer.org/doc/01-basic-usage.md#package-versions). Author & License ---------------- > Reflectors > http://github.com/atelierspierrot/reflectors > Copyright (c) 2015-2016 Pierre Cassat and contributors > Licensed under the Apache 2 license. > http://www.apache.org/licenses/LICENSE-2.0 > ---- > Les Ateliers Pierrot - Paris, France > <http://www.ateliers-pierrot.fr/> - <[email protected]>
{'content_hash': '6736d4f1bfd33dc4888a850a0f305de6', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 148, 'avg_line_length': 35.06521739130435, 'alnum_prop': 0.7427154370737755, 'repo_name': 'atelierspierrot/reflectors', 'id': 'b9f1aee15933d9459c168eaced5b7aaef5437adc', 'size': '1613', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9418'}, {'name': 'HTML', 'bytes': '661624'}, {'name': 'PHP', 'bytes': '125665'}]}
// Code generated by protoc-gen-gogo. // source: combos/unsafemarshaler/types.proto // DO NOT EDIT! /* Package types is a generated protocol buffer package. It is generated from these files: combos/unsafemarshaler/types.proto It has these top-level messages: KnownTypes ProtoTypes StdTypes RepProtoTypes RepStdTypes MapProtoTypes MapStdTypes OneofProtoTypes OneofStdTypes */ package types import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import google_protobuf1 "github.com/gogo/protobuf/types" import google_protobuf2 "github.com/gogo/protobuf/types" import google_protobuf3 "github.com/gogo/protobuf/types" import time "time" import github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type KnownTypes struct { Dur *google_protobuf1.Duration `protobuf:"bytes,1,opt,name=dur" json:"dur,omitempty"` Ts *google_protobuf2.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"` Dbl *google_protobuf3.DoubleValue `protobuf:"bytes,3,opt,name=dbl" json:"dbl,omitempty"` Flt *google_protobuf3.FloatValue `protobuf:"bytes,4,opt,name=flt" json:"flt,omitempty"` I64 *google_protobuf3.Int64Value `protobuf:"bytes,5,opt,name=i64" json:"i64,omitempty"` U64 *google_protobuf3.UInt64Value `protobuf:"bytes,6,opt,name=u64" json:"u64,omitempty"` I32 *google_protobuf3.Int32Value `protobuf:"bytes,7,opt,name=i32" json:"i32,omitempty"` U32 *google_protobuf3.UInt32Value `protobuf:"bytes,8,opt,name=u32" json:"u32,omitempty"` Bool *google_protobuf3.BoolValue `protobuf:"bytes,9,opt,name=bool" json:"bool,omitempty"` Str *google_protobuf3.StringValue `protobuf:"bytes,10,opt,name=str" json:"str,omitempty"` Bytes *google_protobuf3.BytesValue `protobuf:"bytes,11,opt,name=bytes" json:"bytes,omitempty"` } func (m *KnownTypes) Reset() { *m = KnownTypes{} } func (m *KnownTypes) String() string { return proto.CompactTextString(m) } func (*KnownTypes) ProtoMessage() {} func (*KnownTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{0} } func (m *KnownTypes) GetDur() *google_protobuf1.Duration { if m != nil { return m.Dur } return nil } func (m *KnownTypes) GetTs() *google_protobuf2.Timestamp { if m != nil { return m.Ts } return nil } func (m *KnownTypes) GetDbl() *google_protobuf3.DoubleValue { if m != nil { return m.Dbl } return nil } func (m *KnownTypes) GetFlt() *google_protobuf3.FloatValue { if m != nil { return m.Flt } return nil } func (m *KnownTypes) GetI64() *google_protobuf3.Int64Value { if m != nil { return m.I64 } return nil } func (m *KnownTypes) GetU64() *google_protobuf3.UInt64Value { if m != nil { return m.U64 } return nil } func (m *KnownTypes) GetI32() *google_protobuf3.Int32Value { if m != nil { return m.I32 } return nil } func (m *KnownTypes) GetU32() *google_protobuf3.UInt32Value { if m != nil { return m.U32 } return nil } func (m *KnownTypes) GetBool() *google_protobuf3.BoolValue { if m != nil { return m.Bool } return nil } func (m *KnownTypes) GetStr() *google_protobuf3.StringValue { if m != nil { return m.Str } return nil } func (m *KnownTypes) GetBytes() *google_protobuf3.BytesValue { if m != nil { return m.Bytes } return nil } type ProtoTypes struct { NullableTimestamp *google_protobuf2.Timestamp `protobuf:"bytes,1,opt,name=nullableTimestamp" json:"nullableTimestamp,omitempty"` NullableDuration *google_protobuf1.Duration `protobuf:"bytes,2,opt,name=nullableDuration" json:"nullableDuration,omitempty"` Timestamp google_protobuf2.Timestamp `protobuf:"bytes,3,opt,name=timestamp" json:"timestamp"` Duration google_protobuf1.Duration `protobuf:"bytes,4,opt,name=duration" json:"duration"` } func (m *ProtoTypes) Reset() { *m = ProtoTypes{} } func (m *ProtoTypes) String() string { return proto.CompactTextString(m) } func (*ProtoTypes) ProtoMessage() {} func (*ProtoTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{1} } func (m *ProtoTypes) GetNullableTimestamp() *google_protobuf2.Timestamp { if m != nil { return m.NullableTimestamp } return nil } func (m *ProtoTypes) GetNullableDuration() *google_protobuf1.Duration { if m != nil { return m.NullableDuration } return nil } func (m *ProtoTypes) GetTimestamp() google_protobuf2.Timestamp { if m != nil { return m.Timestamp } return google_protobuf2.Timestamp{} } func (m *ProtoTypes) GetDuration() google_protobuf1.Duration { if m != nil { return m.Duration } return google_protobuf1.Duration{} } type StdTypes struct { NullableTimestamp *time.Time `protobuf:"bytes,1,opt,name=nullableTimestamp,stdtime" json:"nullableTimestamp,omitempty"` NullableDuration *time.Duration `protobuf:"bytes,2,opt,name=nullableDuration,stdduration" json:"nullableDuration,omitempty"` Timestamp time.Time `protobuf:"bytes,3,opt,name=timestamp,stdtime" json:"timestamp"` Duration time.Duration `protobuf:"bytes,4,opt,name=duration,stdduration" json:"duration"` } func (m *StdTypes) Reset() { *m = StdTypes{} } func (m *StdTypes) String() string { return proto.CompactTextString(m) } func (*StdTypes) ProtoMessage() {} func (*StdTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{2} } func (m *StdTypes) GetNullableTimestamp() *time.Time { if m != nil { return m.NullableTimestamp } return nil } func (m *StdTypes) GetNullableDuration() *time.Duration { if m != nil { return m.NullableDuration } return nil } func (m *StdTypes) GetTimestamp() time.Time { if m != nil { return m.Timestamp } return time.Time{} } func (m *StdTypes) GetDuration() time.Duration { if m != nil { return m.Duration } return 0 } type RepProtoTypes struct { NullableTimestamps []*google_protobuf2.Timestamp `protobuf:"bytes,1,rep,name=nullableTimestamps" json:"nullableTimestamps,omitempty"` NullableDurations []*google_protobuf1.Duration `protobuf:"bytes,2,rep,name=nullableDurations" json:"nullableDurations,omitempty"` Timestamps []google_protobuf2.Timestamp `protobuf:"bytes,3,rep,name=timestamps" json:"timestamps"` Durations []google_protobuf1.Duration `protobuf:"bytes,4,rep,name=durations" json:"durations"` } func (m *RepProtoTypes) Reset() { *m = RepProtoTypes{} } func (m *RepProtoTypes) String() string { return proto.CompactTextString(m) } func (*RepProtoTypes) ProtoMessage() {} func (*RepProtoTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{3} } func (m *RepProtoTypes) GetNullableTimestamps() []*google_protobuf2.Timestamp { if m != nil { return m.NullableTimestamps } return nil } func (m *RepProtoTypes) GetNullableDurations() []*google_protobuf1.Duration { if m != nil { return m.NullableDurations } return nil } func (m *RepProtoTypes) GetTimestamps() []google_protobuf2.Timestamp { if m != nil { return m.Timestamps } return nil } func (m *RepProtoTypes) GetDurations() []google_protobuf1.Duration { if m != nil { return m.Durations } return nil } type RepStdTypes struct { NullableTimestamps []*time.Time `protobuf:"bytes,1,rep,name=nullableTimestamps,stdtime" json:"nullableTimestamps,omitempty"` NullableDurations []*time.Duration `protobuf:"bytes,2,rep,name=nullableDurations,stdduration" json:"nullableDurations,omitempty"` Timestamps []time.Time `protobuf:"bytes,3,rep,name=timestamps,stdtime" json:"timestamps"` Durations []time.Duration `protobuf:"bytes,4,rep,name=durations,stdduration" json:"durations"` } func (m *RepStdTypes) Reset() { *m = RepStdTypes{} } func (m *RepStdTypes) String() string { return proto.CompactTextString(m) } func (*RepStdTypes) ProtoMessage() {} func (*RepStdTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{4} } func (m *RepStdTypes) GetNullableTimestamps() []*time.Time { if m != nil { return m.NullableTimestamps } return nil } func (m *RepStdTypes) GetNullableDurations() []*time.Duration { if m != nil { return m.NullableDurations } return nil } func (m *RepStdTypes) GetTimestamps() []time.Time { if m != nil { return m.Timestamps } return nil } func (m *RepStdTypes) GetDurations() []time.Duration { if m != nil { return m.Durations } return nil } type MapProtoTypes struct { NullableTimestamp map[int32]*google_protobuf2.Timestamp `protobuf:"bytes,1,rep,name=nullableTimestamp" json:"nullableTimestamp,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` Timestamp map[int32]google_protobuf2.Timestamp `protobuf:"bytes,2,rep,name=timestamp" json:"timestamp" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` NullableDuration map[int32]*google_protobuf1.Duration `protobuf:"bytes,3,rep,name=nullableDuration" json:"nullableDuration,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` Duration map[int32]google_protobuf1.Duration `protobuf:"bytes,4,rep,name=duration" json:"duration" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` } func (m *MapProtoTypes) Reset() { *m = MapProtoTypes{} } func (m *MapProtoTypes) String() string { return proto.CompactTextString(m) } func (*MapProtoTypes) ProtoMessage() {} func (*MapProtoTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{5} } func (m *MapProtoTypes) GetNullableTimestamp() map[int32]*google_protobuf2.Timestamp { if m != nil { return m.NullableTimestamp } return nil } func (m *MapProtoTypes) GetTimestamp() map[int32]google_protobuf2.Timestamp { if m != nil { return m.Timestamp } return nil } func (m *MapProtoTypes) GetNullableDuration() map[int32]*google_protobuf1.Duration { if m != nil { return m.NullableDuration } return nil } func (m *MapProtoTypes) GetDuration() map[int32]google_protobuf1.Duration { if m != nil { return m.Duration } return nil } type MapStdTypes struct { NullableTimestamp map[int32]*time.Time `protobuf:"bytes,1,rep,name=nullableTimestamp,stdtime" json:"nullableTimestamp,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` Timestamp map[int32]time.Time `protobuf:"bytes,2,rep,name=timestamp,stdtime" json:"timestamp" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` NullableDuration map[int32]*time.Duration `protobuf:"bytes,3,rep,name=nullableDuration,stdduration" json:"nullableDuration,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` Duration map[int32]time.Duration `protobuf:"bytes,4,rep,name=duration,stdduration" json:"duration" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` } func (m *MapStdTypes) Reset() { *m = MapStdTypes{} } func (m *MapStdTypes) String() string { return proto.CompactTextString(m) } func (*MapStdTypes) ProtoMessage() {} func (*MapStdTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{6} } func (m *MapStdTypes) GetNullableTimestamp() map[int32]*time.Time { if m != nil { return m.NullableTimestamp } return nil } func (m *MapStdTypes) GetTimestamp() map[int32]time.Time { if m != nil { return m.Timestamp } return nil } func (m *MapStdTypes) GetNullableDuration() map[int32]*time.Duration { if m != nil { return m.NullableDuration } return nil } func (m *MapStdTypes) GetDuration() map[int32]time.Duration { if m != nil { return m.Duration } return nil } type OneofProtoTypes struct { // Types that are valid to be assigned to OneOfProtoTimes: // *OneofProtoTypes_Timestamp // *OneofProtoTypes_Duration OneOfProtoTimes isOneofProtoTypes_OneOfProtoTimes `protobuf_oneof:"OneOfProtoTimes"` } func (m *OneofProtoTypes) Reset() { *m = OneofProtoTypes{} } func (m *OneofProtoTypes) String() string { return proto.CompactTextString(m) } func (*OneofProtoTypes) ProtoMessage() {} func (*OneofProtoTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{7} } type isOneofProtoTypes_OneOfProtoTimes interface { isOneofProtoTypes_OneOfProtoTimes() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type OneofProtoTypes_Timestamp struct { Timestamp *google_protobuf2.Timestamp `protobuf:"bytes,1,opt,name=timestamp,oneof"` } type OneofProtoTypes_Duration struct { Duration *google_protobuf1.Duration `protobuf:"bytes,2,opt,name=duration,oneof"` } func (*OneofProtoTypes_Timestamp) isOneofProtoTypes_OneOfProtoTimes() {} func (*OneofProtoTypes_Duration) isOneofProtoTypes_OneOfProtoTimes() {} func (m *OneofProtoTypes) GetOneOfProtoTimes() isOneofProtoTypes_OneOfProtoTimes { if m != nil { return m.OneOfProtoTimes } return nil } func (m *OneofProtoTypes) GetTimestamp() *google_protobuf2.Timestamp { if x, ok := m.GetOneOfProtoTimes().(*OneofProtoTypes_Timestamp); ok { return x.Timestamp } return nil } func (m *OneofProtoTypes) GetDuration() *google_protobuf1.Duration { if x, ok := m.GetOneOfProtoTimes().(*OneofProtoTypes_Duration); ok { return x.Duration } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*OneofProtoTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _OneofProtoTypes_OneofMarshaler, _OneofProtoTypes_OneofUnmarshaler, _OneofProtoTypes_OneofSizer, []interface{}{ (*OneofProtoTypes_Timestamp)(nil), (*OneofProtoTypes_Duration)(nil), } } func _OneofProtoTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*OneofProtoTypes) // OneOfProtoTimes switch x := m.OneOfProtoTimes.(type) { case *OneofProtoTypes_Timestamp: _ = b.EncodeVarint(1<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Timestamp); err != nil { return err } case *OneofProtoTypes_Duration: _ = b.EncodeVarint(2<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Duration); err != nil { return err } case nil: default: return fmt.Errorf("OneofProtoTypes.OneOfProtoTimes has unexpected type %T", x) } return nil } func _OneofProtoTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*OneofProtoTypes) switch tag { case 1: // OneOfProtoTimes.timestamp if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(google_protobuf2.Timestamp) err := b.DecodeMessage(msg) m.OneOfProtoTimes = &OneofProtoTypes_Timestamp{msg} return true, err case 2: // OneOfProtoTimes.duration if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(google_protobuf1.Duration) err := b.DecodeMessage(msg) m.OneOfProtoTimes = &OneofProtoTypes_Duration{msg} return true, err default: return false, nil } } func _OneofProtoTypes_OneofSizer(msg proto.Message) (n int) { m := msg.(*OneofProtoTypes) // OneOfProtoTimes switch x := m.OneOfProtoTimes.(type) { case *OneofProtoTypes_Timestamp: s := proto.Size(x.Timestamp) n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *OneofProtoTypes_Duration: s := proto.Size(x.Duration) n += proto.SizeVarint(2<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type OneofStdTypes struct { // Types that are valid to be assigned to OneOfStdTimes: // *OneofStdTypes_Timestamp // *OneofStdTypes_Duration OneOfStdTimes isOneofStdTypes_OneOfStdTimes `protobuf_oneof:"OneOfStdTimes"` } func (m *OneofStdTypes) Reset() { *m = OneofStdTypes{} } func (m *OneofStdTypes) String() string { return proto.CompactTextString(m) } func (*OneofStdTypes) ProtoMessage() {} func (*OneofStdTypes) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{8} } type isOneofStdTypes_OneOfStdTimes interface { isOneofStdTypes_OneOfStdTimes() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type OneofStdTypes_Timestamp struct { Timestamp *time.Time `protobuf:"bytes,1,opt,name=timestamp,oneof,stdtime"` } type OneofStdTypes_Duration struct { Duration *time.Duration `protobuf:"bytes,2,opt,name=duration,oneof,stdduration"` } func (*OneofStdTypes_Timestamp) isOneofStdTypes_OneOfStdTimes() {} func (*OneofStdTypes_Duration) isOneofStdTypes_OneOfStdTimes() {} func (m *OneofStdTypes) GetOneOfStdTimes() isOneofStdTypes_OneOfStdTimes { if m != nil { return m.OneOfStdTimes } return nil } func (m *OneofStdTypes) GetTimestamp() *time.Time { if x, ok := m.GetOneOfStdTimes().(*OneofStdTypes_Timestamp); ok { return x.Timestamp } return nil } func (m *OneofStdTypes) GetDuration() *time.Duration { if x, ok := m.GetOneOfStdTimes().(*OneofStdTypes_Duration); ok { return x.Duration } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*OneofStdTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _OneofStdTypes_OneofMarshaler, _OneofStdTypes_OneofUnmarshaler, _OneofStdTypes_OneofSizer, []interface{}{ (*OneofStdTypes_Timestamp)(nil), (*OneofStdTypes_Duration)(nil), } } func _OneofStdTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*OneofStdTypes) // OneOfStdTimes switch x := m.OneOfStdTimes.(type) { case *OneofStdTypes_Timestamp: _ = b.EncodeVarint(1<<3 | proto.WireBytes) data, err := github_com_gogo_protobuf_types.StdTimeMarshal(*x.Timestamp) if err != nil { return err } if err := b.EncodeRawBytes(data); err != nil { return err } case *OneofStdTypes_Duration: _ = b.EncodeVarint(2<<3 | proto.WireBytes) data, err := github_com_gogo_protobuf_types.StdDurationMarshal(*x.Duration) if err != nil { return err } if err := b.EncodeRawBytes(data); err != nil { return err } case nil: default: return fmt.Errorf("OneofStdTypes.OneOfStdTimes has unexpected type %T", x) } return nil } func _OneofStdTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*OneofStdTypes) switch tag { case 1: // OneOfStdTimes.timestamp if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) if err != nil { return true, err } c := new(time.Time) if err2 := github_com_gogo_protobuf_types.StdTimeUnmarshal(c, x); err2 != nil { return true, err } m.OneOfStdTimes = &OneofStdTypes_Timestamp{c} return true, err case 2: // OneOfStdTimes.duration if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) if err != nil { return true, err } c := new(time.Duration) if err2 := github_com_gogo_protobuf_types.StdDurationUnmarshal(c, x); err2 != nil { return true, err } m.OneOfStdTimes = &OneofStdTypes_Duration{c} return true, err default: return false, nil } } func _OneofStdTypes_OneofSizer(msg proto.Message) (n int) { m := msg.(*OneofStdTypes) // OneOfStdTimes switch x := m.OneOfStdTimes.(type) { case *OneofStdTypes_Timestamp: s := github_com_gogo_protobuf_types.SizeOfStdTime(*x.Timestamp) n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *OneofStdTypes_Duration: s := github_com_gogo_protobuf_types.SizeOfStdDuration(*x.Duration) n += proto.SizeVarint(2<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } func init() { proto.RegisterType((*KnownTypes)(nil), "types.KnownTypes") proto.RegisterType((*ProtoTypes)(nil), "types.ProtoTypes") proto.RegisterType((*StdTypes)(nil), "types.StdTypes") proto.RegisterType((*RepProtoTypes)(nil), "types.RepProtoTypes") proto.RegisterType((*RepStdTypes)(nil), "types.RepStdTypes") proto.RegisterType((*MapProtoTypes)(nil), "types.MapProtoTypes") proto.RegisterType((*MapStdTypes)(nil), "types.MapStdTypes") proto.RegisterType((*OneofProtoTypes)(nil), "types.OneofProtoTypes") proto.RegisterType((*OneofStdTypes)(nil), "types.OneofStdTypes") } func (this *KnownTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*KnownTypes) if !ok { that2, ok := that.(KnownTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *KnownTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *KnownTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *KnownTypes but is not nil && this == nil") } if !this.Dur.Equal(that1.Dur) { return fmt.Errorf("Dur this(%v) Not Equal that(%v)", this.Dur, that1.Dur) } if !this.Ts.Equal(that1.Ts) { return fmt.Errorf("Ts this(%v) Not Equal that(%v)", this.Ts, that1.Ts) } if !this.Dbl.Equal(that1.Dbl) { return fmt.Errorf("Dbl this(%v) Not Equal that(%v)", this.Dbl, that1.Dbl) } if !this.Flt.Equal(that1.Flt) { return fmt.Errorf("Flt this(%v) Not Equal that(%v)", this.Flt, that1.Flt) } if !this.I64.Equal(that1.I64) { return fmt.Errorf("I64 this(%v) Not Equal that(%v)", this.I64, that1.I64) } if !this.U64.Equal(that1.U64) { return fmt.Errorf("U64 this(%v) Not Equal that(%v)", this.U64, that1.U64) } if !this.I32.Equal(that1.I32) { return fmt.Errorf("I32 this(%v) Not Equal that(%v)", this.I32, that1.I32) } if !this.U32.Equal(that1.U32) { return fmt.Errorf("U32 this(%v) Not Equal that(%v)", this.U32, that1.U32) } if !this.Bool.Equal(that1.Bool) { return fmt.Errorf("Bool this(%v) Not Equal that(%v)", this.Bool, that1.Bool) } if !this.Str.Equal(that1.Str) { return fmt.Errorf("Str this(%v) Not Equal that(%v)", this.Str, that1.Str) } if !this.Bytes.Equal(that1.Bytes) { return fmt.Errorf("Bytes this(%v) Not Equal that(%v)", this.Bytes, that1.Bytes) } return nil } func (this *KnownTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*KnownTypes) if !ok { that2, ok := that.(KnownTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.Dur.Equal(that1.Dur) { return false } if !this.Ts.Equal(that1.Ts) { return false } if !this.Dbl.Equal(that1.Dbl) { return false } if !this.Flt.Equal(that1.Flt) { return false } if !this.I64.Equal(that1.I64) { return false } if !this.U64.Equal(that1.U64) { return false } if !this.I32.Equal(that1.I32) { return false } if !this.U32.Equal(that1.U32) { return false } if !this.Bool.Equal(that1.Bool) { return false } if !this.Str.Equal(that1.Str) { return false } if !this.Bytes.Equal(that1.Bytes) { return false } return true } func (this *ProtoTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*ProtoTypes) if !ok { that2, ok := that.(ProtoTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *ProtoTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *ProtoTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *ProtoTypes but is not nil && this == nil") } if !this.NullableTimestamp.Equal(that1.NullableTimestamp) { return fmt.Errorf("NullableTimestamp this(%v) Not Equal that(%v)", this.NullableTimestamp, that1.NullableTimestamp) } if !this.NullableDuration.Equal(that1.NullableDuration) { return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", this.NullableDuration, that1.NullableDuration) } if !this.Timestamp.Equal(&that1.Timestamp) { return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", this.Timestamp, that1.Timestamp) } if !this.Duration.Equal(&that1.Duration) { return fmt.Errorf("Duration this(%v) Not Equal that(%v)", this.Duration, that1.Duration) } return nil } func (this *ProtoTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*ProtoTypes) if !ok { that2, ok := that.(ProtoTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.NullableTimestamp.Equal(that1.NullableTimestamp) { return false } if !this.NullableDuration.Equal(that1.NullableDuration) { return false } if !this.Timestamp.Equal(&that1.Timestamp) { return false } if !this.Duration.Equal(&that1.Duration) { return false } return true } func (this *StdTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*StdTypes) if !ok { that2, ok := that.(StdTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *StdTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *StdTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *StdTypes but is not nil && this == nil") } if that1.NullableTimestamp == nil { if this.NullableTimestamp != nil { return fmt.Errorf("this.NullableTimestamp != nil && that1.NullableTimestamp == nil") } } else if !this.NullableTimestamp.Equal(*that1.NullableTimestamp) { return fmt.Errorf("NullableTimestamp this(%v) Not Equal that(%v)", this.NullableTimestamp, that1.NullableTimestamp) } if this.NullableDuration != nil && that1.NullableDuration != nil { if *this.NullableDuration != *that1.NullableDuration { return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", *this.NullableDuration, *that1.NullableDuration) } } else if this.NullableDuration != nil { return fmt.Errorf("this.NullableDuration == nil && that.NullableDuration != nil") } else if that1.NullableDuration != nil { return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", this.NullableDuration, that1.NullableDuration) } if !this.Timestamp.Equal(that1.Timestamp) { return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", this.Timestamp, that1.Timestamp) } if this.Duration != that1.Duration { return fmt.Errorf("Duration this(%v) Not Equal that(%v)", this.Duration, that1.Duration) } return nil } func (this *StdTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*StdTypes) if !ok { that2, ok := that.(StdTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.NullableTimestamp == nil { if this.NullableTimestamp != nil { return false } } else if !this.NullableTimestamp.Equal(*that1.NullableTimestamp) { return false } if this.NullableDuration != nil && that1.NullableDuration != nil { if *this.NullableDuration != *that1.NullableDuration { return false } } else if this.NullableDuration != nil { return false } else if that1.NullableDuration != nil { return false } if !this.Timestamp.Equal(that1.Timestamp) { return false } if this.Duration != that1.Duration { return false } return true } func (this *RepProtoTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*RepProtoTypes) if !ok { that2, ok := that.(RepProtoTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *RepProtoTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *RepProtoTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *RepProtoTypes but is not nil && this == nil") } if len(this.NullableTimestamps) != len(that1.NullableTimestamps) { return fmt.Errorf("NullableTimestamps this(%v) Not Equal that(%v)", len(this.NullableTimestamps), len(that1.NullableTimestamps)) } for i := range this.NullableTimestamps { if !this.NullableTimestamps[i].Equal(that1.NullableTimestamps[i]) { return fmt.Errorf("NullableTimestamps this[%v](%v) Not Equal that[%v](%v)", i, this.NullableTimestamps[i], i, that1.NullableTimestamps[i]) } } if len(this.NullableDurations) != len(that1.NullableDurations) { return fmt.Errorf("NullableDurations this(%v) Not Equal that(%v)", len(this.NullableDurations), len(that1.NullableDurations)) } for i := range this.NullableDurations { if !this.NullableDurations[i].Equal(that1.NullableDurations[i]) { return fmt.Errorf("NullableDurations this[%v](%v) Not Equal that[%v](%v)", i, this.NullableDurations[i], i, that1.NullableDurations[i]) } } if len(this.Timestamps) != len(that1.Timestamps) { return fmt.Errorf("Timestamps this(%v) Not Equal that(%v)", len(this.Timestamps), len(that1.Timestamps)) } for i := range this.Timestamps { if !this.Timestamps[i].Equal(&that1.Timestamps[i]) { return fmt.Errorf("Timestamps this[%v](%v) Not Equal that[%v](%v)", i, this.Timestamps[i], i, that1.Timestamps[i]) } } if len(this.Durations) != len(that1.Durations) { return fmt.Errorf("Durations this(%v) Not Equal that(%v)", len(this.Durations), len(that1.Durations)) } for i := range this.Durations { if !this.Durations[i].Equal(&that1.Durations[i]) { return fmt.Errorf("Durations this[%v](%v) Not Equal that[%v](%v)", i, this.Durations[i], i, that1.Durations[i]) } } return nil } func (this *RepProtoTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*RepProtoTypes) if !ok { that2, ok := that.(RepProtoTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if len(this.NullableTimestamps) != len(that1.NullableTimestamps) { return false } for i := range this.NullableTimestamps { if !this.NullableTimestamps[i].Equal(that1.NullableTimestamps[i]) { return false } } if len(this.NullableDurations) != len(that1.NullableDurations) { return false } for i := range this.NullableDurations { if !this.NullableDurations[i].Equal(that1.NullableDurations[i]) { return false } } if len(this.Timestamps) != len(that1.Timestamps) { return false } for i := range this.Timestamps { if !this.Timestamps[i].Equal(&that1.Timestamps[i]) { return false } } if len(this.Durations) != len(that1.Durations) { return false } for i := range this.Durations { if !this.Durations[i].Equal(&that1.Durations[i]) { return false } } return true } func (this *RepStdTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*RepStdTypes) if !ok { that2, ok := that.(RepStdTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *RepStdTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *RepStdTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *RepStdTypes but is not nil && this == nil") } if len(this.NullableTimestamps) != len(that1.NullableTimestamps) { return fmt.Errorf("NullableTimestamps this(%v) Not Equal that(%v)", len(this.NullableTimestamps), len(that1.NullableTimestamps)) } for i := range this.NullableTimestamps { if !this.NullableTimestamps[i].Equal(*that1.NullableTimestamps[i]) { return fmt.Errorf("NullableTimestamps this[%v](%v) Not Equal that[%v](%v)", i, this.NullableTimestamps[i], i, that1.NullableTimestamps[i]) } } if len(this.NullableDurations) != len(that1.NullableDurations) { return fmt.Errorf("NullableDurations this(%v) Not Equal that(%v)", len(this.NullableDurations), len(that1.NullableDurations)) } for i := range this.NullableDurations { if dthis, dthat := this.NullableDurations[i], that1.NullableDurations[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) { return fmt.Errorf("NullableDurations this[%v](%v) Not Equal that[%v](%v)", i, this.NullableDurations[i], i, that1.NullableDurations[i]) } } if len(this.Timestamps) != len(that1.Timestamps) { return fmt.Errorf("Timestamps this(%v) Not Equal that(%v)", len(this.Timestamps), len(that1.Timestamps)) } for i := range this.Timestamps { if !this.Timestamps[i].Equal(that1.Timestamps[i]) { return fmt.Errorf("Timestamps this[%v](%v) Not Equal that[%v](%v)", i, this.Timestamps[i], i, that1.Timestamps[i]) } } if len(this.Durations) != len(that1.Durations) { return fmt.Errorf("Durations this(%v) Not Equal that(%v)", len(this.Durations), len(that1.Durations)) } for i := range this.Durations { if this.Durations[i] != that1.Durations[i] { return fmt.Errorf("Durations this[%v](%v) Not Equal that[%v](%v)", i, this.Durations[i], i, that1.Durations[i]) } } return nil } func (this *RepStdTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*RepStdTypes) if !ok { that2, ok := that.(RepStdTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if len(this.NullableTimestamps) != len(that1.NullableTimestamps) { return false } for i := range this.NullableTimestamps { if !this.NullableTimestamps[i].Equal(*that1.NullableTimestamps[i]) { return false } } if len(this.NullableDurations) != len(that1.NullableDurations) { return false } for i := range this.NullableDurations { if dthis, dthat := this.NullableDurations[i], that1.NullableDurations[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) { return false } } if len(this.Timestamps) != len(that1.Timestamps) { return false } for i := range this.Timestamps { if !this.Timestamps[i].Equal(that1.Timestamps[i]) { return false } } if len(this.Durations) != len(that1.Durations) { return false } for i := range this.Durations { if this.Durations[i] != that1.Durations[i] { return false } } return true } func (this *MapProtoTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*MapProtoTypes) if !ok { that2, ok := that.(MapProtoTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *MapProtoTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *MapProtoTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *MapProtoTypes but is not nil && this == nil") } if len(this.NullableTimestamp) != len(that1.NullableTimestamp) { return fmt.Errorf("NullableTimestamp this(%v) Not Equal that(%v)", len(this.NullableTimestamp), len(that1.NullableTimestamp)) } for i := range this.NullableTimestamp { if !this.NullableTimestamp[i].Equal(that1.NullableTimestamp[i]) { return fmt.Errorf("NullableTimestamp this[%v](%v) Not Equal that[%v](%v)", i, this.NullableTimestamp[i], i, that1.NullableTimestamp[i]) } } if len(this.Timestamp) != len(that1.Timestamp) { return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", len(this.Timestamp), len(that1.Timestamp)) } for i := range this.Timestamp { a := this.Timestamp[i] b := that1.Timestamp[i] if !(&a).Equal(&b) { return fmt.Errorf("Timestamp this[%v](%v) Not Equal that[%v](%v)", i, this.Timestamp[i], i, that1.Timestamp[i]) } } if len(this.NullableDuration) != len(that1.NullableDuration) { return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", len(this.NullableDuration), len(that1.NullableDuration)) } for i := range this.NullableDuration { if !this.NullableDuration[i].Equal(that1.NullableDuration[i]) { return fmt.Errorf("NullableDuration this[%v](%v) Not Equal that[%v](%v)", i, this.NullableDuration[i], i, that1.NullableDuration[i]) } } if len(this.Duration) != len(that1.Duration) { return fmt.Errorf("Duration this(%v) Not Equal that(%v)", len(this.Duration), len(that1.Duration)) } for i := range this.Duration { a := this.Duration[i] b := that1.Duration[i] if !(&a).Equal(&b) { return fmt.Errorf("Duration this[%v](%v) Not Equal that[%v](%v)", i, this.Duration[i], i, that1.Duration[i]) } } return nil } func (this *MapProtoTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*MapProtoTypes) if !ok { that2, ok := that.(MapProtoTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if len(this.NullableTimestamp) != len(that1.NullableTimestamp) { return false } for i := range this.NullableTimestamp { if !this.NullableTimestamp[i].Equal(that1.NullableTimestamp[i]) { return false } } if len(this.Timestamp) != len(that1.Timestamp) { return false } for i := range this.Timestamp { a := this.Timestamp[i] b := that1.Timestamp[i] if !(&a).Equal(&b) { return false } } if len(this.NullableDuration) != len(that1.NullableDuration) { return false } for i := range this.NullableDuration { if !this.NullableDuration[i].Equal(that1.NullableDuration[i]) { return false } } if len(this.Duration) != len(that1.Duration) { return false } for i := range this.Duration { a := this.Duration[i] b := that1.Duration[i] if !(&a).Equal(&b) { return false } } return true } func (this *MapStdTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*MapStdTypes) if !ok { that2, ok := that.(MapStdTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *MapStdTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *MapStdTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *MapStdTypes but is not nil && this == nil") } if len(this.NullableTimestamp) != len(that1.NullableTimestamp) { return fmt.Errorf("NullableTimestamp this(%v) Not Equal that(%v)", len(this.NullableTimestamp), len(that1.NullableTimestamp)) } for i := range this.NullableTimestamp { if !this.NullableTimestamp[i].Equal(*that1.NullableTimestamp[i]) { return fmt.Errorf("NullableTimestamp this[%v](%v) Not Equal that[%v](%v)", i, this.NullableTimestamp[i], i, that1.NullableTimestamp[i]) } } if len(this.Timestamp) != len(that1.Timestamp) { return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", len(this.Timestamp), len(that1.Timestamp)) } for i := range this.Timestamp { if !this.Timestamp[i].Equal(that1.Timestamp[i]) { return fmt.Errorf("Timestamp this[%v](%v) Not Equal that[%v](%v)", i, this.Timestamp[i], i, that1.Timestamp[i]) } } if len(this.NullableDuration) != len(that1.NullableDuration) { return fmt.Errorf("NullableDuration this(%v) Not Equal that(%v)", len(this.NullableDuration), len(that1.NullableDuration)) } for i := range this.NullableDuration { if dthis, dthat := this.NullableDuration[i], that1.NullableDuration[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) { return fmt.Errorf("NullableDuration this[%v](%v) Not Equal that[%v](%v)", i, this.NullableDuration[i], i, that1.NullableDuration[i]) } } if len(this.Duration) != len(that1.Duration) { return fmt.Errorf("Duration this(%v) Not Equal that(%v)", len(this.Duration), len(that1.Duration)) } for i := range this.Duration { if this.Duration[i] != that1.Duration[i] { return fmt.Errorf("Duration this[%v](%v) Not Equal that[%v](%v)", i, this.Duration[i], i, that1.Duration[i]) } } return nil } func (this *MapStdTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*MapStdTypes) if !ok { that2, ok := that.(MapStdTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if len(this.NullableTimestamp) != len(that1.NullableTimestamp) { return false } for i := range this.NullableTimestamp { if !this.NullableTimestamp[i].Equal(*that1.NullableTimestamp[i]) { return false } } if len(this.Timestamp) != len(that1.Timestamp) { return false } for i := range this.Timestamp { if !this.Timestamp[i].Equal(that1.Timestamp[i]) { return false } } if len(this.NullableDuration) != len(that1.NullableDuration) { return false } for i := range this.NullableDuration { if dthis, dthat := this.NullableDuration[i], that1.NullableDuration[i]; (dthis != nil && dthat != nil && *dthis != *dthat) || (dthis != nil && dthat == nil) || (dthis == nil && dthat != nil) { return false } } if len(this.Duration) != len(that1.Duration) { return false } for i := range this.Duration { if this.Duration[i] != that1.Duration[i] { return false } } return true } func (this *OneofProtoTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*OneofProtoTypes) if !ok { that2, ok := that.(OneofProtoTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *OneofProtoTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *OneofProtoTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *OneofProtoTypes but is not nil && this == nil") } if that1.OneOfProtoTimes == nil { if this.OneOfProtoTimes != nil { return fmt.Errorf("this.OneOfProtoTimes != nil && that1.OneOfProtoTimes == nil") } } else if this.OneOfProtoTimes == nil { return fmt.Errorf("this.OneOfProtoTimes == nil && that1.OneOfProtoTimes != nil") } else if err := this.OneOfProtoTimes.VerboseEqual(that1.OneOfProtoTimes); err != nil { return err } return nil } func (this *OneofProtoTypes_Timestamp) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*OneofProtoTypes_Timestamp) if !ok { that2, ok := that.(OneofProtoTypes_Timestamp) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *OneofProtoTypes_Timestamp") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *OneofProtoTypes_Timestamp but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *OneofProtoTypes_Timestamp but is not nil && this == nil") } if !this.Timestamp.Equal(that1.Timestamp) { return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", this.Timestamp, that1.Timestamp) } return nil } func (this *OneofProtoTypes_Duration) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*OneofProtoTypes_Duration) if !ok { that2, ok := that.(OneofProtoTypes_Duration) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *OneofProtoTypes_Duration") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *OneofProtoTypes_Duration but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *OneofProtoTypes_Duration but is not nil && this == nil") } if !this.Duration.Equal(that1.Duration) { return fmt.Errorf("Duration this(%v) Not Equal that(%v)", this.Duration, that1.Duration) } return nil } func (this *OneofProtoTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*OneofProtoTypes) if !ok { that2, ok := that.(OneofProtoTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.OneOfProtoTimes == nil { if this.OneOfProtoTimes != nil { return false } } else if this.OneOfProtoTimes == nil { return false } else if !this.OneOfProtoTimes.Equal(that1.OneOfProtoTimes) { return false } return true } func (this *OneofProtoTypes_Timestamp) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*OneofProtoTypes_Timestamp) if !ok { that2, ok := that.(OneofProtoTypes_Timestamp) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.Timestamp.Equal(that1.Timestamp) { return false } return true } func (this *OneofProtoTypes_Duration) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*OneofProtoTypes_Duration) if !ok { that2, ok := that.(OneofProtoTypes_Duration) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.Duration.Equal(that1.Duration) { return false } return true } func (this *OneofStdTypes) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*OneofStdTypes) if !ok { that2, ok := that.(OneofStdTypes) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *OneofStdTypes") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *OneofStdTypes but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *OneofStdTypes but is not nil && this == nil") } if that1.OneOfStdTimes == nil { if this.OneOfStdTimes != nil { return fmt.Errorf("this.OneOfStdTimes != nil && that1.OneOfStdTimes == nil") } } else if this.OneOfStdTimes == nil { return fmt.Errorf("this.OneOfStdTimes == nil && that1.OneOfStdTimes != nil") } else if err := this.OneOfStdTimes.VerboseEqual(that1.OneOfStdTimes); err != nil { return err } return nil } func (this *OneofStdTypes_Timestamp) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*OneofStdTypes_Timestamp) if !ok { that2, ok := that.(OneofStdTypes_Timestamp) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *OneofStdTypes_Timestamp") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *OneofStdTypes_Timestamp but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *OneofStdTypes_Timestamp but is not nil && this == nil") } if that1.Timestamp == nil { if this.Timestamp != nil { return fmt.Errorf("this.Timestamp != nil && that1.Timestamp == nil") } } else if !this.Timestamp.Equal(*that1.Timestamp) { return fmt.Errorf("Timestamp this(%v) Not Equal that(%v)", this.Timestamp, that1.Timestamp) } return nil } func (this *OneofStdTypes_Duration) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*OneofStdTypes_Duration) if !ok { that2, ok := that.(OneofStdTypes_Duration) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *OneofStdTypes_Duration") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *OneofStdTypes_Duration but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *OneofStdTypes_Duration but is not nil && this == nil") } if this.Duration != nil && that1.Duration != nil { if *this.Duration != *that1.Duration { return fmt.Errorf("Duration this(%v) Not Equal that(%v)", *this.Duration, *that1.Duration) } } else if this.Duration != nil { return fmt.Errorf("this.Duration == nil && that.Duration != nil") } else if that1.Duration != nil { return fmt.Errorf("Duration this(%v) Not Equal that(%v)", this.Duration, that1.Duration) } return nil } func (this *OneofStdTypes) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*OneofStdTypes) if !ok { that2, ok := that.(OneofStdTypes) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.OneOfStdTimes == nil { if this.OneOfStdTimes != nil { return false } } else if this.OneOfStdTimes == nil { return false } else if !this.OneOfStdTimes.Equal(that1.OneOfStdTimes) { return false } return true } func (this *OneofStdTypes_Timestamp) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*OneofStdTypes_Timestamp) if !ok { that2, ok := that.(OneofStdTypes_Timestamp) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.Timestamp == nil { if this.Timestamp != nil { return false } } else if !this.Timestamp.Equal(*that1.Timestamp) { return false } return true } func (this *OneofStdTypes_Duration) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*OneofStdTypes_Duration) if !ok { that2, ok := that.(OneofStdTypes_Duration) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Duration != nil && that1.Duration != nil { if *this.Duration != *that1.Duration { return false } } else if this.Duration != nil { return false } else if that1.Duration != nil { return false } return true } func NewPopulatedKnownTypes(r randyTypes, easy bool) *KnownTypes { this := &KnownTypes{} if r.Intn(10) != 0 { this.Dur = google_protobuf1.NewPopulatedDuration(r, easy) } if r.Intn(10) != 0 { this.Ts = google_protobuf2.NewPopulatedTimestamp(r, easy) } if r.Intn(10) != 0 { this.Dbl = google_protobuf3.NewPopulatedDoubleValue(r, easy) } if r.Intn(10) != 0 { this.Flt = google_protobuf3.NewPopulatedFloatValue(r, easy) } if r.Intn(10) != 0 { this.I64 = google_protobuf3.NewPopulatedInt64Value(r, easy) } if r.Intn(10) != 0 { this.U64 = google_protobuf3.NewPopulatedUInt64Value(r, easy) } if r.Intn(10) != 0 { this.I32 = google_protobuf3.NewPopulatedInt32Value(r, easy) } if r.Intn(10) != 0 { this.U32 = google_protobuf3.NewPopulatedUInt32Value(r, easy) } if r.Intn(10) != 0 { this.Bool = google_protobuf3.NewPopulatedBoolValue(r, easy) } if r.Intn(10) != 0 { this.Str = google_protobuf3.NewPopulatedStringValue(r, easy) } if r.Intn(10) != 0 { this.Bytes = google_protobuf3.NewPopulatedBytesValue(r, easy) } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedProtoTypes(r randyTypes, easy bool) *ProtoTypes { this := &ProtoTypes{} if r.Intn(10) != 0 { this.NullableTimestamp = google_protobuf2.NewPopulatedTimestamp(r, easy) } if r.Intn(10) != 0 { this.NullableDuration = google_protobuf1.NewPopulatedDuration(r, easy) } v1 := google_protobuf2.NewPopulatedTimestamp(r, easy) this.Timestamp = *v1 v2 := google_protobuf1.NewPopulatedDuration(r, easy) this.Duration = *v2 if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedStdTypes(r randyTypes, easy bool) *StdTypes { this := &StdTypes{} if r.Intn(10) != 0 { this.NullableTimestamp = github_com_gogo_protobuf_types.NewPopulatedStdTime(r, easy) } if r.Intn(10) != 0 { this.NullableDuration = github_com_gogo_protobuf_types.NewPopulatedStdDuration(r, easy) } v3 := github_com_gogo_protobuf_types.NewPopulatedStdTime(r, easy) this.Timestamp = *v3 v4 := github_com_gogo_protobuf_types.NewPopulatedStdDuration(r, easy) this.Duration = *v4 if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedRepProtoTypes(r randyTypes, easy bool) *RepProtoTypes { this := &RepProtoTypes{} if r.Intn(10) != 0 { v5 := r.Intn(5) this.NullableTimestamps = make([]*google_protobuf2.Timestamp, v5) for i := 0; i < v5; i++ { this.NullableTimestamps[i] = google_protobuf2.NewPopulatedTimestamp(r, easy) } } if r.Intn(10) != 0 { v6 := r.Intn(5) this.NullableDurations = make([]*google_protobuf1.Duration, v6) for i := 0; i < v6; i++ { this.NullableDurations[i] = google_protobuf1.NewPopulatedDuration(r, easy) } } if r.Intn(10) != 0 { v7 := r.Intn(5) this.Timestamps = make([]google_protobuf2.Timestamp, v7) for i := 0; i < v7; i++ { v8 := google_protobuf2.NewPopulatedTimestamp(r, easy) this.Timestamps[i] = *v8 } } if r.Intn(10) != 0 { v9 := r.Intn(5) this.Durations = make([]google_protobuf1.Duration, v9) for i := 0; i < v9; i++ { v10 := google_protobuf1.NewPopulatedDuration(r, easy) this.Durations[i] = *v10 } } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedRepStdTypes(r randyTypes, easy bool) *RepStdTypes { this := &RepStdTypes{} if r.Intn(10) != 0 { v11 := r.Intn(5) this.NullableTimestamps = make([]*time.Time, v11) for i := 0; i < v11; i++ { this.NullableTimestamps[i] = github_com_gogo_protobuf_types.NewPopulatedStdTime(r, easy) } } if r.Intn(10) != 0 { v12 := r.Intn(5) this.NullableDurations = make([]*time.Duration, v12) for i := 0; i < v12; i++ { this.NullableDurations[i] = github_com_gogo_protobuf_types.NewPopulatedStdDuration(r, easy) } } if r.Intn(10) != 0 { v13 := r.Intn(5) this.Timestamps = make([]time.Time, v13) for i := 0; i < v13; i++ { v14 := github_com_gogo_protobuf_types.NewPopulatedStdTime(r, easy) this.Timestamps[i] = *v14 } } if r.Intn(10) != 0 { v15 := r.Intn(5) this.Durations = make([]time.Duration, v15) for i := 0; i < v15; i++ { v16 := github_com_gogo_protobuf_types.NewPopulatedStdDuration(r, easy) this.Durations[i] = *v16 } } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedMapProtoTypes(r randyTypes, easy bool) *MapProtoTypes { this := &MapProtoTypes{} if r.Intn(10) != 0 { v17 := r.Intn(10) this.NullableTimestamp = make(map[int32]*google_protobuf2.Timestamp) for i := 0; i < v17; i++ { this.NullableTimestamp[int32(r.Int31())] = google_protobuf2.NewPopulatedTimestamp(r, easy) } } if r.Intn(10) != 0 { v18 := r.Intn(10) this.Timestamp = make(map[int32]google_protobuf2.Timestamp) for i := 0; i < v18; i++ { this.Timestamp[int32(r.Int31())] = *google_protobuf2.NewPopulatedTimestamp(r, easy) } } if r.Intn(10) != 0 { v19 := r.Intn(10) this.NullableDuration = make(map[int32]*google_protobuf1.Duration) for i := 0; i < v19; i++ { this.NullableDuration[int32(r.Int31())] = google_protobuf1.NewPopulatedDuration(r, easy) } } if r.Intn(10) != 0 { v20 := r.Intn(10) this.Duration = make(map[int32]google_protobuf1.Duration) for i := 0; i < v20; i++ { this.Duration[int32(r.Int31())] = *google_protobuf1.NewPopulatedDuration(r, easy) } } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedMapStdTypes(r randyTypes, easy bool) *MapStdTypes { this := &MapStdTypes{} if r.Intn(10) != 0 { v21 := r.Intn(10) this.NullableTimestamp = make(map[int32]*time.Time) for i := 0; i < v21; i++ { this.NullableTimestamp[int32(r.Int31())] = github_com_gogo_protobuf_types.NewPopulatedStdTime(r, easy) } } if r.Intn(10) != 0 { v22 := r.Intn(10) this.Timestamp = make(map[int32]time.Time) for i := 0; i < v22; i++ { this.Timestamp[int32(r.Int31())] = *github_com_gogo_protobuf_types.NewPopulatedStdTime(r, easy) } } if r.Intn(10) != 0 { v23 := r.Intn(10) this.NullableDuration = make(map[int32]*time.Duration) for i := 0; i < v23; i++ { this.NullableDuration[int32(r.Int31())] = github_com_gogo_protobuf_types.NewPopulatedStdDuration(r, easy) } } if r.Intn(10) != 0 { v24 := r.Intn(10) this.Duration = make(map[int32]time.Duration) for i := 0; i < v24; i++ { this.Duration[int32(r.Int31())] = *github_com_gogo_protobuf_types.NewPopulatedStdDuration(r, easy) } } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedOneofProtoTypes(r randyTypes, easy bool) *OneofProtoTypes { this := &OneofProtoTypes{} oneofNumber_OneOfProtoTimes := []int32{1, 2}[r.Intn(2)] switch oneofNumber_OneOfProtoTimes { case 1: this.OneOfProtoTimes = NewPopulatedOneofProtoTypes_Timestamp(r, easy) case 2: this.OneOfProtoTimes = NewPopulatedOneofProtoTypes_Duration(r, easy) } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedOneofProtoTypes_Timestamp(r randyTypes, easy bool) *OneofProtoTypes_Timestamp { this := &OneofProtoTypes_Timestamp{} this.Timestamp = google_protobuf2.NewPopulatedTimestamp(r, easy) return this } func NewPopulatedOneofProtoTypes_Duration(r randyTypes, easy bool) *OneofProtoTypes_Duration { this := &OneofProtoTypes_Duration{} this.Duration = google_protobuf1.NewPopulatedDuration(r, easy) return this } func NewPopulatedOneofStdTypes(r randyTypes, easy bool) *OneofStdTypes { this := &OneofStdTypes{} oneofNumber_OneOfStdTimes := []int32{1, 2}[r.Intn(2)] switch oneofNumber_OneOfStdTimes { case 1: this.OneOfStdTimes = NewPopulatedOneofStdTypes_Timestamp(r, easy) case 2: this.OneOfStdTimes = NewPopulatedOneofStdTypes_Duration(r, easy) } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedOneofStdTypes_Timestamp(r randyTypes, easy bool) *OneofStdTypes_Timestamp { this := &OneofStdTypes_Timestamp{} this.Timestamp = github_com_gogo_protobuf_types.NewPopulatedStdTime(r, easy) return this } func NewPopulatedOneofStdTypes_Duration(r randyTypes, easy bool) *OneofStdTypes_Duration { this := &OneofStdTypes_Duration{} this.Duration = github_com_gogo_protobuf_types.NewPopulatedStdDuration(r, easy) return this } type randyTypes interface { Float32() float32 Float64() float64 Int63() int64 Int31() int32 Uint32() uint32 Intn(n int) int } func randUTF8RuneTypes(r randyTypes) rune { ru := r.Intn(62) if ru < 10 { return rune(ru + 48) } else if ru < 36 { return rune(ru + 55) } return rune(ru + 61) } func randStringTypes(r randyTypes) string { v25 := r.Intn(100) tmps := make([]rune, v25) for i := 0; i < v25; i++ { tmps[i] = randUTF8RuneTypes(r) } return string(tmps) } func randUnrecognizedTypes(r randyTypes, maxFieldNumber int) (data []byte) { l := r.Intn(5) for i := 0; i < l; i++ { wire := r.Intn(4) if wire == 3 { wire = 5 } fieldNumber := maxFieldNumber + r.Intn(100) data = randFieldTypes(data, r, fieldNumber, wire) } return data } func randFieldTypes(data []byte, r randyTypes, fieldNumber int, wire int) []byte { key := uint32(fieldNumber)<<3 | uint32(wire) switch wire { case 0: data = encodeVarintPopulateTypes(data, uint64(key)) v26 := r.Int63() if r.Intn(2) == 0 { v26 *= -1 } data = encodeVarintPopulateTypes(data, uint64(v26)) case 1: data = encodeVarintPopulateTypes(data, uint64(key)) data = append(data, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) case 2: data = encodeVarintPopulateTypes(data, uint64(key)) ll := r.Intn(100) data = encodeVarintPopulateTypes(data, uint64(ll)) for j := 0; j < ll; j++ { data = append(data, byte(r.Intn(256))) } default: data = encodeVarintPopulateTypes(data, uint64(key)) data = append(data, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) } return data } func encodeVarintPopulateTypes(data []byte, v uint64) []byte { for v >= 1<<7 { data = append(data, uint8(uint64(v)&0x7f|0x80)) v >>= 7 } data = append(data, uint8(v)) return data } func (m *KnownTypes) Size() (n int) { var l int _ = l if m.Dur != nil { l = m.Dur.Size() n += 1 + l + sovTypes(uint64(l)) } if m.Ts != nil { l = m.Ts.Size() n += 1 + l + sovTypes(uint64(l)) } if m.Dbl != nil { l = m.Dbl.Size() n += 1 + l + sovTypes(uint64(l)) } if m.Flt != nil { l = m.Flt.Size() n += 1 + l + sovTypes(uint64(l)) } if m.I64 != nil { l = m.I64.Size() n += 1 + l + sovTypes(uint64(l)) } if m.U64 != nil { l = m.U64.Size() n += 1 + l + sovTypes(uint64(l)) } if m.I32 != nil { l = m.I32.Size() n += 1 + l + sovTypes(uint64(l)) } if m.U32 != nil { l = m.U32.Size() n += 1 + l + sovTypes(uint64(l)) } if m.Bool != nil { l = m.Bool.Size() n += 1 + l + sovTypes(uint64(l)) } if m.Str != nil { l = m.Str.Size() n += 1 + l + sovTypes(uint64(l)) } if m.Bytes != nil { l = m.Bytes.Size() n += 1 + l + sovTypes(uint64(l)) } return n } func (m *ProtoTypes) Size() (n int) { var l int _ = l if m.NullableTimestamp != nil { l = m.NullableTimestamp.Size() n += 1 + l + sovTypes(uint64(l)) } if m.NullableDuration != nil { l = m.NullableDuration.Size() n += 1 + l + sovTypes(uint64(l)) } l = m.Timestamp.Size() n += 1 + l + sovTypes(uint64(l)) l = m.Duration.Size() n += 1 + l + sovTypes(uint64(l)) return n } func (m *StdTypes) Size() (n int) { var l int _ = l if m.NullableTimestamp != nil { l = github_com_gogo_protobuf_types.SizeOfStdTime(*m.NullableTimestamp) n += 1 + l + sovTypes(uint64(l)) } if m.NullableDuration != nil { l = github_com_gogo_protobuf_types.SizeOfStdDuration(*m.NullableDuration) n += 1 + l + sovTypes(uint64(l)) } l = github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp) n += 1 + l + sovTypes(uint64(l)) l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.Duration) n += 1 + l + sovTypes(uint64(l)) return n } func (m *RepProtoTypes) Size() (n int) { var l int _ = l if len(m.NullableTimestamps) > 0 { for _, e := range m.NullableTimestamps { l = e.Size() n += 1 + l + sovTypes(uint64(l)) } } if len(m.NullableDurations) > 0 { for _, e := range m.NullableDurations { l = e.Size() n += 1 + l + sovTypes(uint64(l)) } } if len(m.Timestamps) > 0 { for _, e := range m.Timestamps { l = e.Size() n += 1 + l + sovTypes(uint64(l)) } } if len(m.Durations) > 0 { for _, e := range m.Durations { l = e.Size() n += 1 + l + sovTypes(uint64(l)) } } return n } func (m *RepStdTypes) Size() (n int) { var l int _ = l if len(m.NullableTimestamps) > 0 { for _, e := range m.NullableTimestamps { l = github_com_gogo_protobuf_types.SizeOfStdTime(*e) n += 1 + l + sovTypes(uint64(l)) } } if len(m.NullableDurations) > 0 { for _, e := range m.NullableDurations { l = github_com_gogo_protobuf_types.SizeOfStdDuration(*e) n += 1 + l + sovTypes(uint64(l)) } } if len(m.Timestamps) > 0 { for _, e := range m.Timestamps { l = github_com_gogo_protobuf_types.SizeOfStdTime(e) n += 1 + l + sovTypes(uint64(l)) } } if len(m.Durations) > 0 { for _, e := range m.Durations { l = github_com_gogo_protobuf_types.SizeOfStdDuration(e) n += 1 + l + sovTypes(uint64(l)) } } return n } func (m *MapProtoTypes) Size() (n int) { var l int _ = l if len(m.NullableTimestamp) > 0 { for k, v := range m.NullableTimestamp { _ = k _ = v l = 0 if v != nil { l = v.Size() l += 1 + sovTypes(uint64(l)) } mapEntrySize := 1 + sovTypes(uint64(k)) + l n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } if len(m.Timestamp) > 0 { for k, v := range m.Timestamp { _ = k _ = v l = v.Size() mapEntrySize := 1 + sovTypes(uint64(k)) + 1 + l + sovTypes(uint64(l)) n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } if len(m.NullableDuration) > 0 { for k, v := range m.NullableDuration { _ = k _ = v l = 0 if v != nil { l = v.Size() l += 1 + sovTypes(uint64(l)) } mapEntrySize := 1 + sovTypes(uint64(k)) + l n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } if len(m.Duration) > 0 { for k, v := range m.Duration { _ = k _ = v l = v.Size() mapEntrySize := 1 + sovTypes(uint64(k)) + 1 + l + sovTypes(uint64(l)) n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } return n } func (m *MapStdTypes) Size() (n int) { var l int _ = l if len(m.NullableTimestamp) > 0 { for k, v := range m.NullableTimestamp { _ = k _ = v l = 0 if v != nil { l = github_com_gogo_protobuf_types.SizeOfStdTime(*v) l += 1 + sovTypes(uint64(l)) } mapEntrySize := 1 + sovTypes(uint64(k)) + l n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } if len(m.Timestamp) > 0 { for k, v := range m.Timestamp { _ = k _ = v l = github_com_gogo_protobuf_types.SizeOfStdTime(v) mapEntrySize := 1 + sovTypes(uint64(k)) + 1 + l + sovTypes(uint64(l)) n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } if len(m.NullableDuration) > 0 { for k, v := range m.NullableDuration { _ = k _ = v l = 0 if v != nil { l = github_com_gogo_protobuf_types.SizeOfStdDuration(*v) l += 1 + sovTypes(uint64(l)) } mapEntrySize := 1 + sovTypes(uint64(k)) + l n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } if len(m.Duration) > 0 { for k, v := range m.Duration { _ = k _ = v l = github_com_gogo_protobuf_types.SizeOfStdDuration(v) mapEntrySize := 1 + sovTypes(uint64(k)) + 1 + l + sovTypes(uint64(l)) n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize)) } } return n } func (m *OneofProtoTypes) Size() (n int) { var l int _ = l if m.OneOfProtoTimes != nil { n += m.OneOfProtoTimes.Size() } return n } func (m *OneofProtoTypes_Timestamp) Size() (n int) { var l int _ = l if m.Timestamp != nil { l = m.Timestamp.Size() n += 1 + l + sovTypes(uint64(l)) } return n } func (m *OneofProtoTypes_Duration) Size() (n int) { var l int _ = l if m.Duration != nil { l = m.Duration.Size() n += 1 + l + sovTypes(uint64(l)) } return n } func (m *OneofStdTypes) Size() (n int) { var l int _ = l if m.OneOfStdTimes != nil { n += m.OneOfStdTimes.Size() } return n } func (m *OneofStdTypes_Timestamp) Size() (n int) { var l int _ = l if m.Timestamp != nil { l = github_com_gogo_protobuf_types.SizeOfStdTime(*m.Timestamp) n += 1 + l + sovTypes(uint64(l)) } return n } func (m *OneofStdTypes_Duration) Size() (n int) { var l int _ = l if m.Duration != nil { l = github_com_gogo_protobuf_types.SizeOfStdDuration(*m.Duration) n += 1 + l + sovTypes(uint64(l)) } return n } func sovTypes(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozTypes(x uint64) (n int) { return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *KnownTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *KnownTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if m.Dur != nil { data[i] = 0xa i++ i = encodeVarintTypes(data, i, uint64(m.Dur.Size())) n1, err := m.Dur.MarshalTo(data[i:]) if err != nil { return 0, err } i += n1 } if m.Ts != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(m.Ts.Size())) n2, err := m.Ts.MarshalTo(data[i:]) if err != nil { return 0, err } i += n2 } if m.Dbl != nil { data[i] = 0x1a i++ i = encodeVarintTypes(data, i, uint64(m.Dbl.Size())) n3, err := m.Dbl.MarshalTo(data[i:]) if err != nil { return 0, err } i += n3 } if m.Flt != nil { data[i] = 0x22 i++ i = encodeVarintTypes(data, i, uint64(m.Flt.Size())) n4, err := m.Flt.MarshalTo(data[i:]) if err != nil { return 0, err } i += n4 } if m.I64 != nil { data[i] = 0x2a i++ i = encodeVarintTypes(data, i, uint64(m.I64.Size())) n5, err := m.I64.MarshalTo(data[i:]) if err != nil { return 0, err } i += n5 } if m.U64 != nil { data[i] = 0x32 i++ i = encodeVarintTypes(data, i, uint64(m.U64.Size())) n6, err := m.U64.MarshalTo(data[i:]) if err != nil { return 0, err } i += n6 } if m.I32 != nil { data[i] = 0x3a i++ i = encodeVarintTypes(data, i, uint64(m.I32.Size())) n7, err := m.I32.MarshalTo(data[i:]) if err != nil { return 0, err } i += n7 } if m.U32 != nil { data[i] = 0x42 i++ i = encodeVarintTypes(data, i, uint64(m.U32.Size())) n8, err := m.U32.MarshalTo(data[i:]) if err != nil { return 0, err } i += n8 } if m.Bool != nil { data[i] = 0x4a i++ i = encodeVarintTypes(data, i, uint64(m.Bool.Size())) n9, err := m.Bool.MarshalTo(data[i:]) if err != nil { return 0, err } i += n9 } if m.Str != nil { data[i] = 0x52 i++ i = encodeVarintTypes(data, i, uint64(m.Str.Size())) n10, err := m.Str.MarshalTo(data[i:]) if err != nil { return 0, err } i += n10 } if m.Bytes != nil { data[i] = 0x5a i++ i = encodeVarintTypes(data, i, uint64(m.Bytes.Size())) n11, err := m.Bytes.MarshalTo(data[i:]) if err != nil { return 0, err } i += n11 } return i, nil } func (m *ProtoTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *ProtoTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if m.NullableTimestamp != nil { data[i] = 0xa i++ i = encodeVarintTypes(data, i, uint64(m.NullableTimestamp.Size())) n12, err := m.NullableTimestamp.MarshalTo(data[i:]) if err != nil { return 0, err } i += n12 } if m.NullableDuration != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(m.NullableDuration.Size())) n13, err := m.NullableDuration.MarshalTo(data[i:]) if err != nil { return 0, err } i += n13 } data[i] = 0x1a i++ i = encodeVarintTypes(data, i, uint64(m.Timestamp.Size())) n14, err := m.Timestamp.MarshalTo(data[i:]) if err != nil { return 0, err } i += n14 data[i] = 0x22 i++ i = encodeVarintTypes(data, i, uint64(m.Duration.Size())) n15, err := m.Duration.MarshalTo(data[i:]) if err != nil { return 0, err } i += n15 return i, nil } func (m *StdTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *StdTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if m.NullableTimestamp != nil { data[i] = 0xa i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(*m.NullableTimestamp))) n16, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(*m.NullableTimestamp, data[i:]) if err != nil { return 0, err } i += n16 } if m.NullableDuration != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(*m.NullableDuration))) n17, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(*m.NullableDuration, data[i:]) if err != nil { return 0, err } i += n17 } data[i] = 0x1a i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(m.Timestamp))) n18, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.Timestamp, data[i:]) if err != nil { return 0, err } i += n18 data[i] = 0x22 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(m.Duration))) n19, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.Duration, data[i:]) if err != nil { return 0, err } i += n19 return i, nil } func (m *RepProtoTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *RepProtoTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if len(m.NullableTimestamps) > 0 { for _, msg := range m.NullableTimestamps { data[i] = 0xa i++ i = encodeVarintTypes(data, i, uint64(msg.Size())) n, err := msg.MarshalTo(data[i:]) if err != nil { return 0, err } i += n } } if len(m.NullableDurations) > 0 { for _, msg := range m.NullableDurations { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(msg.Size())) n, err := msg.MarshalTo(data[i:]) if err != nil { return 0, err } i += n } } if len(m.Timestamps) > 0 { for _, msg := range m.Timestamps { data[i] = 0x1a i++ i = encodeVarintTypes(data, i, uint64(msg.Size())) n, err := msg.MarshalTo(data[i:]) if err != nil { return 0, err } i += n } } if len(m.Durations) > 0 { for _, msg := range m.Durations { data[i] = 0x22 i++ i = encodeVarintTypes(data, i, uint64(msg.Size())) n, err := msg.MarshalTo(data[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *RepStdTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *RepStdTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if len(m.NullableTimestamps) > 0 { for _, msg := range m.NullableTimestamps { data[i] = 0xa i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(*msg))) n, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(*msg, data[i:]) if err != nil { return 0, err } i += n } } if len(m.NullableDurations) > 0 { for _, msg := range m.NullableDurations { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(*msg))) n, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(*msg, data[i:]) if err != nil { return 0, err } i += n } } if len(m.Timestamps) > 0 { for _, msg := range m.Timestamps { data[i] = 0x1a i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(msg))) n, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(msg, data[i:]) if err != nil { return 0, err } i += n } } if len(m.Durations) > 0 { for _, msg := range m.Durations { data[i] = 0x22 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(msg))) n, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(msg, data[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *MapProtoTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *MapProtoTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if len(m.NullableTimestamp) > 0 { for k := range m.NullableTimestamp { data[i] = 0xa i++ v := m.NullableTimestamp[k] msgSize := 0 if v != nil { msgSize = v.Size() msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) if v != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(v.Size())) n20, err := v.MarshalTo(data[i:]) if err != nil { return 0, err } i += n20 } } } if len(m.Timestamp) > 0 { for k := range m.Timestamp { data[i] = 0x12 i++ v := m.Timestamp[k] msgSize := 0 if (&v) != nil { msgSize = (&v).Size() msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64((&v).Size())) n21, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } i += n21 } } if len(m.NullableDuration) > 0 { for k := range m.NullableDuration { data[i] = 0x1a i++ v := m.NullableDuration[k] msgSize := 0 if v != nil { msgSize = v.Size() msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) if v != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(v.Size())) n22, err := v.MarshalTo(data[i:]) if err != nil { return 0, err } i += n22 } } } if len(m.Duration) > 0 { for k := range m.Duration { data[i] = 0x22 i++ v := m.Duration[k] msgSize := 0 if (&v) != nil { msgSize = (&v).Size() msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64((&v).Size())) n23, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } i += n23 } } return i, nil } func (m *MapStdTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *MapStdTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if len(m.NullableTimestamp) > 0 { for k := range m.NullableTimestamp { data[i] = 0xa i++ v := m.NullableTimestamp[k] msgSize := 0 if v != nil { msgSize = github_com_gogo_protobuf_types.SizeOfStdTime(*v) msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) if v != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(*v))) n24, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(*v, data[i:]) if err != nil { return 0, err } i += n24 } } } if len(m.Timestamp) > 0 { for k := range m.Timestamp { data[i] = 0x12 i++ v := m.Timestamp[k] msgSize := 0 if (&v) != nil { msgSize = github_com_gogo_protobuf_types.SizeOfStdTime(*(&v)) msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(*(&v)))) n25, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(*(&v), data[i:]) if err != nil { return 0, err } i += n25 } } if len(m.NullableDuration) > 0 { for k := range m.NullableDuration { data[i] = 0x1a i++ v := m.NullableDuration[k] msgSize := 0 if v != nil { msgSize = github_com_gogo_protobuf_types.SizeOfStdDuration(*v) msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) if v != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(*v))) n26, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(*v, data[i:]) if err != nil { return 0, err } i += n26 } } } if len(m.Duration) > 0 { for k := range m.Duration { data[i] = 0x22 i++ v := m.Duration[k] msgSize := 0 if (&v) != nil { msgSize = github_com_gogo_protobuf_types.SizeOfStdDuration(*(&v)) msgSize += 1 + sovTypes(uint64(msgSize)) } mapSize := 1 + sovTypes(uint64(k)) + msgSize i = encodeVarintTypes(data, i, uint64(mapSize)) data[i] = 0x8 i++ i = encodeVarintTypes(data, i, uint64(k)) data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(*(&v)))) n27, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(*(&v), data[i:]) if err != nil { return 0, err } i += n27 } } return i, nil } func (m *OneofProtoTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *OneofProtoTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if m.OneOfProtoTimes != nil { nn28, err := m.OneOfProtoTimes.MarshalTo(data[i:]) if err != nil { return 0, err } i += nn28 } return i, nil } func (m *OneofProtoTypes_Timestamp) MarshalTo(data []byte) (int, error) { i := 0 if m.Timestamp != nil { data[i] = 0xa i++ i = encodeVarintTypes(data, i, uint64(m.Timestamp.Size())) n29, err := m.Timestamp.MarshalTo(data[i:]) if err != nil { return 0, err } i += n29 } return i, nil } func (m *OneofProtoTypes_Duration) MarshalTo(data []byte) (int, error) { i := 0 if m.Duration != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(m.Duration.Size())) n30, err := m.Duration.MarshalTo(data[i:]) if err != nil { return 0, err } i += n30 } return i, nil } func (m *OneofStdTypes) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *OneofStdTypes) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l if m.OneOfStdTimes != nil { nn31, err := m.OneOfStdTimes.MarshalTo(data[i:]) if err != nil { return 0, err } i += nn31 } return i, nil } func (m *OneofStdTypes_Timestamp) MarshalTo(data []byte) (int, error) { i := 0 if m.Timestamp != nil { data[i] = 0xa i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(*m.Timestamp))) n32, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(*m.Timestamp, data[i:]) if err != nil { return 0, err } i += n32 } return i, nil } func (m *OneofStdTypes_Duration) MarshalTo(data []byte) (int, error) { i := 0 if m.Duration != nil { data[i] = 0x12 i++ i = encodeVarintTypes(data, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(*m.Duration))) n33, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(*m.Duration, data[i:]) if err != nil { return 0, err } i += n33 } return i, nil } func encodeFixed64Types(data []byte, offset int, v uint64) int { data[offset] = uint8(v) data[offset+1] = uint8(v >> 8) data[offset+2] = uint8(v >> 16) data[offset+3] = uint8(v >> 24) data[offset+4] = uint8(v >> 32) data[offset+5] = uint8(v >> 40) data[offset+6] = uint8(v >> 48) data[offset+7] = uint8(v >> 56) return offset + 8 } func encodeFixed32Types(data []byte, offset int, v uint32) int { data[offset] = uint8(v) data[offset+1] = uint8(v >> 8) data[offset+2] = uint8(v >> 16) data[offset+3] = uint8(v >> 24) return offset + 4 } func encodeVarintTypes(data []byte, offset int, v uint64) int { for v >= 1<<7 { data[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } data[offset] = uint8(v) return offset + 1 } func init() { proto.RegisterFile("combos/unsafemarshaler/types.proto", fileDescriptorTypes) } var fileDescriptorTypes = []byte{ // 922 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xec, 0x56, 0xcf, 0x6f, 0xe3, 0x44, 0x18, 0x8d, 0xed, 0x64, 0x49, 0xbf, 0x28, 0xec, 0xae, 0x25, 0x90, 0x09, 0xc8, 0x2d, 0xe6, 0x52, 0x76, 0xb5, 0x0e, 0x24, 0x51, 0x40, 0x8b, 0x16, 0x16, 0xab, 0xbb, 0xdb, 0xa5, 0xea, 0x0f, 0xa5, 0xa5, 0x02, 0x24, 0x10, 0x76, 0xe3, 0xa4, 0x11, 0x8e, 0x27, 0xb2, 0xc7, 0x54, 0xb9, 0xf1, 0x27, 0x70, 0x41, 0x02, 0x6e, 0x1c, 0x90, 0x38, 0x70, 0x87, 0x23, 0x17, 0xa4, 0xde, 0xe0, 0x2f, 0x80, 0x36, 0xfc, 0x13, 0x3d, 0xa2, 0x19, 0xff, 0x8e, 0xc7, 0x0e, 0x89, 0x54, 0x71, 0xd9, 0x5b, 0x9c, 0x79, 0xdf, 0x9b, 0xe7, 0x37, 0xef, 0xfb, 0xc6, 0xa0, 0x9c, 0xa0, 0xb1, 0x81, 0xdc, 0xa6, 0x67, 0xbb, 0xfa, 0xc0, 0x1c, 0xeb, 0x8e, 0x7b, 0xaa, 0x5b, 0xa6, 0xd3, 0xc4, 0xd3, 0x89, 0xe9, 0xaa, 0x13, 0x07, 0x61, 0x24, 0x56, 0xe8, 0x43, 0xe3, 0xde, 0x70, 0x84, 0x4f, 0x3d, 0x43, 0x3d, 0x41, 0xe3, 0xe6, 0x10, 0x0d, 0x51, 0x93, 0xae, 0x1a, 0xde, 0x80, 0x3e, 0xd1, 0x07, 0xfa, 0xcb, 0xaf, 0x6a, 0xc8, 0x43, 0x84, 0x86, 0x96, 0x19, 0xa3, 0xfa, 0x9e, 0xa3, 0xe3, 0x11, 0xb2, 0x83, 0xf5, 0xf5, 0xf9, 0x75, 0x3c, 0x1a, 0x9b, 0x2e, 0xd6, 0xc7, 0x93, 0x3c, 0x82, 0x33, 0x47, 0x9f, 0x4c, 0x4c, 0x27, 0x90, 0xa5, 0x7c, 0x53, 0x06, 0xd8, 0xb1, 0xd1, 0x99, 0x7d, 0x44, 0xe4, 0x89, 0x77, 0x41, 0xe8, 0x7b, 0x8e, 0xc4, 0x6d, 0x70, 0x9b, 0xb5, 0xd6, 0x4b, 0xaa, 0x5f, 0xac, 0x86, 0xc5, 0xea, 0x56, 0xb0, 0x7b, 0x8f, 0xa0, 0xc4, 0x3b, 0xc0, 0x63, 0x57, 0xe2, 0x29, 0xb6, 0x91, 0xc1, 0x1e, 0x85, 0x4a, 0x7a, 0x3c, 0x76, 0x45, 0x15, 0x84, 0xbe, 0x61, 0x49, 0x02, 0x05, 0xbf, 0x92, 0x25, 0x46, 0x9e, 0x61, 0x99, 0xc7, 0xba, 0xe5, 0x99, 0x3d, 0x02, 0x14, 0xef, 0x81, 0x30, 0xb0, 0xb0, 0x54, 0xa6, 0xf8, 0x97, 0x33, 0xf8, 0xc7, 0x16, 0xd2, 0x71, 0x00, 0x1f, 0x58, 0x98, 0xc0, 0x47, 0xdd, 0x8e, 0x54, 0xc9, 0x81, 0x3f, 0xb5, 0x71, 0xb7, 0x13, 0xc0, 0x47, 0xdd, 0x0e, 0x51, 0xe3, 0x75, 0x3b, 0xd2, 0x8d, 0x1c, 0x35, 0x1f, 0x26, 0xf1, 0x5e, 0xb7, 0x43, 0xe9, 0xdb, 0x2d, 0xe9, 0xb9, 0x7c, 0xfa, 0x76, 0x2b, 0xa4, 0x6f, 0xb7, 0x28, 0x7d, 0xbb, 0x25, 0x55, 0x0b, 0xe8, 0x23, 0xbc, 0x47, 0xf1, 0x65, 0x03, 0x21, 0x4b, 0x5a, 0xcb, 0xb1, 0x52, 0x43, 0xc8, 0xf2, 0xe1, 0x14, 0x47, 0xf8, 0x5d, 0xec, 0x48, 0x90, 0xc3, 0x7f, 0x88, 0x9d, 0x91, 0x3d, 0x0c, 0xf8, 0x5d, 0xec, 0x88, 0x6f, 0x42, 0xc5, 0x98, 0x62, 0xd3, 0x95, 0x6a, 0x39, 0x2f, 0xa0, 0x91, 0x55, 0xbf, 0xc0, 0x47, 0x2a, 0xdf, 0xf3, 0x00, 0x07, 0x64, 0xd9, 0xcf, 0xc5, 0x36, 0xdc, 0xb6, 0x3d, 0xcb, 0xd2, 0x0d, 0xcb, 0x8c, 0xce, 0x35, 0x48, 0x49, 0xd1, 0xc9, 0x67, 0x8b, 0xc4, 0x47, 0x70, 0x2b, 0xfc, 0x33, 0x4c, 0x53, 0x10, 0xa1, 0x82, 0xb8, 0x65, 0x4a, 0xc4, 0x77, 0x61, 0x2d, 0x8a, 0x7a, 0x90, 0xaa, 0x02, 0x21, 0x5a, 0xf9, 0xfc, 0xaf, 0xf5, 0x52, 0x2f, 0x2e, 0x11, 0xdf, 0x81, 0x6a, 0xd8, 0x4a, 0x41, 0xc8, 0xf2, 0xb7, 0x0f, 0xaa, 0xa3, 0x02, 0xe5, 0x67, 0x1e, 0xaa, 0x87, 0xb8, 0xef, 0x5b, 0xb3, 0xb7, 0x92, 0x35, 0x5a, 0xf9, 0xeb, 0xbf, 0xd7, 0x39, 0x96, 0x41, 0x3b, 0x2b, 0x18, 0xa4, 0x95, 0xbf, 0x25, 0x6c, 0x59, 0x9b, 0xb4, 0xe5, 0x6c, 0xaa, 0x92, 0x17, 0xa5, 0xc2, 0x12, 0x56, 0xbd, 0xb7, 0x8c, 0x55, 0x94, 0x81, 0x8a, 0x89, 0xed, 0xfa, 0x91, 0x87, 0x7a, 0xcf, 0x9c, 0x24, 0xe2, 0xf4, 0x01, 0x88, 0x99, 0x17, 0x77, 0x25, 0x6e, 0x43, 0x58, 0x90, 0x27, 0x46, 0x95, 0xf8, 0x24, 0xf6, 0x3f, 0x54, 0x41, 0x86, 0x92, 0x50, 0x9c, 0xa8, 0x6c, 0x8d, 0xf8, 0x10, 0x00, 0xc7, 0x62, 0x84, 0x45, 0x62, 0x82, 0x54, 0x24, 0x6a, 0xc4, 0x07, 0xb0, 0xd6, 0x8f, 0x24, 0x94, 0x17, 0x48, 0x08, 0x33, 0x19, 0x55, 0x28, 0xbf, 0xf0, 0x50, 0xeb, 0x99, 0x93, 0x28, 0x59, 0x07, 0xab, 0xb9, 0x14, 0x44, 0x8b, 0xe5, 0xd5, 0xee, 0x2a, 0x5e, 0x05, 0xe1, 0x62, 0x38, 0xb6, 0xb5, 0xa4, 0x63, 0x71, 0xbc, 0x92, 0xae, 0xbd, 0xbf, 0x94, 0x6b, 0x71, 0xc0, 0x12, 0xce, 0xfd, 0x5e, 0x81, 0xfa, 0xae, 0x9e, 0x4c, 0xd8, 0xc7, 0xec, 0xae, 0x24, 0xe4, 0x77, 0x55, 0xff, 0x5e, 0x4e, 0x15, 0xa8, 0x7b, 0xf3, 0xe8, 0x47, 0x36, 0x76, 0xa6, 0xac, 0x06, 0x7d, 0x92, 0xec, 0x29, 0xdf, 0xbc, 0xd7, 0x98, 0x94, 0x69, 0xaa, 0xec, 0x0c, 0x3a, 0x66, 0x74, 0xba, 0x6f, 0xe2, 0x9d, 0x42, 0x89, 0x21, 0xd8, 0x57, 0x98, 0x6d, 0xfa, 0xad, 0x54, 0xc3, 0x12, 0x3e, 0x85, 0xc9, 0x97, 0xe2, 0x99, 0x1f, 0x72, 0x8d, 0xcf, 0xe1, 0x45, 0xb6, 0x27, 0xe2, 0x2d, 0x10, 0xbe, 0x30, 0xa7, 0x74, 0xc6, 0x55, 0x7a, 0xe4, 0xa7, 0xf8, 0x06, 0x54, 0xbe, 0x24, 0xb7, 0xc7, 0x7f, 0xf8, 0x18, 0xf0, 0x81, 0xf7, 0xf9, 0xb7, 0xb9, 0xc6, 0x47, 0xf0, 0xfc, 0x35, 0x31, 0x7f, 0x06, 0x2f, 0x30, 0xcd, 0x62, 0x6c, 0xd0, 0x4c, 0x6f, 0x50, 0x30, 0x32, 0x12, 0xfc, 0xc7, 0x50, 0xbf, 0x0e, 0x5e, 0xe5, 0x8f, 0x0a, 0xd4, 0x76, 0xf5, 0x78, 0x02, 0x7c, 0x9a, 0x9f, 0xe2, 0xd7, 0xe3, 0x23, 0x0d, 0xe1, 0x39, 0x19, 0xce, 0xbf, 0x6a, 0x9e, 0x66, 0x93, 0xfc, 0x2a, 0x83, 0x76, 0x8e, 0x8e, 0x79, 0x49, 0x7c, 0x92, 0x9b, 0xe5, 0xcd, 0x02, 0xa1, 0x73, 0x09, 0xcc, 0xb9, 0xc4, 0x1e, 0x67, 0xf2, 0xbc, 0xc1, 0xe0, 0x4c, 0x73, 0x31, 0xee, 0xa1, 0x67, 0x89, 0xfe, 0x1f, 0x12, 0xfd, 0x1d, 0x07, 0x37, 0xf7, 0x6d, 0x13, 0x0d, 0x12, 0xb3, 0xf9, 0x7e, 0x32, 0x76, 0x0b, 0xbf, 0x94, 0xb6, 0x53, 0x33, 0xf3, 0xad, 0x44, 0x16, 0x16, 0xe9, 0xd8, 0x4e, 0x8c, 0x33, 0xed, 0x36, 0xd5, 0xb1, 0x1f, 0xe8, 0x20, 0x7c, 0xca, 0x0f, 0x1c, 0xd4, 0xa9, 0xb6, 0xa8, 0xdf, 0x1e, 0x2e, 0xa5, 0xcc, 0x6f, 0xac, 0xb4, 0xbe, 0x07, 0x4b, 0xe8, 0xf3, 0x03, 0x9f, 0x52, 0x79, 0x93, 0x2a, 0xda, 0xa7, 0x8a, 0x08, 0xa7, 0xb6, 0x79, 0x71, 0x29, 0x73, 0x57, 0x97, 0x32, 0xf7, 0xd3, 0x4c, 0xe6, 0x7e, 0x9d, 0xc9, 0xdc, 0x6f, 0x33, 0x99, 0x3b, 0x9f, 0xc9, 0xa5, 0x3f, 0x67, 0x72, 0xe9, 0x62, 0x26, 0x73, 0x57, 0x33, 0x99, 0xfb, 0xea, 0x1f, 0xb9, 0x64, 0xdc, 0xa0, 0xfc, 0xed, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf6, 0x96, 0x19, 0xdc, 0x8d, 0x0e, 0x00, 0x00, }
{'content_hash': '6d840c8c1e39f5374cc518b52d4ce2cf', 'timestamp': '', 'source': 'github', 'line_count': 3304, 'max_line_length': 221, 'avg_line_length': 27.69128329297821, 'alnum_prop': 0.651182617059415, 'repo_name': 'jabley/cf-metrics', 'id': 'b5ced21de147f2f22cac093714b7d399ff0de363', 'size': '91492', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/src/github.com/gogo/protobuf/test/types/combos/unsafemarshaler/types.pb.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '19148'}, {'name': 'Makefile', 'bytes': '358'}]}
import cgi import wsgiref import logging import datetime import time from geohash import Geohash from shardedcounter import * from boundsSplitting import * from urlparse import urlparse from django.utils import simplejson from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db class BikeBingle(db.Model): occuredOn = db.DateTimeProperty() enteredOn = db.DateTimeProperty(auto_now_add=True) position = db.GeoPtProperty() description = db.TextProperty() enteredBy = db.UserProperty() injuryIndex = db.IntegerProperty() type = db.IntegerProperty() link = db.LinkProperty() geoHash = db.StringProperty() class BikeBingleHighRes(db.Model): type = db.IntegerProperty() position = db.GeoPtProperty() geoHash = db.StringProperty() class BikeBingleMediumRes(db.Model): type = db.IntegerProperty() position = db.GeoPtProperty() geoHash = db.StringProperty() class BikeBingleLowRes(db.Model): type = db.IntegerProperty() position = db.GeoPtProperty() geoHash = db.StringProperty() def getQueryForLengthSquared(lengthSquared): if lengthSquared < 0.015: return BikeBingle.all() elif lengthSquared < 0.8: return BikeBingleHighRes.all() elif lengthSquared < 800: return BikeBingleMediumRes.all() else: return BikeBingleLowRes.all() class test1(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' #self.response.out.write('Hello, webapp World!') #the name will be obtained from a URL something like # this http://localhost:8080/server/?name=ImReallyGood name = self.request.get("name") self.response.out.write('hello ' + name) class DeleteBingle(webapp.RequestHandler): def post(self): respBody = 'false' bingleId = self.request.body logging.info("request to delete a bingle with id :" + bingleId + ":") if len(bingleId) == 0: #no bingle id given so return respBody = 'false' else: currentUser = users.get_current_user() if not currentUser: #no user logged in so return logging.warn("no user logged in, cannot delete from db") else: entity = BikeBingle.get_by_id(int(bingleId)) if not entity: #no entity returnefd as it mustn't be in the DB so just return logging.warn("no entity found with key " + bingleId) else: if currentUser != entity.enteredBy: #then the user that entered this entity is not the one trying to delete it logging.warn("current user does not match user trying to delete item") else: ChangeCountForBingleType(entity.type,-1) entity.delete() respBody = 'true' self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Content-Length'] = len(respBody) self.response.out.write(respBody) class AddBingle(webapp.RequestHandler): def post(self): args = simplejson.loads(self.request.body) aBingle = self.getBingleFromJsonData(args) #calculate the geohash value for the position latitude = aBingle.position.lat longitude = aBingle.position.lon #yes it needs double brackets around the lat,long pthash = Geohash((latitude,longitude)) aBingle.geoHash = str(pthash) aBingle.put() ChangeCountForBingleType(aBingle.type,1) #now add it to the low res table self.addToHighResIfNecessary(latitude,longitude) logging.info("bingle added to database with id" + str(aBingle.key().id())) def getRoundedValueHigh(self, latOrLng): return round(latOrLng,2) def getRoundedValueMedium(self, latOrLng): return round(latOrLng,1) def getRoundedValueLow(self, latOrLng): return round(latOrLng/2.)*2 def addToHighResIfNecessary(self,lat,lng): latitude = self.getRoundedValueHigh(lat) longitude = self.getRoundedValueHigh(lng) pthash = Geohash((latitude,longitude)) geoHashString = str(pthash) q = BikeBingleHighRes.all() q.filter("geoHash =", geoHashString) res = q.fetch(1) #logging.info("found LODs" + str(len(res))) if len(res) == 0: logging.info("added high res") bblr = BikeBingleHighRes( position=db.GeoPt(lat,lng), geoHash = geoHashString, type = -2 ) bblr.put() self.addToMediumResIfNecessary(lat, lng) def addToMediumResIfNecessary(self,lat,lng): latitude = self.getRoundedValueMedium(lat) longitude = self.getRoundedValueMedium(lng) pthash = Geohash((latitude,longitude)) geoHashString = str(pthash) q = BikeBingleMediumRes.all() q.filter("geoHash =", geoHashString) res = q.fetch(1) #logging.info("found LODs" + str(len(res))) if len(res) == 0: logging.info("added med res") bblr = BikeBingleMediumRes( position=db.GeoPt(lat,lng), geoHash = geoHashString, type = -2 ) bblr.put() self.addToLowResIfNecessary(lat, lng) def addToLowResIfNecessary(self,lat,lng): latitude = self.getRoundedValueLow(lat) longitude = self.getRoundedValueLow(lng) pthash = Geohash((latitude,longitude)) geoHashString = str(pthash) q = BikeBingleLowRes.all() q.filter("geoHash =", geoHashString) res = q.fetch(1) #logging.info("found LODs" + str(len(res))) if len(res) == 0: logging.info("added low res") bblr = BikeBingleLowRes( position=db.GeoPt(lat,lng), geoHash = geoHashString, type = -2 ) bblr.put() def makeLinkValid(self, url): if len(url) == 0: return url elif url.startswith('http://'): return url else: return 'http://' + url def getBingleFromJsonData(self, jsonData): occuredOnDate = datetime.datetime.strptime(jsonData['occuredOn'], "%Y-%m-%d %H:%M:%S"); desc = jsonData['description'] pos = jsonData['position'] lat = pos['lat'] lng =pos['lng'] injury = jsonData['injuryIndex'] typet = jsonData['type'] linkt = jsonData['link'] linkt = self.makeLinkValid(linkt) if len(linkt) == 0: centerBB = BikeBingle(enteredBy=users.get_current_user(), occuredOn=occuredOnDate, enteredOn=datetime.datetime.today(), description=desc, position=db.GeoPt(lat,lng), injuryIndex=injury, type=typet ) else: centerBB = BikeBingle(enteredBy=users.get_current_user(), occuredOn=occuredOnDate, enteredOn=datetime.datetime.today(), description=desc, position=db.GeoPt(lat,lng), injuryIndex=injury, type=typet, link=linkt ) return centerBB class GetBingleCount(webapp.RequestHandler): def get(self): result = 0 bingleType = self.request.get("type") if bingleType: result = GetCountForBingleType(bingleType) else: result = GetCountForAllBingleTypes() respBody = str(result) self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Content-Length'] = len(respBody) self.response.out.write(respBody) class GetLatestBingles(webapp.RequestHandler): def get(self): bingles = self.getLatestBingles() list = [] for aBingle in bingles: list.append(getBingleAsSimplePythonObject(aBingle)) data = simplejson.dumps(list,indent=4) self.response.headers['Content-Length'] = len(data) self.response.out.write(data) def getLatestBingles(self): q = BikeBingle.all() q.order("-enteredOn") res = q.fetch(10) return res class GetBingles(webapp.RequestHandler): def __init__(self): self.__isLowRes = False def get(self): start_time = datetime.datetime.now() #url would be something like # http://localhost:8080/getbingles/?neLatitude=1.23456&neLongitude=2.3456789&swLatitude=3.456789012&swLongitude=4.567890123 neLat = self.request.get("neLatitude") neLng = self.request.get("neLongitude") swLat = self.request.get("swLatitude") swLng = self.request.get("swLongitude") isUserOnly = self.request.get("isuseronly") isLowRes = self.request.get("islowres") #if not isLowRes: # self.__isLowRes = False #elif isLowRes == 'true': # self.__isLowRes = True #else: # self.__isLowRes = False #respString = 'ne=' + neLat + ", " + neLng + " sw=" + swLat + ", " + swLng self.__isLowRes = True #logging.info("getting URL params = " + str(datetime.datetime.now() - start_time)) #start_time = datetime.datetime.now() if not isUserOnly: bingles = self.getBingles(neLat, neLng, swLat, swLng) elif isUserOnly == 'true': bingles = self.getBinglesForCurrentUser() else: bingles = self.getBingles(neLat, neLng, swLat, swLng) #logging.info("getting bingles = " + str(datetime.datetime.now() - start_time)) #start_time = datetime.datetime.now() list = [] for aBingle in bingles: list.append(getBingleAsSimplePythonObject(aBingle)) #logging.info("bingles to simple python = " + str(datetime.datetime.now() - start_time)) #start_time = datetime.datetime.now() ##logging.info("found bingles count = " + str(len(list))) data = simplejson.dumps(list,indent=4) #logging.info('generated JSON: ' + data) #logging.info("simple python to json str = " + str(datetime.datetime.now() - start_time)) #self.response.headers['Content-Type'] = 'text/plain' self.response.headers['Content-Length'] = len(data) self.response.out.write(data) def getBingles(self, neLat, neLng, swLat, swLng): fneLat = float(neLat) fneLng = float(neLng) fswLat = float(swLat) fswLng = float(swLng) start_time = datetime.datetime.now() res = [] splitBounds = getSplitBounds(fneLat, fneLng, fswLat, fswLng) lengthSquared = getLengthSquaredOfSplitBounds(splitBounds) #logging.info("length squared = " + str(lengthSquared)) #logging.info(" getting split bounds = " + str(datetime.datetime.now() - start_time)) #logging.info('no of split bounds = '+str(len(splitBounds))) for sb in splitBounds: ineLat, ineLng, iswLat, iswLng = sb #logging.info(str(sb)) neGeoHash = Geohash((ineLat,ineLng)) swGeoHash = Geohash((iswLat,iswLng)) if self.__isLowRes: #q = BikeBingleLowRes.all() q = getQueryForLengthSquared(lengthSquared) else: q = BikeBingle.all() q.filter("geoHash <", str(neGeoHash)) q.filter("geoHash >", str(swGeoHash)) greetings = q.fetch(500) #logging.info('no found from db = '+str(len(greetings))) res = res + greetings #for aBingle in greetings: # #if (aBingle.position.lat < ineLat) & # (aBingle.position.lat > iswLat) & # (aBingle.position.lon < ineLng) & (aBingle.position.lon > iswLng): # res.append(aBingle) #logging.info('no found from db after strip = '+str(len(res))) return res def getBinglesForCurrentUser(self): user = users.get_current_user() if not user: return [] q = BikeBingle.all() q.filter("enteredBy =", user) q.order("enteredOn") res = q.fetch(500) return res def getBingleAsSimplePythonObject(aBingle): if aBingle.type == -2: bingleData = {'id': aBingle.key().id(), 'position': {'lat':aBingle.position.lat,'lng':aBingle.position.lon}, 'type':aBingle.type } return bingleData else: #userEmail = aBingle.enteredBy.email() #userNickName = aBingle.enteredBy.nickname() #TODO - figure out what I was meant to do with this #userEmail = '' #userNickName = '' bingleData = {'id': aBingle.key().id(), 'description': str(aBingle.description), 'occuredOn': str(aBingle.occuredOn), 'enteredOn': str(aBingle.enteredOn), 'position': {'lat':aBingle.position.lat,'lng':aBingle.position.lon}, #'enteredBy': {'name':userNickName,'email':userEmail}, 'injuryIndex': aBingle.injuryIndex, 'type':aBingle.type, 'link':str(aBingle.link) } return bingleData class LoggedInUser(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: logging.info(user.email() + ' logged in') self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(user.nickname() + ' ' + user.email()) else: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('') class LoginPage(webapp.RequestHandler): def get(self): user = users.get_current_user() tabName = self.request.get("tabname") if not tabName: tabName = 'add' if user: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(user.nickname() + ' ' + user.email() + ' isLoggedIn') else: o = urlparse(self.request.uri) rootUrl = o[0] + "://" + o[1] + "/" queryBit = "?tab=" + tabName self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(users.create_login_url(rootUrl + queryBit)) #self.redirect(users.create_login_url(self.request.uri)) class LogoutPage(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: self.redirect(users.create_logout_url(self.request.uri)) else: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('You are not logged in '); class Cleanup(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: if users.is_current_user_admin(): #self.__doCleanup() self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('remember lock, you removed this functionality to prevent accidents'); else: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('you are not an administrator'); else: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('no user logged in'); def __doCleanup(self): logging.info('doing cleanup') res = CounterShard.all().fetch(500) if len(res) != 0: db.delete(res) else: logging.info('counter shard empty') res = BikeBingleLowRes.all().fetch(500) if len(res) != 0: db.delete(res) else: logging.info('BikeBingleLowRes empty') res = BikeBingleMediumRes.all().fetch(500) if len(res) != 0: db.delete(res) else: logging.info('BikeBingleMediumRes empty') res = BikeBingleHighRes.all().fetch(500) if len(res) != 0: db.delete(res) else: logging.info('BikeBingleHighRes empty') res = BikeBingle.all().fetch(500) if len(res) != 0: db.delete(res) else: logging.info('BikeBingle empty') logging.info('cleanup complete') self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('cleanup complete'); application = webapp.WSGIApplication( [('/server/',test1), ('/getbingles/',GetBingles), ('/getlatestbingles/',GetLatestBingles), ('/addbingle/',AddBingle), ('/deletebingle/',DeleteBingle), ('/getbinglecount/',GetBingleCount), ('/login/',LoginPage), ('/logout/',LogoutPage), ('/cleanup/',Cleanup), ('/user/',LoggedInUser)], debug=True ) def main(): run_wsgi_app(application) #wsgiref.handlers.CGIHandler.run(application) if __name__ == "__main__": main()
{'content_hash': '77a695e2471195033d44797c20c5ab18', 'timestamp': '', 'source': 'github', 'line_count': 554, 'max_line_length': 132, 'avg_line_length': 35.691335740072205, 'alnum_prop': 0.5119607545643049, 'repo_name': 'lachlanhurst/BikeBingle', 'id': '2d51e1bd753df5afb83b300916cbb854d24a2378', 'size': '19773', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ServerMain.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '70793'}, {'name': 'Java', 'bytes': '184075'}, {'name': 'JavaScript', 'bytes': '10'}, {'name': 'Python', 'bytes': '31472'}]}
'use strict'; var tap = require('tap'); var test = tap.test; var util = require('util'); test('proper exit on uncaughtException', {skip: true}, function(t) { process.on('uncaughtException', function(err) { if (err.message === 'oops') { //console.log("ok got expected message: %s", err.message); t.pass(util.format("ok got expected message: %s", err.message)); } else { throw err; } }); var cls = require('../../index.js'); var ns = cls.createNamespace('x'); ns.run(function() { throw new Error('oops'); }); });
{'content_hash': '24c2235617b988df3d2a81668064ca6f', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 70, 'avg_line_length': 25.59090909090909, 'alnum_prop': 0.5914742451154529, 'repo_name': 'Jeff-Lewis/cls-hooked', 'id': 'c1bd769de9e5cf29afc811ce44206377751270a9', 'size': '563', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/tap/proper-exit.tap.js', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'JavaScript', 'bytes': '125102'}]}
<?php namespace Demagog\WebBundle\Response; use Symfony\Component\HttpFoundation\Response; class JSONResponse extends Response { public function __construct($payload) { parent::__construct(json_encode($payload), 200, [ 'Content-Type' => 'application/json' ]); } }
{'content_hash': '5a4920f38caf89669cc3c31276e4c444', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 57, 'avg_line_length': 20.466666666666665, 'alnum_prop': 0.6514657980456026, 'repo_name': 'Demagog2/Demagog.cz', 'id': '4821e76ae8cbb3f63a162bc34dcc08aa606ce6c8', 'size': '307', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Demagog/WebBundle/Response/JSONResponse.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '179013'}]}
"use strict"; define(['./DvtToolkit', './DvtSubcomponent'], function(dvt) { // Internal use only. All APIs and functionality are subject to change at any time. // Map the D namespace to dvt, which is used to provide access across partitions. var D = dvt; /** * The base class for tree components. * @extends {DvtBaseComponent} * @class The base class for tree components. * @constructor * @export */ var DvtBaseTreeView = function() {}; DvtObj.createSubclass(DvtBaseTreeView, DvtBaseComponent, 'DvtBaseTreeView'); /** * Initializes the tree view. * @param {DvtContext} context The rendering context. * @param {object} callback The function that should be called to dispatch component events. * @param {object} callbackObj The object context for the callback function * @protected */ DvtBaseTreeView.prototype.Init = function(context, callback, callbackObj) { DvtBaseTreeView.superclass.Init.call(this, context, callback, callbackObj); // Create the event handler and add event listeners this._eventHandler = this.CreateEventManager(this, context, this.__dispatchEvent, this); this._eventHandler.addListeners(this); // Drag and drop support this._dragSource = new DvtDragSource(context); this._dropTarget = new DvtBaseTreeDropTarget(this); this._eventHandler.setDragSource(this._dragSource); /** * Field used to store the legend displayable during render. * @private */ this._legend = null; // boolean to indicate whether or not this view has current keyboard focus this._hasFocus = false; // String to indicate the id of the node that should get keyboard focus // Used when an event causes the view to re-render or animate and we want to re-set the keyboard focus to a // non-default node, for example when we // 1. drill up (set keyboard focus to the node that was the previous, drilled-in root of the treemap) // 2. restore a treemap after isolating a node (set focus to the node that was previously isolated) // 3. expand or collapse a sunburst node (set focus to the node that was expanded/collapsed) this._navigableIdToFocus = null; }; /** * @override */ DvtBaseTreeView.prototype.SetOptions = function(options) { if (options) { this.Options = this.Defaults.calcOptions(options); // Disable animation for canvas and xml if (!DvtAgent.isEnvironmentBrowser()) { this.Options['animationOnDisplay'] = 'none'; this.Options['animationOnDataChange'] = 'none'; } } else if (!this.Options) this.Options = this.GetDefaults(); }; /** * Renders the component using the specified options. If no options is supplied to a component * that has already been rendered, this function will rerender the component with the * specified size. * @param {object} options The new options object. * @param {number} width The width of the component. * @param {number} height The height of the component. * @export */ DvtBaseTreeView.prototype.render = function(options, width, height) { // Update if a new options object has been provided or initialize with defaults if needed. var bNewOptions = (options || !this.Options); this.SetOptions(options); // Process the options object var root = this._processNodes(); this.ApplyParsedProperties({root: root}); // Update the width and height if provided if (!isNaN(width) && !isNaN(height)) { this.Width = width; this.Height = height; } // Hide any currently shown tooltips if (this._eventHandler) this._eventHandler.hideTooltip(); // Relayout the component (for resize or new data) var availSpace = new DvtRectangle(0, 0, this.Width, this.Height); this.Layout(availSpace); // Create a new container and render the component into it var container = new DvtContainer(this.getCtx()); this.addChild(container); // content facet: create afContext if (this._templates) { this._afContext = new DvtAfContext(this.getCtx(), this._eventHandler); //remove any components that don't fit in the tree node this._afContext.setRmIfNotFit(true); } this.Render(container, availSpace); // Animation Support // Stop any animation in progress if (this.Animation) { this.AnimationStopped = true; this.Animation.stop(); } // Construct the new animation playable var animationOnDataChange = this.getOptions()['animationOnDataChange']; var bounds = new DvtRectangle(0, 0, this.Width, this.Height); var bBlackBoxUpdate = false; // true if this is a black box update animation if (!this._container) { this.Animation = this.GetDisplayAnimation(container, bounds); } else if (animationOnDataChange && bNewOptions) { // AnimationOnDataChange if (DvtBlackBoxAnimationHandler.isSupported(animationOnDataChange)) { // Black Box Animation this.Animation = DvtBlackBoxAnimationHandler.getCombinedAnimation(this.getCtx(), animationOnDataChange, this._container, container, bounds, this.AnimationDuration); bBlackBoxUpdate = true; } else if (this._oldRoot && animationOnDataChange == 'auto') { // Data Change Animation // Create the animation handler, calc, and play the animation this._deleteContainer = this.GetDeleteContainer(); this.addChild(this._deleteContainer); var ah = new DvtBaseTreeAnimationHandler(this.getCtx(), this._deleteContainer); ah.animate(this._oldRoot, this._root, this._oldAncestors, this._ancestors); this.Animation = ah.getAnimation(true); } } // Clear out the old info, not needed anymore this._oldRoot = null; this._oldAncestors = null; // If an animation was created, play it if (this.Animation) { // Disable event listeners temporarily this._eventHandler.removeListeners(this); // Start the animation this.Animation.setOnEnd(this.OnAnimationEnd, this); this.Animation.play(); } // Clean up the old container. If doing black box animation, store a pointer and clean // up after animation is complete. Otherwise, remove immediately. if (bBlackBoxUpdate) { this._oldContainer = this._container; } else if (this._container) { // Not black box animation, so clean up the old contents this.removeChild(this._container); } // Update the pointer to the new container this._container = container; // Selection Support if (bNewOptions) { // Update the selection manager with the initial selections. This must be done after // the shapes are created to apply the selection effects. this._processInitialSelections(); } else this.ReselectNodes(); // Resize or Rerender: Reselect the nodes using the selection handler's state // Update the event manager with the initial focus this._processInitialFocus(!this.Animation); // Process the highlightedCategories. We'll also do this in the animation end listener to avoid conflicts with insert // animations. if (!this.Animation) this._processInitialHighlighting(); this.UpdateAriaAttributes(); }; /** * Parses the xml and returns the root node. * @param {string} xmlString The string to be parsed * @return {object} An object containing the parsed properties. * @protected */ DvtBaseTreeView.prototype.Parse = function(xmlString) { // subclasses should override return null; }; /** * Performs layout for the component. * @param {DvtRect} availSpace The rectangle within which to perform layout. * @protected */ DvtBaseTreeView.prototype.Layout = function(availSpace) { // subclasses should override }; /** * Renders the component. * @param {DvtContainer} container The container to render within. * @param {DvtRectangle} bounds The bounds of the node area. * @protected */ DvtBaseTreeView.prototype.Render = function(container, bounds) { // subclasses should override }; /** * Renders the background. * @param {DvtContainer} container The container to render within. * @param {string} defaultStyle The default style string * @protected */ DvtBaseTreeView.prototype.RenderBackground = function(container, defaultStyle) { // Render an invisible fill for eventing var background = new DvtRect(this.getCtx(), 0, 0, this.Width, this.Height); background.setInvisibleFill(); container.addChild(background); }; /** * Lays out the breadcrumbs and updates the available space. * @param {DvtRect} availSpace The rectangle within which to perform layout. * @protected */ DvtBaseTreeView.prototype.LayoutBreadcrumbs = function(availSpace) { if (this._ancestors.length > 0) { var rootLabel = this._root ? this._root.getLabel() : null; if (this._breadcrumbs) this._eventHandler.removeComponentKeyboardHandler(this._breadcrumbs.getEventManager()); this._breadcrumbs = DvtTreeBreadcrumbsRenderer.render(this, availSpace, this._ancestors, rootLabel); this._eventHandler.addComponentKeyboardHandlerAt(this._breadcrumbs.getEventManager(), 0); } else { if (this._breadcrumbs) this._eventHandler.removeComponentKeyboardHandler(this._breadcrumbs.getEventManager()); this._breadcrumbs = null; } }; /** * Renders the breadcrumbs. * @param {DvtContainer} container The container to render within. * @protected */ DvtBaseTreeView.prototype.RenderBreadcrumbs = function(container) { // The breadcrumbs are actually already rendered in _layoutBreadcrumbs, so just add it to the tree here. if (this._breadcrumbs) { container.addChild(this._breadcrumbs); } }; /** * Lays out the legend component and updates the available space. * @param {DvtRect} availSpace The rectangle within which to perform layout. * @protected */ DvtBaseTreeView.prototype.LayoutLegend = function(availSpace) { this._legend = DvtTreeLegendRenderer.render(this, availSpace, this._legendSource); }; /** * Renders the legend. * @param {DvtContainer} container The container to render within. * @protected */ DvtBaseTreeView.prototype.RenderLegend = function(container) { // The legend is actually already rendered in _layoutLegend, so just add it to the tree here. if (this._legend) { container.addChild(this._legend); // Clear the pointer, since we don't need it anymore this._legend = null; } }; /** * Renders the empty text message, centered in the available space. * @param {DvtContainer} container The container to render within. * @protected */ DvtBaseTreeView.prototype.RenderEmptyText = function(container) { var options = this.getOptions(); var emptyText = options['emptyText']; if (!emptyText) emptyText = DvtBundle.getTranslation(options, 'labelNoData', DvtBundle.UTIL_PREFIX, 'NO_DATA'); DvtTextUtils.renderEmptyText(container, emptyText, new DvtRectangle(0, 0, this.Width, this.Height), this.__getEventManager()); }; /** * Checks whether the component has valid data. * @return {boolean} True if the component has valid data. * @protected */ DvtBaseTreeView.prototype.HasValidData = function() { return (this._root && this._root.getSize() > 0); }; /** * Returns the animation to use on initial display of this component. * @param {DvtContainer} container The container to render within. * @param {DvtRectangle} bounds The bounds of the node area. * @return {DvtBaseAnimation} The initial display animation. * @protected */ DvtBaseTreeView.prototype.GetDisplayAnimation = function(container, bounds) { var animationOnDisplay = this.getOptions()['animationOnDisplay']; if (DvtBlackBoxAnimationHandler.isSupported(animationOnDisplay)) return DvtBlackBoxAnimationHandler.getInAnimation(this.getCtx(), animationOnDisplay, container, bounds, this.AnimationDuration); else return null; }; /** * Hook for cleaning up animation behavior at the end of the animation. * @protected */ DvtBaseTreeView.prototype.OnAnimationEnd = function() { // Remove the container containing the delete animations if (this._deleteContainer) { this.removeChild(this._deleteContainer); this._deleteContainer = null; } // Clean up the old container used by black box updates if (this._oldContainer) { this.removeChild(this._oldContainer); this._oldContainer = null; } // Reset the animation stopped flag this.AnimationStopped = false; // Remove the animation reference this.Animation = null; // Restore event listeners this._eventHandler.addListeners(this); // Restore visual effects on node with keyboard focus this._processInitialFocus(true); // Process the highlightedCategories this._processInitialHighlighting(); }; /** * Creates a container that can be used for storing delete animation content. * @return {DvtContainer} * @protected */ DvtBaseTreeView.prototype.GetDeleteContainer = function() { return new DvtContainer(this.getCtx()); }; /** * Returns a keyboard handler that can be used by the view's event manager * @param {DvtEventManager} manager The owning event manager * @return {DvtKeyboardHandler} * @protected */ DvtBaseTreeView.prototype.CreateKeyboardHandler = function(manager) { return new DvtBaseTreeKeyboardHandler(manager); }; /** * Returns an event manager that will handle events on this view * @param {DvtContainer} view * @param {DvtContext} context * @param {object} callback The function that should be called to dispatch component events. * @param {object} callbackObj The object context for the callback function * @return {DvtEventManager} * @protected */ DvtBaseTreeView.prototype.CreateEventManager = function(view, context, callback, callbackObj) { return new DvtBaseTreeEventManager(view, context, callback, callbackObj); }; /** * Returns the node that should receive initial keyboard focus when the view first gets focus * @param {DvtBaseTreeNode} root The node that should receive initial keyboard focus * @return {DvtBaseTreeNode} * @protected */ DvtBaseTreeView.prototype.GetInitialFocusedItem = function(root) { return root; }; /** * @override * @export */ DvtBaseTreeView.prototype.highlight = function(categories) { // Update the options this.getOptions()['highlightedCategories'] = DvtJSONUtils.clone(categories); // Perform the highlighting DvtCategoryRolloverHandler.highlight(categories, DvtBaseTreeUtils.getAllNodes(this._root), this.getOptions()['highlightMatch'] == 'any'); }; /** * @override * @export */ DvtBaseTreeView.prototype.select = function(selection) { // Update the options var options = this.getOptions(); options['selection'] = DvtJSONUtils.clone(selection); // Perform the selection if (this._selectionHandler) { var targets = DvtBaseTreeUtils.getAllNodes(this._root); this._selectionHandler.processInitialSelections(options['selection'], targets); } }; /** * @override */ DvtBaseTreeView.prototype.__getEventManager = function() { return this._eventHandler; }; /** * Returns the maximum depth of the tree. * @return {number} The maximum depth of the tree. */ DvtBaseTreeView.prototype.__getMaxDepth = function() { return this._maxDepth; }; /** * Returns the node count of the tree. * @return {number} The node count of the tree. */ DvtBaseTreeView.prototype.__getNodeCount = function() { return this._nodeCount; }; /** * Applies the parsed properties to this component. * @param {object} props An object containing the parsed properties for this component. * @protected */ DvtBaseTreeView.prototype.ApplyParsedProperties = function(props) { var options = this.getOptions(); // Save the old info for animation support this._oldRoot = this._root; this._oldAncestors = this._ancestors; // Save the parsed properties this._root = props.root; this._ancestors = options['_ancestors'] ? options['_ancestors'] : []; this._nodeCount = this._root ? DvtBaseTreeUtils.calcNodeCount(this._root) : 0; this._maxDepth = this._root ? DvtBaseTreeUtils.calcMaxDepth(this._root, 0) : 0; // TODO HZHANG: This uses the weird client side value in seconds this.AnimationDuration = DvtStyleUtils.getTimeMilliseconds(options['animationDuration']) / 1000; this._styles = props.styles ? props.styles : {}; // Selection Support if (options['selectionMode'] == 'none') this._nodeSelection = null; else if (options['selectionMode'] == 'single') this._nodeSelection = DvtSelectionHandler.TYPE_SINGLE; else this._nodeSelection = DvtSelectionHandler.TYPE_MULTIPLE; if (this._nodeSelection) { this._selectionHandler = new DvtSelectionHandler(this._nodeSelection); this._initialSelection = options['selection']; } else this._selectionHandler = null; // Event Handler delegates to other handlers this._eventHandler.setSelectionHandler(this._selectionHandler); // Keyboard Support this._eventHandler.setKeyboardHandler(this.CreateKeyboardHandler(this._eventHandler)); // Attribute Groups and Legend Support this._legendSource = null; this._attrGroups = []; if (options['attributeGroups']) { var nodes = DvtBaseTreeUtils.getAllNodes(this._root); for (var i = 0; i < options['attributeGroups'].length; i++) { var attrGroup = options['attributeGroups'][i]; var agObj = null; if (attrGroup['attributeType'] == 'continuous') { DvtBaseTreeUtils.calcContinuousAttrGroupsExtents(attrGroup, nodes); agObj = new DvtContinuousAttrGroups(attrGroup['min'], attrGroup['max'], attrGroup['minLabel'], attrGroup['maxLabel'], attrGroup['colors']); } else { // discrete agObj = new DvtDiscreteAttrGroups(); for (var groupIndex = 0; groupIndex < attrGroup['groups'].length; groupIndex++) { var group = attrGroup['groups'][groupIndex]; agObj.add(group['id'], group['label'], {color: group['color'], pattern: group['pattern']}); } } this._attrGroups.push({attrGroups: agObj, stampId: attrGroup['S'], id: attrGroup['id']}); // If source wasn't specified, use the first attributeGroups. In ADF no legend unless explicitly specified. if (!options['_adf'] && !options['_legendSource'] && i == 0) this._legendSource = agObj; else if (options['_legendSource'] && options['_legendSource'] == attrGroup['id']) this._legendSource = agObj; } // For continuous attribute groups sent from server, evaluate to get the colors DvtBaseTreeUtils.processContinuousAttrGroups(this._attrGroups, nodes); } // ADF Context Menus var menus = options['_contextMenus']; if (menus && menus.length > 0) { var contextMenuHandler = new DvtContextMenuHandler(this.getCtx(), menus); this._eventHandler.setContextMenuHandler(contextMenuHandler); } // ADF Templates for Content Facet var templates = options['_templates']; if (templates) { this._templates = {}; // The templates object is a mapping from stampId to template definition for (var templateKey in templates) { var afComponent = DvtAfComponentFactory.parseJsonElement(templates[templateKey]); this._templates[templateKey] = afComponent; } } }; /** * Reselects the selected nodes after a re-render. * @protected */ DvtBaseTreeView.prototype.ReselectNodes = function() { var selectedNodes = this._selectionHandler ? this._selectionHandler.getSelection() : new Array(); for (var i = 0; i < selectedNodes.length; i++) selectedNodes[i].setSelected(true); }; /** * Update the selection handler with the initial selections. * @private */ DvtBaseTreeView.prototype._processInitialSelections = function() { if (this._selectionHandler && this._initialSelection) { var targets = DvtBaseTreeUtils.getAllNodes(this._root); this._selectionHandler.processInitialSelections(this._initialSelection, targets); this._initialSelection = null; } }; /** * Update the displayables with the initial highlighting. * @private */ DvtBaseTreeView.prototype._processInitialHighlighting = function() { var highlightedCategories = this.getOptions()['highlightedCategories']; if (highlightedCategories && highlightedCategories.length > 0) this.highlight(highlightedCategories); }; /** * Update the event manager with the initial focused item * @param {Boolean} applyVisualEffects True if we want to apply visual effects to indicate which node has * keyboard focus. * @private */ DvtBaseTreeView.prototype._processInitialFocus = function(applyVisualEffects) { var initialFocus = null; var id = this.__getNavigableIdToFocus(); if (id) { initialFocus = DvtBaseTreeNode.getNodeById(this._root, id); this._eventHandler.setFocus(initialFocus); } if (applyVisualEffects) { // if we are applying visual effects in response to an event that caused a re-render or animation, and this // event specified a non-default node to set keyboard focus on, clear that value now that we've used it this.__setNavigableIdToFocus(null); } if (!initialFocus) { // set the item that has initial keyboard focus to a default if none was previously defined initialFocus = this.GetInitialFocusedItem(this._root); this._eventHandler.setFocus(initialFocus); } // have the event manager apply any needed visual effects // however, do this only if we are not animating so as to prevent the focus visual effect // from appearing during the duration of the animation if (applyVisualEffects) this.setFocused(this.isFocused()); }; /** * Update the visual effects on view when it receives or loses keyboard focus * * @param {boolean} isFocused */ DvtBaseTreeView.prototype.setFocused = function(isFocused) { this._hasFocus = isFocused; this._eventHandler.setFocused(isFocused); }; /** * Returns true if the view currently has keyboard focus * @return {boolean} */ DvtBaseTreeView.prototype.isFocused = function() { return this._hasFocus; }; /** * Returns the animation duration, in milliseconds. * @return {number} */ DvtBaseTreeView.prototype.__getAnimationDuration = function() { return this.AnimationDuration; }; /** * Returns the content facet template for the given stamp id. * @param {string} stampId * @return {object} */ DvtBaseTreeView.prototype.__getTemplate = function(stampId) { return this._templates ? this._templates[stampId] : null; }; /** * Returns the afComponent context instance. * @return {DvtAfContext} */ DvtBaseTreeView.prototype.__getAfContext = function() { return this._afContext; }; /** * Returns the node under the specified coordinates. * @param {number} x * @param {number} y * @return {DvtBaseTreeNode} */ DvtBaseTreeView.prototype.__getNodeUnderPoint = function(x, y) { return this._root.getNodeUnderPoint(x, y); }; /** * Returns the clientId of the drag source owner if dragging is supported. * @param {array} clientIds * @return {string} */ DvtBaseTreeView.prototype.__isDragAvailable = function(clientIds) { // Drag and drop supported when selection is enabled, only 1 drag source if (this._selectionHandler) return clientIds[0]; else return null; }; /** * Returns the row keys for the current drag. * @param {DvtBaseTreeNode} node The node where the drag was initiated. * @return {array} The row keys for the current drag. */ DvtBaseTreeView.prototype.__getDragTransferable = function(node) { // Select the node if not already selected if (!node.isSelected()) { this._selectionHandler.processClick(node, false); this._eventHandler.fireSelectionEvent(); } // Gather the rowKeys for the selected objects var rowKeys = []; var selection = this._selectionHandler.getSelection(); for (var i = 0; i < selection.length; i++) { rowKeys.push(selection[i].getId()); } return rowKeys; }; /** * Returns the displayables to use for drag feedback for the current drag. * @return {array} The displayables for the current drag. */ DvtBaseTreeView.prototype.__getDragFeedback = function() { // This is called after __getDragTransferable, so the selection has been updated already. // Gather the displayables for the selected objects var displayables = []; var selection = this._selectionHandler.getSelection(); for (var i = 0; i < selection.length; i++) { displayables.push(selection[i].getDisplayable()); } return displayables; }; /** * Displays drop site feedback for the specified node. * @param {DvtBaseTreeNode} node The node for which to show drop feedback, or null to remove drop feedback. * @return {DvtDisplayable} The drop site feedback, if any. */ DvtBaseTreeView.prototype.__showDropSiteFeedback = function(node) { // Remove any existing drop site feedback if (this._dropSiteFeedback) { this.removeChild(this._dropSiteFeedback); this._dropSiteFeedback = null; } // Create feedback for the node if (node) { this._dropSiteFeedback = node.getDropSiteFeedback(); if (this._dropSiteFeedback) { var styleDefaults = this.getOptions()['styleDefaults']; this._dropSiteFeedback.setSolidFill(styleDefaults['_dropSiteFillColor'], styleDefaults['_dropSiteOpacity']); this._dropSiteFeedback.setSolidStroke(styleDefaults['_dropSiteBorderColor']); this.addChild(this._dropSiteFeedback); } } return this._dropSiteFeedback; }; /** * Processes a breadcrumb drill event. * @param {DvtBreadcrumbsDrillEvent} event */ DvtBaseTreeView.prototype.__processBreadcrumbsEvent = function(event) { if (event instanceof DvtBreadcrumbsDrillEvent) this.__drill(event.getId(), false); }; /** * Performs a drill on the specified node. * @param {string} id * @param {boolean} bDrillUp True if this is a drill up operation. */ DvtBaseTreeView.prototype.__drill = function(id, bDrillUp) { if (bDrillUp && this._root && id == this._root.getId() && this._ancestors.length > 0) { // after the drill up completes, set keyboard focus on the node that was the // root of the previously drilled-down view this.__setNavigableIdToFocus(id); // Drill up only supported on the root node this.__dispatchEvent(new DvtDrillReplaceEvent(this._ancestors[0].id)); } else if (!bDrillUp) // Fire the event this.__dispatchEvent(new DvtDrillReplaceEvent(id)); // Hide any tooltips being shown this.getCtx().getTooltipManager().hideTooltip(); }; /** * Returns the logical object corresponding to the physical target * @param {Object} target * @return {Object} */ DvtBaseTreeView.prototype.getLogicalObject = function(target) { return this._eventHandler.GetLogicalObject(target); }; /** * @return {DvtBaseTreeNode} the root tree node. */ DvtBaseTreeView.prototype.getRootNode = function() { return this._root; }; /** * Returns the id of the node that should get keyboard focus, if the default node should not receive focus. * Used when an event causes the view to re-render or animate and we want to set the keyboard focus * to a non-default node. * * @return {String} the id of the node that should receive keyboard focus */ DvtBaseTreeView.prototype.__getNavigableIdToFocus = function() { return this._navigableIdToFocus; }; /** * Sets the id of the node that should get keyboard focus, if the default node should not receive focus. * Used when an event causes the view to re-render or animate and we want to set the keyboard focus * to a non-default node. * * @param {String} id The id of the node that should receive keyboard focus */ DvtBaseTreeView.prototype.__setNavigableIdToFocus = function(id) { this._navigableIdToFocus = id; }; /** * @return {String} whether nodeSelection is multiple, single, or null. */ DvtBaseTreeView.prototype.__getNodeSelection = function() { return this._nodeSelection; }; /** * Creates a node for this view. Subclasses must override. * @param {object} nodeOptions The options for the node. * @return {DvtBaseTreeNode} * @protected */ DvtBaseTreeView.prototype.CreateNode = function(nodeOptions) { // subclasses must override return null; }; /** * Helper function to return the bundle prefix for this component. * @return {string} */ DvtBaseTreeView.prototype.getBundlePrefix = function() { // subclasses must override return null; }; /** * Returns the automation object for this treeView * @return {DvtAutomation} The automation object * @export */ DvtBaseTreeView.prototype.getAutomation = function() { return new DvtTreeAutomation(this); }; /** * Returns the breadcrumbs object for this treeView * Used by automation APIs * @return {DvtBreadcrumbs} The breadcrumbs object */ DvtBaseTreeView.prototype.getBreadcrumbs = function() { return this._breadcrumbs; }; /** * Recursively creates and returns the root layer nodes based on the options object. Creates an artificial node if * needed for multi-rooted trees. * @return {DvtBaseTreeNode} * @private */ DvtBaseTreeView.prototype._processNodes = function() { var options = this.getOptions(); if (options['nodes'] == null) return null; // Create each of the root level nodes var rootNodes = []; // create a boolean map of hidden categories for better performance var hiddenCategories = DvtArrayUtils.createBooleanMap(options['hiddenCategories']); for (i = 0; i < options['nodes'].length; i++) { var nodeOptions = options['nodes'][i]; // Store the index for automation nodeOptions['_index'] = i; // Recursively process the node var rootNode = this._processNode(hiddenCategories, nodeOptions); if (rootNode) rootNodes.push(rootNode); } // Ensure that there's a single root, creating an artificial one if needed if (rootNodes.length == 1) return rootNodes[0]; else { // Calculate the sum of the child sizes var size = 0; for (var i = 0; i < rootNodes.length; i++) { size += rootNodes[i].getSize(); } // Create the actual node and set the children var props = {'value': size, bArtificialRoot: true}; var artificialRoot = this.CreateNode(props); artificialRoot.setChildNodes(rootNodes); return artificialRoot; } }; /** * Recursively creates and returns the node based on the options object. * @param {object} hiddenCategories The boolean map of hidden categories. * @param {object} nodeOptions The options for the node to process. * @return {DvtBaseTreeNode} * @private */ DvtBaseTreeView.prototype._processNode = function(hiddenCategories, nodeOptions) { // Don't create if node is hidden if (DvtBaseTreeUtils.isHiddenNode(hiddenCategories, nodeOptions)) return null; // Create the node var node = this.CreateNode(nodeOptions); // Create child nodes only if this node is expanded if (node.isDisclosed()) { // Recurse and build the child nodes var childNodes = []; var childOptions = nodeOptions['nodes'] ? nodeOptions['nodes'] : []; for (var childIndex = 0; childIndex < childOptions.length; childIndex++) { var childNodeOptions = childOptions[childIndex]; childNodeOptions['_index'] = childIndex; var childNode = this._processNode(hiddenCategories, childNodeOptions); if (childNode) childNodes.push(childNode); } node.setChildNodes(childNodes); } return node; }; /** * Annotates nodes with aria flowto properties for VoiceOver navigation * @param {DvtBaseTreeNode} root The root node * @protected */ DvtBaseTreeView.prototype.UpdateAriaNavigation = function(root) { // VoiceOver workaround for bug 20745395 if (DvtAgent.isTouchDevice() || DvtAgent.isEnvironmentTest()) { var nodes = DvtBaseTreeUtils.getAllVisibleNodes(root); for (var i = 0; i < nodes.length - 1; i++) { // Set the aria flowto property of the current node to the next node's id var id = this.getId() + (nodes[i + 1].getId() ? nodes[i + 1].getId() : nodes[i + 1].getLabel()); // VoiceOver doesn't work well if there are spaces in the id so remove all spaces first id = id.replace(/\s+/g, ''); nodes[i + 1].getDisplayable().setId(id, true); nodes[i].getDisplayable().setAriaProperty('flowto', id); } } }; // APIs called by the ADF Faces drag source for DvtBaseTreeView /** * If this object supports drag, returns the client id of the drag component. * Otherwise returns null. * @param mouseX the x coordinate of the mouse * @param mouseY the x coordinate of the mouse * @param clientIds the array of client ids of the valid drag components */ DvtBaseTreeView.prototype.isDragAvailable = function(mouseX, mouseY, clientIds) { return this._dragSource.isDragAvailable(clientIds); }; /** * Returns the transferable object for a drag initiated at these coordinates. */ DvtBaseTreeView.prototype.getDragTransferable = function(mouseX, mouseY) { return this._dragSource.getDragTransferable(mouseX, mouseY); }; /** * Returns the feedback for the drag operation. */ DvtBaseTreeView.prototype.getDragOverFeedback = function(mouseX, mouseY) { return this._dragSource.getDragOverFeedback(mouseX, mouseY); }; /** * Returns an Object containing the drag context info. */ DvtBaseTreeView.prototype.getDragContext = function(mouseX, mouseY) { return this._dragSource.getDragContext(mouseX, mouseY); }; /** * Returns the offset to use for the drag feedback. This positions the drag * feedback relative to the pointer. */ DvtBaseTreeView.prototype.getDragOffset = function(mouseX, mouseY) { return this._dragSource.getDragOffset(mouseX, mouseY); }; /** * Returns the offset from the mouse pointer where the drag is considered to be located. */ DvtBaseTreeView.prototype.getPointerOffset = function(xOffset, yOffset) { return this._dragSource.getPointerOffset(xOffset, yOffset); }; /** * Notifies the component that a drag started. */ DvtBaseTreeView.prototype.initiateDrag = function() { this._dragSource.initiateDrag(); }; /** * Clean up after the drag is completed. */ DvtBaseTreeView.prototype.dragDropEnd = function() { this._dragSource.dragDropEnd(); }; // APIs called by the ADF Faces drop target for DvtBaseTreeView /** * If a drop is possible at these mouse coordinates, returns the client id * of the drop component. Returns null if drop is not possible. */ DvtBaseTreeView.prototype.acceptDrag = function(mouseX, mouseY, clientIds) { return this._dropTarget.acceptDrag(mouseX, mouseY, clientIds); }; /** * Paints drop site feedback as a drag enters the drop site. */ DvtBaseTreeView.prototype.dragEnter = function() { this._dropTarget.dragEnter(); }; /** * Cleans up drop site feedback as a drag exits the drop site. */ DvtBaseTreeView.prototype.dragExit = function() { this._dropTarget.dragExit(); }; /** * Returns the object representing the drop site. This method is called when a valid * drop is performed. */ DvtBaseTreeView.prototype.getDropSite = function(mouseX, mouseY) { return this._dropTarget.getDropSite(mouseX, mouseY); }; /** * Animation handler for tree data objects. * @param {DvtContext} context The platform specific context object. * @param {DvtContainer} deleteContainer The container where deletes should be moved for animation. * @class DvtBaseTreeAnimationHandler * @constructor */ var DvtBaseTreeAnimationHandler = function(context, deleteContainer) { this.Init(context, deleteContainer); }; DvtObj.createSubclass(DvtBaseTreeAnimationHandler, DvtDataAnimationHandler, 'DvtBaseTreeAnimationHandler'); /** * Animates the tree component, with support for data changes and drilling. * @param {DvtBaseTreeNode} oldRoot The state of the tree before the animation. * @param {DvtBaseTreeNode} newRoot The state of the tree after the animation. * @param {array} oldAncestors The array of ancestors for the old root node. * @param {array} newAncestors The array of ancestors for the new root node. */ DvtBaseTreeAnimationHandler.prototype.animate = function(oldRoot, newRoot, oldAncestors, newAncestors) { this._bDrill = false; // true if this is a drilling animation this._oldRoot = oldRoot; this._oldAncestors = oldAncestors; // Determine whether this is a drill or data change animation if (DvtBaseTreeAnimationHandler._isAncestor(newAncestors, oldRoot) || DvtBaseTreeAnimationHandler._isAncestor(oldAncestors, newRoot)) { // Drilling this._bDrill = true; var oldList = oldRoot.getDescendantNodes(); var newList = newRoot.getDescendantNodes(); oldList.push(oldRoot); newList.push(newRoot); this.constructAnimation(oldList, newList); } else { // Data Change Animation this.constructAnimation([oldRoot], [newRoot]); } }; /** * Returns true if the current animation is for a drill operation. The nodes * will call this function and handle their animations differently. * @return {boolean} */ DvtBaseTreeAnimationHandler.prototype.isDrillAnimation = function() { return this._bDrill; }; /** * Returns true if the specified node was previously an ancestor of the old root. A value * of true indicates that an insert animation should not be performed on this node. * @param {DvtBaseTreeNode} node */ DvtBaseTreeAnimationHandler.prototype.isAncestorInsert = function(node) { if (this._bDrill) return this._oldRoot.getId() == node.getId() || DvtBaseTreeAnimationHandler._isAncestor(this._oldAncestors, node); else return false; }; /** * Returns true if the specified node is contained in the array of ancestors. * @param {array} ancestors The array of ancestors to search. * @param {DvtBaseTreeNode} node The node to search for. * @return {boolean} */ DvtBaseTreeAnimationHandler._isAncestor = function(ancestors, node) { if (!node || !ancestors) return false; // Iterate through the array and search for the node for (var i = 0; i < ancestors.length; i++) { if (ancestors[i]['id'] == node.getId()) return true; } // No match found return false; }; /** * Drop Target event handler for DvtBaseTreeView * @param {DvtBaseTreeView} view * @class DvtBaseTreeDropTarget * @extends {DvtDropTarget} * @constructor */ var DvtBaseTreeDropTarget = function(view) { this._view = view; }; DvtObj.createSubclass(DvtBaseTreeDropTarget, DvtDropTarget, 'DvtBaseTreeDropTarget'); /** * @override */ DvtBaseTreeDropTarget.prototype.acceptDrag = function(mouseX, mouseY, clientIds) { // If there is no node under the point, then don't accept the drag var node = this._view.__getNodeUnderPoint(mouseX, mouseY); if (!node) { this._view.__showDropSiteFeedback(null); return null; } else if (node != this._dropSite) { this._view.__showDropSiteFeedback(node); this._dropSite = node; } // Return the first clientId, since this component has only a single drag source return clientIds[0]; }; /** * @override */ DvtBaseTreeDropTarget.prototype.dragExit = function() { // Remove drop site feedback this._view.__showDropSiteFeedback(null); this._dropSite = null; }; /** * @override */ DvtBaseTreeDropTarget.prototype.getDropSite = function(mouseX, mouseY) { var node = this._view.__getNodeUnderPoint(mouseX, mouseY); if (node) return {clientRowKey: node.getId()}; else return null; }; /** * Event Manager for tree components. * @param {DvtBaseTreeView} view * @param {DvtContext} context * @param {function} callback A function that responds to component events. * @param {object} callbackObj The optional object instance that the callback function is defined on. * @constructor */ var DvtBaseTreeEventManager = function(view, context, callback, callbackObj) { this.Init(context, callback, callbackObj); this._view = view; }; DvtObj.createSubclass(DvtBaseTreeEventManager, DvtEventManager, 'DvtBaseTreeEventManager'); /** * Returns the owning tree component. * @return {DvtBaseTreeView} * @protected */ DvtBaseTreeEventManager.prototype.GetView = function() { return this._view; }; /** * @override */ DvtBaseTreeEventManager.prototype.OnDblClickInternal = function(event) { // Done if there is no object var obj = this.GetLogicalObject(event.target); if (!obj) return; this._processDrill(obj, event.shiftKey); }; /** * @override */ DvtBaseTreeEventManager.prototype.OnClick = function(event) { DvtBaseTreeEventManager.superclass.OnClick.call(this, event); // If the object is a DvtBaseTreePeer (for node labels), handle drilling var obj = this.GetLogicalObject(event.target); this._processNodeLabel(obj); }; /** * @override */ DvtBaseTreeEventManager.prototype.OnMouseOver = function(event) { DvtBaseTreeEventManager.superclass.OnMouseOver.call(this, event); // Additional mouse over support var obj = this.GetLogicalObject(event.target); if (!obj) return; if (obj.handleMouseOver) obj.handleMouseOver(); }; /** * @override */ DvtBaseTreeEventManager.prototype.OnMouseOut = function(event) { DvtBaseTreeEventManager.superclass.OnMouseOut.call(this, event); // Additional mouse out support var obj = this.GetLogicalObject(event.target); if (!obj) return; // Don't hide on mouseOut to object belonging to same node (expand button for example) if (obj.handleMouseOut) { var relatedObj = this.GetLogicalObject(event.relatedTarget); var relatedId = relatedObj && relatedObj.getId ? relatedObj.getId() : null; if ((obj.getId() == null) || (relatedId != obj.getId())) obj.handleMouseOut(); } }; /** * @override */ DvtBaseTreeEventManager.prototype.ProcessKeyboardEvent = function(event) { var eventConsumed = false; var keyCode = event.keyCode; var obj = this.getFocus(); // the item with current keyboard focus if (keyCode == DvtKeyboardEvent.ENTER && !event.ctrlKey) { // handle drill operations obj = this.getFocus(); if (obj.isDrillReplaceEnabled && obj.isDrillReplaceEnabled()) { // SHIFT+ENTER means drill up from the current root, even if the node with keyboard focus is not the current root if (event.shiftKey) obj = this._view.getRootNode(); // Delegate to the view to fire a drill event this._view.__drill(obj.getId(), event.shiftKey); } DvtEventManager.consumeEvent(event); eventConsumed = true; } else { eventConsumed = DvtBaseTreeEventManager.superclass.ProcessKeyboardEvent.call(this, event); } return eventConsumed; }; /** * @override */ DvtBaseTreeEventManager.prototype.HandleTouchClickInternal = function(event) { var targetObj = event.target; var obj = this.GetLogicalObject(targetObj); this._processNodeLabel(obj); if (this._currentHoverItem) { if (this._currentHoverItem != obj) { this._currentHoverItem.handleMouseOut(); this._currentHoverItem = null; } } if (obj && obj instanceof DvtBaseTreeNode) { if (this._currentHoverItem != obj) { this._currentHoverItem = obj; obj.handleMouseOver(); } } }; /** * @override */ DvtBaseTreeEventManager.prototype.HandleTouchDblClickInternal = function(event) { var targetObj = event.target; var obj = this.GetLogicalObject(targetObj); if (!obj) return; this._processDrill(obj, false); }; /** * Processes a click on a node label. * @param {DvtLogicalObject} obj The logical object that was the target of the event * @private */ DvtBaseTreeEventManager.prototype._processNodeLabel = function(obj) { if (obj && obj instanceof DvtBaseTreePeer && obj.isDrillable()) { // Delegate to the view to fire a drill event this._view.__drill(obj.getId(), false); } }; /** * Processes a drill on the specified object. * @param {DvtLogicalObject} obj The logical object that was the target of the event * @param {boolean} shiftKey True if the shift key was pressed. * @private */ DvtBaseTreeEventManager.prototype._processDrill = function(obj, shiftKey) { // Fire a drill event if drilling is enabled if (obj.isDrillReplaceEnabled && obj.isDrillReplaceEnabled()) { // Delegate to the view to fire a drill event this._view.__drill(obj.getId(), shiftKey); } }; /** * @override */ DvtBaseTreeEventManager.prototype.ProcessRolloverEvent = function(event, obj, bOver) { // Don't continue if not enabled var options = this._view.getOptions(); if (options['hoverBehavior'] != 'dim') return; // Compute the new highlighted categories and update the options var categories = obj.getCategories ? obj.getCategories() : []; options['highlightedCategories'] = bOver ? categories.slice() : null; // Fire the event to the rollover handler, who will fire to the component callback. var type = bOver ? DvtCategoryRolloverEvent.TYPE_OVER : DvtCategoryRolloverEvent.TYPE_OUT; var rolloverEvent = new DvtCategoryRolloverEvent(type, options['highlightedCategories']); var nodes = DvtBaseTreeUtils.getAllNodes(this.GetView().getRootNode()); var hoverBehaviorDelay = DvtStyleUtils.getTimeMilliseconds(options['hoverBehaviorDelay']); this.RolloverHandler.processEvent(rolloverEvent, nodes, hoverBehaviorDelay, options['highlightMatch'] == 'any'); // Stop event propagation, since this rollover is now handled event.stopPropagation(); }; /** * Base class for tree component nodes. * @class The base class for tree component nodes. * @constructor * @implements {DvtCategoricalObject} * @implements {DvtTooltipSource} * @implements {DvtSelectable} * @implements {DvtPopupSource} * @implements {DvtContextMenuSource} * @implements {DvtKeyboardNavigable} * @implements {DvtDraggable} */ var DvtBaseTreeNode = function() {}; DvtObj.createSubclass(DvtBaseTreeNode, DvtObj, 'DvtBaseTreeNode'); DvtBaseTreeNode._ANIMATION_DELETE_PRIORITY = 0; // The order in which the delete animation occurs DvtBaseTreeNode._ANIMATION_UPDATE_PRIORITY = 1; // The order in which the update animation occurs DvtBaseTreeNode._ANIMATION_INSERT_PRIORITY = 2; // The order in which the insert animation occurs DvtBaseTreeNode._DEFAULT_FILL_COLOR = '#000000'; DvtBaseTreeNode._DEFAULT_TEXT_SIZE = 11; DvtBaseTreeNode.__NODE_SELECTED_SHADOW = new DvtShadow('#000000', 2, 5, 5, 45, 0.5); /** * @param {DvtBaseTreeView} treeView The DvtBaseTreeView that owns this node. * @param {object} props The properties for the node. * @protected */ DvtBaseTreeNode.prototype.Init = function(treeView, props) { this._view = treeView; this._options = props; var nodeDefaults = this._view.getOptions()['nodeDefaults']; this._id = props['id']; this._color = props['color'] ? props['color'] : DvtBaseTreeNode._DEFAULT_FILL_COLOR; this._textStr = props['label']; this._labelStyle = typeof props['labelStyle'] == 'string' ? new DvtCSSStyle(props['labelStyle']) : props['labelStyle']; this._pattern = props['pattern']; this._selectable = props['selectable']; this._shortDesc = props['shortDesc'] ? props['shortDesc'] : props['tooltip']; this._size = props['value']; this._drilling = props['drilling'] ? props['drilling'] : nodeDefaults['drilling']; this._stampId = props['S']; // Whether this node is an artificial root this._bArtificialRoot = props.bArtificialRoot; // Node alpha is always 1 unless during animation this._alpha = 1; // reference to last visited child this._lastVisitedChild = null; this._isShowingKeyboardFocusEffect = false; this.IsHover = false; }; /** * Sets the Array containing all children of this node. * @param {array} children The array of children for this node. */ DvtBaseTreeNode.prototype.setChildNodes = function(children) { // Set this node as the parent of the children if (children != null) { for (var i = 0; i < children.length; i++) children[i]._parent = this; } // Store the children this._children = children; }; /** * Returns the Array containing all children of this node. * @return {array} The array of children belonging to this node. */ DvtBaseTreeNode.prototype.getChildNodes = function() { return this._children ? this._children : []; }; /** * Returns an Array containing all the descendants of this node * @return {Array} The array of descendants of this node */ DvtBaseTreeNode.prototype.getDescendantNodes = function() { var descendants = []; var childDescendants; var child; if (!this.hasChildren()) return descendants; for (var i = 0; i < this._children.length; i++) { child = this._children[i]; childDescendants = child.getDescendantNodes(); descendants.push(child); descendants = descendants.concat(childDescendants); } return descendants; }; /** * Sets a reference to the last visited child. * * @param {DvtBaseTreeNode} lastVisited * @protected */ DvtBaseTreeNode.prototype.SetLastVisitedChild = function(lastVisited) { this._lastVisitedChild = lastVisited; }; /** * Returns the last visited child * * @return {DvtBaseTreeNode} The last visited child * @protected */ DvtBaseTreeNode.prototype.GetLastVisitedChild = function() { return this._lastVisitedChild; }; /** * Updates the last visited child on the given node's parent to this node * @protected */ DvtBaseTreeNode.prototype.MarkAsLastVisitedChild = function() { var parent = this.GetParent(); if (parent) { parent.SetLastVisitedChild(this); } }; /** * Returns true if this node is a descendant of the specified node. * @param {DvtBaseTreeNode} node */ DvtBaseTreeNode.prototype.isDescendantOf = function(node) { if (!node || !this.GetParent()) return false; else if (this.GetParent() == node) return true; else return this.GetParent().isDescendantOf(node); }; /** * Returns an Array containing all nodes that are at the given depth away from the current node * @param {DvtBaseTreeNode} root * @param {Number} depth * @return {Array} */ DvtBaseTreeNode.prototype.GetNodesAtDepth = function(root, depth) { var returnArray = []; if (depth < 0) return returnArray; if (depth == 0) return [this]; else if (root.hasChildren()) { var children = root.getChildNodes(); var child; for (var i = 0; i < children.length; i++) { child = children[i]; returnArray = returnArray.concat(child.GetNodesAtDepth(child, depth - 1)); } } return returnArray; }; /** * Returns the node with the given id, if it is in the tree with the given root * @param {DvtBaseTreeNode} root * @param {String} id * @return {DvtBaseTreeNode} The node with the given id, or null if no node with the given id is found */ DvtBaseTreeNode.getNodeById = function(root, id) { if (root.getId() == id) { return root; } else { // recursively call getNodeById on each of the children var node = null; var children = root.getChildNodes(); var length = children.length; var child = null; for (var i = 0; i < length; i++) { child = children[i]; node = DvtBaseTreeNode.getNodeById(child, id); if (node) { // if we found the node, return it, otherwise check the next child return node; } } return null; } }; /** * Returns the component that owns this node. * @return {DvtBaseTreeView} The component that owns this node. */ DvtBaseTreeNode.prototype.getView = function() { return this._view; }; /** * Returns the id of the stamp for this node. * @return {string} The id of the stamp for this node. */ DvtBaseTreeNode.prototype.getStampId = function() { return this._stampId; }; /** * Returns the options object for this node. * @return {object} */ DvtBaseTreeNode.prototype.getOptions = function() { return this._options; }; /** * @override */ DvtBaseTreeNode.prototype.getCategories = function() { // Implements function in DvtCategoricalObject var categories = this.getOptions()['categories']; if (!categories) { // By default, append the id of this node to the parent's categories var parent = this.GetParent(); var parentCategories = parent ? parent.getCategories() : null; categories = parentCategories ? parentCategories.slice() : []; categories.push(this.getId()); } return categories; }; /** * Returns the id for this node. * @return {string} The id for this node. */ DvtBaseTreeNode.prototype.getId = function() { return this._id; }; /** * Returns the relative size of this node. * @return {Number} The relative size of this node. */ DvtBaseTreeNode.prototype.getSize = function() { // Note: Called by automation APIs return this._size; }; /** * Returns the color of this node. * @return {String} The color of this node. */ DvtBaseTreeNode.prototype.getColor = function() { // Note: Called by automation APIs return this._color; }; /** * @override */ DvtBaseTreeNode.prototype.getDatatip = function() { // Custom Tooltip from Function var tooltipFunc = this._view.getOptions()['tooltip']; if (tooltipFunc) return this.getView().getCtx().getTooltipManager().getCustomTooltip(tooltipFunc, this.getDataContext()); // Custom Tooltip from ShortDesc return this._shortDesc; }; /** * @override */ DvtBaseTreeNode.prototype.getDatatipColor = function() { return this._color; }; /** * Returns the shortDesc of the node. * @return {string} */ DvtBaseTreeNode.prototype.getShortDesc = function() { // Note: Called by automation APIs return this._shortDesc; }; /** * Returns the data context that will be passed to the tooltip function. * @return {object} */ DvtBaseTreeNode.prototype.getDataContext = function() { return { 'id': this.getId(), 'label': this.getLabel(), 'value': this.getSize(), 'color': this.getColor() }; }; /** * Returns the index for this node within the current parent. Used for automation, this takes into account nodes that * were not created due to hiddenCategories. * @return {number} */ DvtBaseTreeNode.prototype.getIndex = function() { return this.getOptions()['_index']; }; /** * Returns the alpha for this node. * @return {number} The alpha for this node. */ DvtBaseTreeNode.prototype.getAlpha = function() { // Note: This API is called by the fadeIn and fadeOut animations return this._alpha; }; /** * Specifies the alpha for this node. * @param {number} alpha The alpha for this node. */ DvtBaseTreeNode.prototype.setAlpha = function(alpha) { // Note: This API is called by the fadeIn and fadeOut animations this._alpha = alpha; if (this._shape) this._shape.setAlpha(this._alpha); }; /** * Specifies whether the children of this node are disclosed. * @param {boolean} disclosed * @protected */ DvtBaseTreeNode.prototype.setDisclosed = function(disclosed) { this.getOptions()['_expanded'] = disclosed; }; /** * Returns true if the children of this node are disclosed. * @return {boolean} * @protected */ DvtBaseTreeNode.prototype.isDisclosed = function() { return this.getOptions()['_expanded'] !== false; }; /** * Returns true if this node is the artificial root of the tree. * @return {boolean} */ DvtBaseTreeNode.prototype.isArtificialRoot = function() { return this._bArtificialRoot; }; /** * Returns true if drill replace is enabled for this node. * @return {boolean} */ DvtBaseTreeNode.prototype.isDrillReplaceEnabled = function() { return this._drilling == 'replace' || this._drilling == 'insertAndReplace'; }; /** * @override */ DvtBaseTreeNode.prototype.getShowPopupBehaviors = function() { // Retrieve from the showPopupBehaviors map in the options object, indexed via the stampid. var behaviors = this.getView().getOptions()['_spb']; if (!behaviors || !behaviors[this.getStampId()]) return null; // If found, create a DvtShowPopupBehavior and return return DvtShowPopupBehavior.createBehaviors(behaviors[this.getStampId()]); }; /** * Renders this node. * @param {DvtContainer} container The container to render in. */ DvtBaseTreeNode.prototype.render = function(container) { // subclasses should override }; /** * Renders the child nodes of this node. * @param {DvtContainer} container The container to render in. */ DvtBaseTreeNode.prototype.renderChildren = function(container) { // Render all children of this node var children = this.getChildNodes(); if (children != null) { for (var i = 0; i < children.length; i++) { children[i].render(container); } } }; /** * Updates this node and its children with values from the attribute groups. * @param {DvtAttrGroups} ag */ DvtBaseTreeNode.prototype.processAttrGroups = function(ag) { var color = ag.get(this.getOptions()['_cv']); if (color) this._color = color; }; /** * Default implementation of getNextNavigable. Returns this node as the next navigable. Subclasses should override * @override */ DvtBaseTreeNode.prototype.getNextNavigable = function(event) { // subclasses should override this.MarkAsLastVisitedChild(); return this; }; /** * @override */ DvtBaseTreeNode.prototype.getKeyboardBoundingBox = function(targetCoordinateSpace) { // subclasses should override return new DvtRectangle(0, 0, 0, 0); }; /** * @override */ DvtBaseTreeNode.prototype.getTargetElem = function() { // subclasses should override return null; }; /** * @override */ DvtBaseTreeNode.prototype.showKeyboardFocusEffect = function() { this._isShowingKeyboardFocusEffect = true; this.showHoverEffect(); if (this.handleMouseOver) this.handleMouseOver(); }; /** * @override */ DvtBaseTreeNode.prototype.hideKeyboardFocusEffect = function() { // Hide the hover effect if it was shown in response to keyboard focus if (this._isShowingKeyboardFocusEffect) { this._isShowingKeyboardFocusEffect = false; this.hideHoverEffect(); } if (this.handleMouseOut) this.handleMouseOut(); }; /** * @override */ DvtBaseTreeNode.prototype.isShowingKeyboardFocusEffect = function() { return this._isShowingKeyboardFocusEffect; }; /** * Handles a mouse over event on the node. */ DvtBaseTreeNode.prototype.handleMouseOver = function() { this.IsHover = true; }; /** * Handles a mouse out event on the node. */ DvtBaseTreeNode.prototype.handleMouseOut = function() { this.IsHover = false; }; /** * @override */ DvtBaseTreeNode.prototype.isSelectable = function() { return this._selectable != 'off' && this.getView().__getNodeSelection() != null; }; /** * @override */ DvtBaseTreeNode.prototype.isSelected = function() { return this._selected; }; /** * @override */ DvtBaseTreeNode.prototype.setSelected = function(selected) { // Store the selection state this._selected = selected; this.UpdateAriaLabel(); }; /** * @override */ DvtBaseTreeNode.prototype.showHoverEffect = function() { // subclasses should override }; /** * @override */ DvtBaseTreeNode.prototype.hideHoverEffect = function() { // subclasses should override }; /** * @override */ DvtBaseTreeNode.prototype.highlight = function(bDimmed, alpha) { // Implements DvtCategoricalObject.prototype.highlight this.setAlpha(alpha); }; /** * @override */ DvtBaseTreeNode.prototype.isDragAvailable = function(clientIds) { return this.getView().__isDragAvailable(clientIds); }; /** * @override */ DvtBaseTreeNode.prototype.getDragTransferable = function(mouseX, mouseY) { return this.getView().__getDragTransferable(this); }; /** * @override */ DvtBaseTreeNode.prototype.getDragFeedback = function(mouseX, mouseY) { return this.getView().__getDragFeedback(); }; /** * Returns a displayable used for drop site feedback. * @return {DvtDisplayable} */ DvtBaseTreeNode.prototype.getDropSiteFeedback = function() { return null; }; /** * Returns the bounds upon which the popup fired by the given behavior should align. * @param {DvtShowPopupBehavior} behavior The DvtShowPopupBehavior that is firing the popup. * @return {DvtRectangle} The rectangle that the popup should align to. */ DvtBaseTreeNode.prototype.getPopupBounds = function(behavior) { return null; // subclasses can override, or else default positioning will occur }; /** * Returns true if this node contains the given coordinates. * @param {number} x * @param {number} y * @return {boolean} */ DvtBaseTreeNode.prototype.contains = function(x, y) { return false; // subclasses should override }; /** * Returns the node under the given point, if it exists in the subtree of this node. * @param {number} x * @param {number} y * @return {DvtBaseTreeNode} */ DvtBaseTreeNode.prototype.getNodeUnderPoint = function(x, y) { return null; // subclasses should override }; /** * Returns the layout parameters for the current animation frame. * @return {array} The array of layout parameters. * @protected */ DvtBaseTreeNode.prototype.GetAnimationParams = function() { return []; // subclasses should override }; /** * Sets the layout parameters for the current animation frame. * @param {array} params The array of layout parameters. * @protected */ DvtBaseTreeNode.prototype.SetAnimationParams = function(params) { // subclasses should override }; /** * Creates the update animation for this node. * @param {DvtBaseTreeAnimationHandler} handler The animation handler, which can be used to chain animations. * @param {DvtBaseTreeNode} oldNode The old node state to animate from. */ DvtBaseTreeNode.prototype.animateUpdate = function(handler, oldNode) { // Drilling animations are handled across all nodes up front, no recursion needed if (!handler.isDrillAnimation()) { // Recurse and animate the children handler.constructAnimation(oldNode.getChildNodes(), this.getChildNodes()); } // Create the animator for this node var endState = this.GetAnimationParams(); var startState = oldNode.GetAnimationParams(endState); var nodePlayable; if (!DvtArrayUtils.equals(startState, endState)) { // Only create if state changed nodePlayable = new DvtCustomAnimation(this.getView().getCtx(), this, this.getView().__getAnimationDuration()); nodePlayable.getAnimator().addProp(DvtAnimator.TYPE_NUMBER_ARRAY, this, this.GetAnimationParams, this.SetAnimationParams, endState); // Create the playable handler.add(nodePlayable, DvtBaseTreeNode._ANIMATION_UPDATE_PRIORITY); // Determine whether size and color changed. This must be done before start state is set. var bSizeChanged = (this._size != oldNode._size); var bColorChanged = (DvtColorUtils.getRGBA(this._color) != DvtColorUtils.getRGBA(oldNode._color)); // Initialize the start state this.SetAnimationParams(startState); // If the data changed, flash directly into the update color. var animationUpdateColor = this._view.getOptions()['animationUpdateColor']; if (animationUpdateColor && (bSizeChanged || bColorChanged)) this._color = animationUpdateColor; } }; /** * Creates the insert animation for this node. * @param {DvtBaseTreeAnimationHandler} handler The animation handler, which can be used to chain animations. */ DvtBaseTreeNode.prototype.animateInsert = function(handler) { // Animate if this is a data change animation (not drilling), or if this node is not an // ancestor of the old root in a drilling animation. The ancestors are not animated // so that they appear at the beginning of the animation. if (!handler.isDrillAnimation() || !handler.isAncestorInsert(this)) { // Initialize the start state this.setAlpha(0); var anim = new DvtAnimFadeIn(this.getView().getCtx(), this, this.getView().__getAnimationDuration()); handler.add(anim, DvtBaseTreeNode._ANIMATION_INSERT_PRIORITY); // Recurse to children if (this.hasChildren()) { for (var i = 0; i < this._children.length; i++) { this._children[i].animateInsert(handler); } } } }; /** * Creates the delete animation for this node. * @param {DvtBaseTreeAnimationHandler} handler The animation handler, which can be used to chain animations. * @param {DvtContainer} container The container where deletes should be moved for animation. */ DvtBaseTreeNode.prototype.animateDelete = function(handler, container) { // Move to the new container, since the old container may be removed container.addChild(this._shape); // Create the animation var anim = new DvtAnimFadeOut(this.getView().getCtx(), this, this.getView().__getAnimationDuration()); handler.add(anim, DvtBaseTreeNode._ANIMATION_DELETE_PRIORITY); // Drilling animations are handled across all nodes up front, no recursion needed if (!handler.isDrillAnimation() && this.hasChildren()) { // Recurse to children for (var i = 0; i < this._children.length; i++) { this._children[i].animateDelete(handler, container); } } }; /** * Returns true if this node has children. * @return {boolean} true if this node has children. */ DvtBaseTreeNode.prototype.hasChildren = function() { return (this._children != null && this._children.length > 0); }; /** * Returns the parent node for this node. * @return {DvtBaseTreeNode} The parent node. * @protected */ DvtBaseTreeNode.prototype.GetParent = function() { return this._parent; }; /** * Returns the depth of the node in the tree. * @return {number} The depth of the node. * @protected */ DvtBaseTreeNode.prototype.GetDepth = function() { var depth = 0; var parent = this.GetParent(); while (parent) { depth++; parent = parent.GetParent(); } return depth; }; /** * Returns the DvtFill to use for this node. * @return {DvtFill} */ DvtBaseTreeNode.prototype.GetFill = function() { if (this._pattern) return new DvtPatternFill(this._pattern, this._color); else return new DvtSolidFill(this._color); }; /** * Calculates and returns a color for node text that will provide a * good contrast with the given color. * @param {DvtBaseTreeNode} node * @protected */ DvtBaseTreeNode.GetNodeTextColor = function(node) { if (node._pattern) { // Use black for all patterned nodes against white backgrounds return '#000000'; } else { return DvtColorUtils.getContrastingTextColor(node._color); } }; DvtBaseTreeNode.prototype.ApplyLabelTextStyle = function(text) { var defaultFillColor = DvtBaseTreeNode.GetNodeTextColor(this); text.setSolidFill(defaultFillColor); var textStyle = new Array(); textStyle.push(this._view.getOptions()['nodeDefaults']['labelStyle']); if (this._labelStyle) textStyle.push(this._labelStyle); text.setCSSStyle(DvtCSSStyle.mergeStyles(textStyle)); // In high contrast mode, override the app settings and use the default colors if (DvtAgent.isHighContrast()) text.setSolidFill(defaultFillColor); }; DvtBaseTreeNode.prototype.GetTextSize = function() { var size = DvtBaseTreeNode._DEFAULT_TEXT_SIZE; var textStyle = this._view.getOptions()['nodeDefaults']['labelStyle']; var fontSize = textStyle.getFontSize(); if (fontSize) { size = parseFloat(fontSize); } return size; }; /** * Returns the primary displayable for this node. * @return {DvtDisplayable} */ DvtBaseTreeNode.prototype.getDisplayable = function() { // Note: Called by automation APIs return this._shape; }; /** * Returns the label string for this node. * @return {string} */ DvtBaseTreeNode.prototype.getLabel = function() { // Note: Called by automation APIs return this._textStr; }; DvtBaseTreeNode.prototype.GetAfContext = function() { return this.getView().__getAfContext(); }; DvtBaseTreeNode.prototype.GetElAttributes = function() { return this.getOptions()['_cf']; }; DvtBaseTreeNode.prototype.GetTemplate = function() { return this.getView().__getTemplate(this.getStampId()); }; /** * Returns whether this node can be double clicked. */ DvtBaseTreeNode.prototype.isDoubleClickable = function() { return this.isDrillReplaceEnabled(); }; /** * Updates the aria label of the node. * @protected */ DvtBaseTreeNode.prototype.UpdateAriaLabel = function() { // subclasses should override }; /** * Simple logical object for drilling and tooltip support. * @param {DvtBaseTreeNode} node The associated node, if it has been created. * @param {string} id The id of the associated node. * @param {string} tooltip The tooltip to display. * @param {string} datatip The datatip to display. * @param {string} datatipColor The border color of the datatip. * @class * @constructor * @implements {DvtTooltipSource} */ var DvtBaseTreePeer = function(node, id, tooltip, datatip, datatipColor) { this.Init(tooltip, datatip, datatipColor); this._node = node; this._id = id; this._bDrillable = false; }; DvtObj.createSubclass(DvtBaseTreePeer, DvtSimpleObjPeer, 'DvtBaseTreePeer'); /** * Returns the id of the associated node. * @return {string} */ DvtBaseTreePeer.prototype.getId = function() { return this._id; }; /** * Returns true if the associated object is drillable. * @return {boolean} */ DvtBaseTreePeer.prototype.isDrillable = function() { return this._bDrillable; }; /** * Specifies whether the associated object is drillable. * @param {boolean} drillable */ DvtBaseTreePeer.prototype.setDrillable = function(drillable) { this._bDrillable = drillable; }; /** * Handles a mouse out event on the associated object. */ DvtBaseTreePeer.prototype.handleMouseOut = function() { // Expand/Collapse: hide button if displayed if (this._node && this._node.handleMouseOut) { this._node.handleMouseOut(); } }; /** * Breadcrumb rendering utilities for tree components. * @class */ var DvtTreeBreadcrumbsRenderer = function() {}; DvtObj.createSubclass(DvtTreeBreadcrumbsRenderer, DvtObj, 'DvtTreeBreadcrumbsRenderer'); DvtTreeBreadcrumbsRenderer._COMPONENT_GAP = 6; DvtTreeBreadcrumbsRenderer._ENABLED_INLINE_STYLE = 'color: #003286;'; /** * Performs layout and rendering for the breadcrumbs in the given space. Updates the available * space and returns the rendered displayable. * @param {DvtBaseTreeView} treeView The owning component. * @param {DvtRectangle} availSpace The rectangle within which to layout. * @param {array} ancestors * @param {string} rootLabel The label for the root node. * @return {DvtDisplayable} The rendered legend contents. */ DvtTreeBreadcrumbsRenderer.render = function(treeView, availSpace, ancestors, rootLabel) { var context = treeView.getCtx(); var styleDefaults = treeView.getOptions()['styleDefaults']; // Figure out the label styles var enabledStyleArray = new Array(); enabledStyleArray.push(new DvtCSSStyle(DvtTreeBreadcrumbsRenderer._ENABLED_INLINE_STYLE)); enabledStyleArray.push(styleDefaults['_drillTextStyle']); var enabledStyle = DvtCSSStyle.mergeStyles(enabledStyleArray).toString(); var enabledStyleOver = enabledStyle + 'text-decoration: underline;'; var disabledStyleArray = new Array(); disabledStyleArray.push(styleDefaults['_currentTextStyle']); var disabledStyle = DvtCSSStyle.mergeStyles(disabledStyleArray).toString(); // Create the breadcrumbs component and temporarily add to the component var options = {labelStyle: enabledStyle, labelStyleOver: enabledStyleOver, labelStyleDown: enabledStyleOver, disabledLabelStyle: disabledStyle}; var breadcrumbs = new DvtBreadcrumbs(context, treeView.__processBreadcrumbsEvent, treeView, options); treeView.addChild(breadcrumbs); // Create the data object for the breadcrumbs. Use the reverse of the ancestors array, since // the most distant ancestor is rendered first. var dataItems = ancestors.slice(0).reverse(); dataItems.push({'label': rootLabel}); var data = {'items': dataItems}; breadcrumbs.render(data, availSpace.w); // Figure out the height used and reduce availSpace var dims = breadcrumbs.getDimensions(); breadcrumbs.setTranslate(availSpace.x, availSpace.y); var height = dims.h + DvtTreeBreadcrumbsRenderer._COMPONENT_GAP; availSpace.y += height; availSpace.h -= height; // Remove the breadcrumbs so that it can be added under the right parent. treeView.removeChild(breadcrumbs); return breadcrumbs; }; /** * Legend rendering utilies for tree components. * @class */ var DvtTreeLegendRenderer = function() {}; DvtObj.createSubclass(DvtTreeLegendRenderer, DvtObj, 'DvtTreeLegendRenderer'); /** @private @const **/ DvtTreeLegendRenderer._LEGEND_GAP = 4; /** @private @const **/ DvtTreeLegendRenderer._LEGEND_LABEL_GAP = 7; /** @private @const **/ DvtTreeLegendRenderer._LEGEND_SECTION_GAP = 24; /** @private @const **/ DvtTreeLegendRenderer._LABEL_SIZE = 11; /** @private @const **/ DvtTreeLegendRenderer._LABEL_COLOR = '#636363'; /** @private @const **/ DvtTreeLegendRenderer._LABEL_INLINE_STYLE = 'color:' + DvtTreeLegendRenderer._LABEL_COLOR + ';'; /** * Performs layout and rendering for the legend in the given space. Updates the available * space and returns the rendered displayable. * @param {DvtBaseTreeView} treeView The owning component. * @param {DvtRectangle} availSpace The rectangle within which to layout. * @param {DvtAttrGroups} attrGroups An attribute groups describing the colors. * @return {DvtDisplayable} The rendered legend contents. */ DvtTreeLegendRenderer.render = function(treeView, availSpace, attrGroups) { var options = treeView.getOptions(); var sizeValueStr = options['sizeLabel']; var colorValueStr = options['colorLabel']; if (sizeValueStr == null && colorValueStr == null && attrGroups == null) return; var context = treeView.getCtx(); var eventManager = treeView.__getEventManager(); // Create the legend container and temporarily add to the component var legend = new DvtContainer(context); treeView.addChild(legend); // Size/Color Labels var labelContainer = DvtTreeLegendRenderer._renderLabels(context, treeView, legend, availSpace.w, sizeValueStr, colorValueStr, attrGroups); var borderColor = DvtCSSStyle.afterSkinAlta(treeView.getOptions()['skin']) ? null : '#000000'; var legendStyleArray = new Array(); legendStyleArray.push(options['styleDefaults']['_labelStyle']); var legendStyles = {borderColor: borderColor, labelStyle: DvtCSSStyle.mergeStyles(legendStyleArray)}; // Color Section var colorContainer = DvtLegendAttrGroupsRenderer.renderAttrGroups(context, eventManager, legend, availSpace.w, availSpace.h, attrGroups, legendStyles); // Position the sections horizontally var labelDims = labelContainer ? labelContainer.getDimensions() : null; var colorDims = colorContainer ? colorContainer.getDimensions() : null; if (labelContainer && !colorContainer) // Only labels, center labelContainer.setTranslateX(availSpace.y + (availSpace.w - labelDims.w) / 2); else if (colorContainer && !labelContainer) // Only colors, center colorContainer.setTranslateX(availSpace.y + (availSpace.w - colorDims.w) / 2); else if (colorContainer && labelContainer) { // Deal with overflow var availWidth = availSpace.w - DvtTreeLegendRenderer._LEGEND_SECTION_GAP; if (labelDims.w + colorDims.w > availWidth) { if (labelDims.w > availWidth / 2 && colorDims.w > availWidth / 2) { // Both don't fit, recreate at half of the avail width each legend.removeChild(labelContainer); legend.removeChild(colorContainer); labelContainer = DvtTreeLegendRenderer._renderLabels(context, treeView, legend, availWidth / 2, sizeValueStr, colorValueStr, attrGroups); colorContainer = DvtLegendAttrGroupsRenderer.renderAttrGroups(context, eventManager, legend, availWidth / 2, availSpace.h, attrGroups, legendStyles); } else if (labelDims.w > colorDims.w) { // Labels don't fit, give all remaining space var labelSpace = availWidth - colorDims.w; // Recreate the labelContainer at the available size legend.removeChild(labelContainer); labelContainer = DvtTreeLegendRenderer._renderLabels(context, treeView, legend, labelSpace, sizeValueStr, colorValueStr, attrGroups); } else { // Colors don't fit, give all remaining space var colorSpace = availWidth - labelDims.w; // Recreate the labelContainer at the available size legend.removeChild(colorContainer); colorContainer = DvtLegendAttrGroupsRenderer.renderAttrGroups(context, eventManager, legend, colorSpace, availSpace.h, attrGroups, legendStyles); } // Size changed so recalc dimensions labelDims = labelContainer.getDimensions(); colorDims = colorContainer.getDimensions(); } // Position if (DvtAgent.isRightToLeft(context)) { colorContainer.setTranslateX(availSpace.x); labelContainer.setTranslateX(availSpace.x + availSpace.w - labelDims.w); } else { labelContainer.setTranslateX(availSpace.x); colorContainer.setTranslateX(availSpace.x + availSpace.w - colorDims.w); } } // Figure out the height used and reduce availSpace var legendDims = legend.getDimensions(); legend.setTranslateY(availSpace.y + availSpace.h - legendDims.h); availSpace.h -= (legendDims.h + DvtTreeLegendRenderer._LEGEND_GAP); // Remove the legend so that it can be added under the right parent. treeView.removeChild(legend); return legend; }; /** * Performs layout and rendering for the legend labels. * @param {DvtContext} context * @param {DvtBaseTreeView} treeView The owning component. * @param {DvtContainer} legend The legend container. * @param {number} availWidth The available horizontal space. * @param {string} sizeValueStr A description of the size metric. * @param {string} colorValueStr A description of the color metric. * @param {DvtAttrGroups} attrGroups An attribute groups describing the colors. * @return {DvtDisplayable} The rendered contents. */ DvtTreeLegendRenderer._renderLabels = function(context, treeView, legend, availWidth, sizeValueStr, colorValueStr, attrGroups) { var isRTL = DvtAgent.isRightToLeft(context); var eventManager = treeView.__getEventManager(); var styleDefaults = treeView.getOptions()['styleDefaults']; var labelContainer = null; if (sizeValueStr || colorValueStr) { // Create a container for the labels labelContainer = new DvtContainer(context); legend.addChild(labelContainer); var textStyle = new Array(); textStyle.push(styleDefaults['_attributeTypeTextStyle']); var attrTypeStyle = DvtCSSStyle.mergeStyles(textStyle); textStyle = new Array(); textStyle.push(styleDefaults['_attributeValueTextStyle']); var attrValueStyle = DvtCSSStyle.mergeStyles(textStyle); // Size: Size Metric var sizeLabel; var sizeValueLabel; var sizeLabelWidth; var sizeValueLabelWidth; var sizeWidth = 0; if (sizeValueStr) { // Size Label var sizeStr = DvtBundle.getTranslation(treeView.getOptions(), 'labelSize', treeView.getBundlePrefix(), 'SIZE'); sizeLabel = new DvtOutputText(context, sizeStr, 0, 0); sizeLabel.setCSSStyle(attrTypeStyle); labelContainer.addChild(sizeLabel); sizeLabelWidth = sizeLabel.measureDimensions().w; // Size Value Label sizeValueLabel = new DvtOutputText(context, sizeValueStr, 0, 0); sizeValueLabel.setCSSStyle(attrValueStyle); labelContainer.addChild(sizeValueLabel); sizeValueLabelWidth = sizeValueLabel.measureDimensions().w; // Size section width sizeWidth = sizeLabelWidth + sizeValueLabelWidth + DvtTreeLegendRenderer._LEGEND_LABEL_GAP; } // Color: Color Metric var colorLabel; var colorValueLabel; var colorLabelWidth; var colorValueLabelWidth; var colorWidth = 0; if (colorValueStr) { // Color Label var colorStr = DvtBundle.getTranslation(treeView.getOptions(), 'labelColor', treeView.getBundlePrefix(), 'COLOR'); colorLabel = new DvtOutputText(context, colorStr, 0, 0); colorLabel.setCSSStyle(attrTypeStyle); labelContainer.addChild(colorLabel); colorLabelWidth = colorLabel.measureDimensions().w; // Color Value Label colorValueLabel = new DvtOutputText(context, colorValueStr, 0, 0); colorValueLabel.setCSSStyle(attrValueStyle); labelContainer.addChild(colorValueLabel); colorValueLabelWidth = colorValueLabel.measureDimensions().w; // Size section width colorWidth = colorLabelWidth + colorValueLabelWidth + DvtTreeLegendRenderer._LEGEND_LABEL_GAP; } // Reduce size to fit if needed availWidth -= DvtTreeLegendRenderer._LEGEND_SECTION_GAP; if (sizeWidth + colorWidth > availWidth) { var widthPerSection = availWidth / 2; if (sizeWidth > widthPerSection && colorWidth > widthPerSection) { // Both don't fit, truncate and reposition var sizeValueSpace = widthPerSection - sizeLabelWidth - DvtTreeLegendRenderer._LEGEND_LABEL_GAP; if (DvtTextUtils.fitText(sizeValueLabel, sizeValueSpace, Infinity, labelContainer)) { sizeValueLabelWidth = sizeValueLabel.measureDimensions().w; eventManager.associate(sizeValueLabel, new DvtSimpleObjPeer(sizeValueStr)); } else { labelContainer.removeChild(sizeLabel); labelContainer.removeChild(sizeValueLabel); sizeValueLabel = null; sizeValueLabelWidth = 0; } var colorValueSpace = widthPerSection - colorLabelWidth - DvtTreeLegendRenderer._LEGEND_LABEL_GAP; if (DvtTextUtils.fitText(colorValueLabel, colorValueSpace, Infinity, labelContainer)) { colorValueLabelWidth = colorValueLabel.measureDimensions().w; eventManager.associate(colorValueLabel, new DvtSimpleObjPeer(colorValueStr)); } else { labelContainer.removeChild(colorLabel); labelContainer.removeChild(colorValueLabel); colorValueLabel = null; colorValueLabelWidth = 0; } } else if (sizeWidth > colorWidth) { // Reduce the size label size if (DvtTextUtils.fitText(sizeValueLabel, availWidth - colorWidth - sizeLabelWidth - DvtTreeLegendRenderer._LEGEND_LABEL_GAP, Infinity, labelContainer)) { sizeValueLabelWidth = sizeValueLabel.measureDimensions().w; eventManager.associate(sizeValueLabel, new DvtSimpleObjPeer(sizeValueStr)); } else { labelContainer.removeChild(sizeLabel); labelContainer.removeChild(sizeValueLabel); sizeValueLabel = null; sizeValueLabelWidth = 0; } } else { // Reduce the color label size if (DvtTextUtils.fitText(colorValueLabel, availWidth - sizeWidth - colorLabelWidth - DvtTreeLegendRenderer._LEGEND_LABEL_GAP, Infinity, labelContainer)) { colorValueLabelWidth = colorValueLabel.measureDimensions().w; eventManager.associate(colorValueLabel, new DvtSimpleObjPeer(colorValueStr)); } else { labelContainer.removeChild(colorLabel); labelContainer.removeChild(colorValueLabel); colorValueLabel = null; colorValueLabelWidth = 0; } } } // Position the text objects var x = 0; if (isRTL) { if (colorValueLabel) { colorValueLabel.setX(x); x += colorValueLabelWidth + DvtTreeLegendRenderer._LEGEND_LABEL_GAP; colorLabel.setX(x); x += colorLabelWidth + DvtTreeLegendRenderer._LEGEND_SECTION_GAP; } if (sizeValueLabel) { sizeValueLabel.setX(x); x += sizeValueLabelWidth + DvtTreeLegendRenderer._LEGEND_LABEL_GAP; sizeLabel.setX(x); } } else { if (sizeValueLabel) { sizeLabel.setX(x); x += sizeLabelWidth + DvtTreeLegendRenderer._LEGEND_LABEL_GAP; sizeValueLabel.setX(x); x += sizeValueLabelWidth + DvtTreeLegendRenderer._LEGEND_SECTION_GAP; } if (colorValueLabel) { colorLabel.setX(x); x += colorLabelWidth + DvtTreeLegendRenderer._LEGEND_LABEL_GAP; colorValueLabel.setX(x); } } } return labelContainer; }; /*---------------------------------------------------------------------------------*/ /* DvtBaseTreeKeyboardHandler Keyboard handler for Sunburst */ /*---------------------------------------------------------------------------------*/ /** * @param {DvtEventManager} manager The owning DvtEventManager * @class DvtBaseTreeKeyboardHandler * @extends {DvtKeyboardHandler} * @constructor */ var DvtBaseTreeKeyboardHandler = function(manager) { this.Init(manager); }; DvtObj.createSubclass(DvtBaseTreeKeyboardHandler, DvtKeyboardHandler, 'DvtBaseTreeKeyboardHandler'); /** * @override */ DvtBaseTreeKeyboardHandler.prototype.isSelectionEvent = function(event) { return this.isNavigationEvent(event) && !event.ctrlKey; }; /** * @override */ DvtBaseTreeKeyboardHandler.prototype.isMultiSelectEvent = function(event) { return event.keyCode == DvtKeyboardEvent.SPACE && event.ctrlKey; }; /** * Default values and utility functions for component versioning. * @class * @constructor * @extends {DvtBaseComponentDefaults} */ var DvtBaseTreeDefaults = function() {}; DvtObj.createSubclass(DvtBaseTreeDefaults, DvtBaseComponentDefaults, 'DvtBaseTreeDefaults'); /** * Defaults for version 1. This component was exposed after the Alta skin, so no earlier defaults are provided. */ DvtBaseTreeDefaults.VERSION_1 = { 'skin': DvtCSSStyle.SKIN_ALTA, // Note, only attributes that are different than the XML defaults need // to be listed here, at least until the XML API is replaced. 'animationDuration': 500, 'animationOnDataChange': 'none', 'animationOnDisplay': 'none', 'highlightMatch' : 'all', 'hoverBehavior': 'none', 'hoverBehaviorDelay': 200, 'nodeDefaults': { 'labelStyle': new DvtCSSStyle("font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 11px;") }, 'selectionMode': 'multiple', 'sorting': 'off', 'styleDefaults': { '_attributeTypeTextStyle': new DvtCSSStyle("font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:12px;font-weight:bold;color:#4F4F4F"), '_attributeValueTextStyle': new DvtCSSStyle("font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:12px;"), '_currentTextStyle': new DvtCSSStyle("font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:12px;"), '_drillTextStyle': new DvtCSSStyle("font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:12px;"), '_labelStyle': new DvtCSSStyle("font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;") }, '_resources': {} }; /** * @override */ DvtBaseTreeDefaults.prototype.Init = function(defaultsMap) { // This will only be called via subclasses. Combine with defaults from this class before passing to super. var ret = { 'skyros': DvtJSONUtils.merge(defaultsMap['skyros'], DvtBaseTreeDefaults.VERSION_1), 'alta': DvtJSONUtils.merge(defaultsMap['alta'], {}) }; DvtBaseTreeDefaults.superclass.Init.call(this, ret); }; /** * Utility functions for DvtBaseTreeView. * @class */ var DvtBaseTreeUtils = {}; DvtObj.createSubclass(DvtBaseTreeUtils, DvtObj, 'DvtBaseTreeUtils'); /** * Returns the maximum depth of the tree rooted at the specified node. * @param {DvtBaseTreeNode} node The subtree to find the depth for. * @param {number} depth The depth of the specified node. * @return {number} The maximum depth of the tree. */ DvtBaseTreeUtils.calcMaxDepth = function(node, depth) { var maxDepth = depth; var children = node.getChildNodes(); if (children) { for (var i = 0; i < children.length; i++) { var childDepth = DvtBaseTreeUtils.calcMaxDepth(children[i], depth + 1); maxDepth = Math.max(maxDepth, childDepth); } } return maxDepth; }; /** * Returns the node count of the tree rooted at the specified node. * @param {DvtBaseTreeNode} node The subtree to find the depth for. * @return {number} */ DvtBaseTreeUtils.calcNodeCount = function(node) { var count = 1; var children = node.getChildNodes(); if (children) { for (var i = 0; i < children.length; i++) { count += DvtBaseTreeUtils.calcNodeCount(children[i]); } } return count; }; /** * Returns an array containing all the nodes in the subtree rooted at the specified node. * @param {DvtBaseTreeNode} node * @return {array} */ DvtBaseTreeUtils.getAllNodes = function(node) { var ret = []; DvtBaseTreeUtils._addNodesToArray(node, ret); return ret; }; /** * Returns an array containing all the visible nodes in the subtree rooted at the specified node. * @param {DvtBaseTreeNode} node * @return {array} */ DvtBaseTreeUtils.getAllVisibleNodes = function(node) { var ret = []; DvtBaseTreeUtils._addNodesToArray(node, ret, false, true); return ret; }; /** * Returns an array containing all the leaf nodes in the subtree rooted at the specified node. * @param {DvtBaseTreeNode} node * @return {array} */ DvtBaseTreeUtils.getLeafNodes = function(node) { var ret = []; DvtBaseTreeUtils._addNodesToArray(node, ret, true); return ret; }; /** * Returns true if the node with the specified options would be hidden. * @param {object} categoryMap The boolean map of hidden categories. * @param {object} nodeOptions The options for the node to process. * @return {boolean} */ DvtBaseTreeUtils.isHiddenNode = function(categoryMap, nodeOptions) { return DvtArrayUtils.hasAnyMapItem(categoryMap, nodeOptions['categories']); }; /** * If not specified, calculates and updates the attribute groups min and max values. * @param {object} attrGroupOptions * @param {array} nodes */ DvtBaseTreeUtils.calcContinuousAttrGroupsExtents = function(attrGroupOptions, nodes) { // Return if explicitly defined or no stamp id specified var stampId = attrGroupOptions['S']; if (stampId == null || (attrGroupOptions['min'] != null && attrGroupOptions['max'] != null)) return; // Loop through all the nodes to find the values var min = Infinity; var max = -Infinity; for (var i = 0; i < nodes.length; i++) { // Only process if the template id matches. This is internal and only sent by ADF. var node = nodes[i]; if (stampId == node.getStampId()) { var value = node.getOptions()['_cv']; if (value != null) { max = Math.max(max, value); min = Math.min(min, value); } } } // Apply the values if (attrGroupOptions['min'] == null) attrGroupOptions['min'] = min; if (attrGroupOptions['max'] == null) attrGroupOptions['max'] = max; }; /** * Processes the list of attribute groups, applying the continuous color properties if needed. * @param {array} attrGroupsList The array of attribute groups definitions. * @param {array} nodes The array of nodes whose attribute groups will be applied. */ DvtBaseTreeUtils.processContinuousAttrGroups = function(attrGroupsList, nodes) { for (var i = 0; i < attrGroupsList.length; i++) { var attrGroupsMap = attrGroupsList[i]; var attrGroups = attrGroupsMap.attrGroups; var stampId = attrGroupsMap.stampId; if (attrGroups instanceof DvtContinuousAttrGroups && stampId != null) { for (var j = 0; j < nodes.length; j++) { // Only process if the template id matches. This is internal and only sent by ADF. var node = nodes[j]; if (stampId == node.getStampId()) node.processAttrGroups(attrGroups); } } } }; /** * Recursively returns an array containing all nodes in the subtree of a given node. * @param {DvtBaseTreeNode} node The root of the subtree whose children will be returned. * @param {array} ret The array onto which to add the subtree. * @param {boolean=} bLeafOnly Optional flag to specify whether only leaf nodes should be included. * @param {boolean=} bRendered Optional flag to specify whether only rendered nodes should be included. * @private */ DvtBaseTreeUtils._addNodesToArray = function(node, ret, bLeafOnly, bRendered) { if (!node) return; var children = node.getChildNodes(); var childCount = children ? children.length : 0; // Add this node if ((!bLeafOnly || childCount == 0) && !(bRendered && !node.getDisplayable())) ret.push(node); // Add its children for (var i = 0; i < childCount; i++) { DvtBaseTreeUtils._addNodesToArray(children[i], ret, bLeafOnly, bRendered); } }; // Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. /*---------------------------------------------------------------------*/ /* DvtTreeAutomation Tree Automation Services */ /*---------------------------------------------------------------------*/ /** * Provides automation services for treemap/sunburst. To obtain a * @class DvtTreeAutomation * @param {DvtBaseTreeView} treeView * @implements {DvtAutomation} * @constructor * @export */ var DvtTreeAutomation = function(treeView) { this._treeView = treeView; this._root = treeView.getRootNode(); }; DvtObj.createSubclass(DvtTreeAutomation, DvtAutomation, 'DvtTreeAutomation'); /** * The subId prefix for tree nodes */ DvtTreeAutomation.NODE_ID_PREFIX = 'node'; /** * The subId prefix for breadcrumbs */ DvtTreeAutomation.BREADCRUMBS_PREFIX = 'breadcrumbs'; /** * Valid subIds inlcude: * <ul> * <li>node[nodeIndex0][nodeIndex1]...[nodeIndexN]</li> * </ul> * @override */ DvtTreeAutomation.prototype.GetSubIdForDomElement = function(displayable) { var logicalObj = this._treeView.getLogicalObject(displayable); if (!logicalObj) { // could be a breadcrumb if (displayable.getParent() instanceof DvtButton) { displayable = displayable.getParent(); } var parent = displayable.getParent(); if (parent instanceof DvtBreadcrumbs) return DvtTreeAutomation.BREADCRUMBS_PREFIX + '[' + parent.getCrumbIndex(displayable) + ']'; return null; } if (logicalObj instanceof DvtBaseTreeNode) { var currentNode = logicalObj; var indices = ''; if (!this._root.isArtificialRoot()) { // If logicalObj represents real root node, return default subId // Else include index for real root as first index in string of indices if (currentNode == this._root) return DvtTreeAutomation.NODE_ID_PREFIX + '[0]'; else indices += '[0]'; } // Indices for nodes beyond the root var childIndices = this._getIndicesFromNode(currentNode, this._root.getChildNodes()); indices = childIndices ? indices + childIndices : indices; if (indices.length > 0) return DvtTreeAutomation.NODE_ID_PREFIX + indices; } return null; }; /** * Returns the index values of the given node * @param {Object} node The tree node to find the indices for * @param {Object} children The legend nodes whose descendants are being searched * @return {String} [nodeIndex0][nodeIndex1]...[nodeIndexN] * @private */ DvtTreeAutomation.prototype._getIndicesFromNode = function(node, children) { // If there are sections in this options object, recurse through the section object if (children && children.length > 0) { for (var n = 0; n < children.length; n++) { if (children[n] == node) return '[' + n + ']'; else { var nodeIndex = this._getIndicesFromNode(node, children[n].getChildNodes()); if (nodeIndex) return '[' + n + ']' + nodeIndex; } } } return null; }; /** * Valid subIds inlcude: * <ul> * <li>node[nodeIndex0][nodeIndex1]...[nodeIndexN]</li> * <li>tooltip</li> * </ul> * @override * @export */ DvtTreeAutomation.prototype.getDomElementForSubId = function(subId) { if (!subId) return null; // tooltip if (subId == DvtAutomation.TOOLTIP_SUBID) return this.GetTooltipElement(this._treeView); if (subId.indexOf(DvtTreeAutomation.BREADCRUMBS_PREFIX) == 0) { var index = subId.substring(subId.indexOf('[') + 1, subId.indexOf(']')); var crumb = this._root.getView().getBreadcrumbs().getCrumb(index); return crumb ? crumb.getElem() : null; } //If root is real remove first index from subId because we begin searching at the root if (!this._root.isArtificialRoot()) { subId = subId.substring(0, subId.indexOf('[')) + subId.substring(subId.indexOf(']') + 1); // If no more indices exist in the string return the root dom element if (subId == DvtTreeAutomation.NODE_ID_PREFIX) return this._root.getDisplayable().getElem(); } var foundNode = this._getNodeFromSubId(this._root, subId); if (foundNode) return foundNode.getDisplayable().getElem(); return null; }; /** * Returns the tree node for the given subId * @param {Object} node The tree node whose children wil be searched * @param {String} subId The subId of the desired node * @return {Object} the child node corresponding to the given subId * @private */ DvtTreeAutomation.prototype._getNodeFromSubId = function(node, subId) { var openParen = subId.indexOf('['); var closeParen = subId.indexOf(']'); if (openParen >= 0 && closeParen >= 0) { var index = subId.substring(openParen + 1, closeParen); subId = subId.substring(closeParen + 1); var nextOpenParen = subId.indexOf('['); var nextCloseParen = subId.indexOf(']'); var childNode = DvtTreeAutomation._getNodeByIndex(node.getChildNodes(), index); if (nextOpenParen >= 0 && nextCloseParen >= 0) { // If there is another index layer recurse into the child node at that index return this._getNodeFromSubId(childNode, subId); } else // If we are at the last index return the child node at that index return childNode; } }; /** * Returns the tree node for the given path array * @param {Object} node The tree node whose children wil be searched * @param {String} path The array of indices * @return {Object} the child node corresponding to the given path * @private */ DvtTreeAutomation.prototype._getNodeFromPath = function(node, path) { // Remove index at the head of the array var index = path.shift(); var childNode = DvtTreeAutomation._getNodeByIndex(node.getChildNodes(), index); if (path.length == 0) // If this is the last index return child node at that position return childNode; else if (path.length > 0) return this._getNodeFromPath(childNode, path); return null; }; /** * Returns an object containing data for a tree node. Used for verification. * Valid verification values inlcude: * <ul> * <li>color</li> * <li>label</li> * <li>selected</li> * <li>size</li> * <li>tooltip</li> * </ul> * @param {String} subIdPath The array of indices in the subId for the desired node * @return {Object} An object containing data for the node * @export */ DvtTreeAutomation.prototype.getNode = function(subIdPath) { // If the root is real, remove first element of subIdPath since we already start searching at the root if (!this._root.isArtificialRoot() && subIdPath[0] == 0) subIdPath.shift(); // If root index was the only element of subIdPath, set the node to get data for as the root, else search for the correct node var node = (subIdPath.length == 0) ? this._root : this._getNodeFromPath(this._root, subIdPath); var nodeData = { 'color': node.getColor(), 'label': node.getLabel(), 'selected': node.isSelected() == undefined ? false : node.isSelected(), 'size': node.getSize(), 'tooltip': node.getShortDesc() }; return nodeData; }; /** * Returns the node from the array with the specified index. * @param {array} nodes * @param {number} index * @return {DvtBaseTreeNode} * @private */ DvtTreeAutomation._getNodeByIndex = function(nodes, index) { for (var i = 0; i < nodes.length; i++) { if (index == nodes[i].getIndex()) return nodes[i]; } // None found, return null return null; }; return D; });
{'content_hash': 'a3fee42f7804f895e76825e227af3038', 'timestamp': '', 'source': 'github', 'line_count': 3243, 'max_line_length': 170, 'avg_line_length': 30.589885908109775, 'alnum_prop': 0.7075693275404977, 'repo_name': 'jobinesh/jet-examples', 'id': '772b5086382d1b54fcd197920c8f400d03c42ce3', 'size': '99287', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'node-jet1.1.2-mongo-app/public/js/libs/oj/v1.1.2/debug/internal-deps/dvt/DvtBaseTreeView.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4792833'}, {'name': 'HTML', 'bytes': '52517'}, {'name': 'JavaScript', 'bytes': '48909007'}]}
<?php namespace FOS\UserBundle\Command; use FOS\UserBundle\Util\UserManipulator; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; /** * @author Antoine Hérault <[email protected]> * * @internal * * @final */ #[AsCommand(name: 'fos:user:deactivate', description: 'Deactivate a user')] class DeactivateUserCommand extends Command { // BC with Symfony <5.3 protected static $defaultName = 'fos:user:deactivate'; private $userManipulator; public function __construct(UserManipulator $userManipulator) { parent::__construct(); $this->userManipulator = $userManipulator; } /** * {@inheritdoc} */ protected function configure() { $this // BC with Symfony <5.3 ->setName('fos:user:deactivate') ->setDescription('Deactivate a user') ->setDefinition([ new InputArgument('username', InputArgument::REQUIRED, 'The username'), ]) ->setHelp(<<<'EOT' The <info>fos:user:deactivate</info> command deactivates a user (will not be able to log in) <info>php %command.full_name% matthieu</info> EOT ); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output): int { $username = $input->getArgument('username'); $this->userManipulator->deactivate($username); $output->writeln(sprintf('User "%s" has been deactivated.', $username)); return 0; } /** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { if (!$input->getArgument('username')) { $question = new Question('Please choose a username:'); $question->setValidator(function ($username) { if (empty($username)) { throw new \Exception('Username can not be empty'); } return $username; }); $answer = $this->getHelper('question')->ask($input, $output, $question); $input->setArgument('username', $answer); } } }
{'content_hash': '805865139d4153b7aa48178ef6c1a711', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 92, 'avg_line_length': 26.877777777777776, 'alnum_prop': 0.6134766432410087, 'repo_name': 'FriendsOfSymfony/FOSUserBundle', 'id': 'd1876f706d4242254013e95c9749494937d3c203', 'size': '2672', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Command/DeactivateUserCommand.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '154'}, {'name': 'PHP', 'bytes': '283258'}, {'name': 'Twig', 'bytes': '6819'}]}
Helium ====== A small 64 bit OS with a micro-kernel. ## Done 1. Read Multiboot Info - memory map - module table ## Partially Done 2. Setup Page Frame Allocator - watermark - revisit for more sophisticated implementation ## TODO 3. Setup Virtual Memory Allocator - decide where to map paging structures 4. CPU features like I/O Ports, MSRs, etc. - may be needed be earlier steps too 5. Parse ACPI and SMP Tables - needs virtual memory management (at least for ACPI) 6. Enable I/O APICs and Local APIC of BSP 7. Boot Application Processors 8. Keyboard 9. User Mode processes 10. Virtual Consoles
{'content_hash': 'd302a442cbba468fa062298ae12e5e23', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 57, 'avg_line_length': 21.133333333333333, 'alnum_prop': 0.7113564668769716, 'repo_name': 'fatho/Helium', 'id': 'ea54eb0fdaf532875f49ea48f9d03b476c35c0a0', 'size': '634', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '12562'}, {'name': 'C', 'bytes': '129325'}, {'name': 'C++', 'bytes': '44794'}, {'name': 'Shell', 'bytes': '431'}]}
@implementation PriceBar @synthesize date = _date; @synthesize open = _open; @synthesize high = _high; @synthesize low = _low; @synthesize close = _close; @synthesize volume = _volume; - (instancetype)initWithOpen:(double)open high:(double)high low:(double)low close:(double)close volume:(long)volume { self = [super init]; if (self) { _date = [[NSDate alloc] init]; _open = open; _high = high; _low = low; _close = close; _volume = volume; } return self; } - (instancetype)initWithDate:(NSDate *)date open:(double)open high:(double)high low:(double)low close:(double)close volume:(long)volume { self = [super init]; if (self) { _date = date; _open = open; _high = high; _low = low; _close = close; _volume = volume; } return self; } @end
{'content_hash': '2654d0f60961d8629be540e4af4fc615', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 137, 'avg_line_length': 24.194444444444443, 'alnum_prop': 0.5832376578645235, 'repo_name': 'ABTSoftware/SciChartiOSTutorial', 'id': '0c835ac36a0367eb1aa2e6cbdeff16c4326ed6b1', 'size': '1647', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'v2.x/Examples/SciChartDemo/SciChartDemo/Data/PriceBar.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Swift', 'bytes': '77055'}]}
(function() { 'use strict'; if (!navigator.geolocation) { alert('Cannot use geolocation'); return; } var success = function(pos) { console.log(pos.coords); var info = '緯度:' + pos.coords.latitude + '<br/>' + '経度:' + pos.coords.longitude + '<br/>'; console.log(info); document.getElementById('current_info').innerHTML = info; }; var error = function(err) { alert('ERROR! (' + err.code + ' : ' + err.message + ')'); }; navigator.geolocation.getCurrentPosition(success, error); }).call(this);
{'content_hash': 'b0988f411078b84f16748aaf27c88052', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 74, 'avg_line_length': 28.526315789473685, 'alnum_prop': 0.5977859778597786, 'repo_name': 'TomckySan/wordbench', 'id': 'ae30d8b0c3de7fed2fb130b8429d953fb49df63e', 'size': '550', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vol9_20150425/geolocation-api-sample/geolocation-sample.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '844'}, {'name': 'JavaScript', 'bytes': '3347'}]}
import { SessionApitype } from './../apitypes/Session.apitype'; import { Injectable } from '@angular/core'; @Injectable() export class StateService { private _isLoggedIn = false; get isLoggedIn(): boolean { return this._isLoggedIn; } set isLoggedIn(_isLoggedIn: boolean) { this._isLoggedIn = _isLoggedIn; this.saveLocalStorage(); } private _isAdmin = false; get isAdmin(): boolean { return this._isAdmin; } set isAdmin(_isAdmin: boolean) { this._isAdmin = _isAdmin; this.saveLocalStorage(); } private _apiToken: string = null; get apiToken(): string { return this._apiToken; } set apiToken(_apiToken: string) { this._apiToken = _apiToken; this.saveLocalStorage(); } private _isNative = false; get isNative(): boolean { return this._isNative; } set isNative(_isNative: boolean) { this._isNative = _isNative; this.saveLocalStorage(); } private _pageSize = 25; get pageSize(): number { return this._pageSize; } set pageSize(_pageSize: number) { this._pageSize = _pageSize; this.saveLocalStorage(); } private _pageSizes = [5, 10, 25, 50, 100]; get pageSizes(): Array<number> { return this._pageSizes; } private _recordTypes = [ 'A', 'A6', 'AAAA', 'AFSDB', 'ALIAS', 'CAA', 'CDNSKEY', 'CDS', 'CERT', 'CNAME', 'DHCID', 'DLV', 'DNAME', 'DNSKEY', 'DS', 'EUI48', 'EUI64', 'HINFO', 'IPSECKEY', 'KEY', 'KX', 'LOC', 'LUA', 'MAILA', 'MAILB', 'MINFO', 'MR', 'MX', 'NAPTR', 'NS', 'NSEC', 'NSEC3', 'NSEC3PARAM', 'OPENPGPKEY', 'OPT', 'PTR', 'RKEY', 'RP', 'RRSIG', 'SIG', 'SPF', 'SRV', 'TKEY', 'SSHFP', 'TLSA', 'TSIG', 'TXT', 'WKS', 'MBOXFW', 'URL' ]; get recordTypes(): Array<string> { return this._recordTypes; } constructor() { this.loadLocalStorage(); } private saveLocalStorage() { localStorage.setItem('pdnsmanagerstate', JSON.stringify(this)); } private loadLocalStorage() { Object.assign(this, JSON.parse(localStorage.getItem('pdnsmanagerstate'))); } }
{'content_hash': '1adac14952514977ee189dee90331134', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 95, 'avg_line_length': 27.6625, 'alnum_prop': 0.5661997288748305, 'repo_name': 'loewexy/pdnsmanager', 'id': '3535deb3289309ad74a76fd389706977fd49919b', 'size': '2213', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'frontend/src/app/services/state.service.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '41226'}, {'name': 'JavaScript', 'bytes': '67754'}, {'name': 'PHP', 'bytes': '136459'}, {'name': 'SCSS', 'bytes': '2066'}, {'name': 'Shell', 'bytes': '4786'}, {'name': 'TypeScript', 'bytes': '102332'}]}
using System.IO; using Goedel.Mesh.Shell; using Goedel.Cryptography; using MT=Microsoft.VisualStudio.TestTools.UnitTesting; using Goedel.Test; namespace Goedel.Catalog.Test { [MT.TestClass] public partial class CatalogTests { static string ResultDirectory; static string ContainerDirectory = "Shells"; const string DirectorySource = "Files"; const string DirectoryEncrypted = "Encrypted"; const string DirectoryDecrypted = "Decrypted"; const string DirectoryTarget = "Target"; string Target(string File) => DirectoryTarget + @"\" + File; const string DirectoryArchive = "Archive"; const string DirectoryArchiveCopy = "ArchiveCopy"; string Archive(string File) => DirectoryArchive + @"\" + File; const string FileTest1 = @"PHBLogo1.svg"; const string FileTest2 = @"PHBLogo1.svg"; const string FileTest3 = @"PHBLogo180.png"; const string FileTest4 = @"PHBLogo256.ico"; const string FileTest5 = @"PHBLogo256.png"; /// <summary> /// /// </summary> public static void TestDirect() { InitializeClass(); var Instance = new CatalogTests(); //Instance.TestBasicCalendar(); //Instance.TestContainerSerial(); Instance.TestContainerArchiveBase(); //Instance.TestBasicBookMark(); //Instance.TestBasicCredential(); } static ShellDispatch ShellDispatchCommon; [MT.AssemblyInitialize] public static void InitializeClass(MT.TestContext Context) { ResultDirectory = Context.TestRunDirectory; Directory.SetCurrentDirectory(Directories.RunDirectoryFramework); InitializeClass(); } public static void InitializeClass() { Directory.CreateDirectory(ContainerDirectory); Directory.CreateDirectory(DirectoryEncrypted); Directory.CreateDirectory(DirectoryDecrypted); Directory.CreateDirectory(DirectoryTarget); Directory.CreateDirectory(DirectoryArchive); CryptographyWindows.Initialize(); ShellDispatchCommon = GetShell("TestFile.dcon"); // OK so here create ourselves a set of test keys for encryption and signature } static ShellDispatch GetShell(string Filename) { Filename = ContainerDirectory + @"\" + Filename; File.Delete(Filename); return new ShellDispatch(Catalog: Filename); } } }
{'content_hash': '3d63cd8735f3281586ecfccfc871e2aa', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 90, 'avg_line_length': 34.62820512820513, 'alnum_prop': 0.6086634579785265, 'repo_name': 'hallambaker/Mathematical-Mesh', 'id': 'cf66a66ca0af10724080b5d89e43ec9fffea30a3', 'size': '2703', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'Testing/Goedel.Catalog.Test/base.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '4297'}, {'name': 'C', 'bytes': '10818'}, {'name': 'C#', 'bytes': '7433774'}, {'name': 'C++', 'bytes': '2618'}, {'name': 'CSS', 'bytes': '24248'}, {'name': 'Dockerfile', 'bytes': '146'}, {'name': 'HTML', 'bytes': '18736869'}, {'name': 'JavaScript', 'bytes': '2218'}, {'name': 'Makefile', 'bytes': '143050'}, {'name': 'Python', 'bytes': '27929'}, {'name': 'Shell', 'bytes': '40856'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Minim : : AudioSample : : mute</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="stylesheet.css" rel="stylesheet" type="text/css"> </head> <body> <center> <table class="mainTable"> <tr> <td class="header"> <span class="indexheader">Minim</span><br/> <span class="indexnavigation"> <a href="index.html">core</a> | <a href="index_ugens.html">ugens</a> | <a href="index_analysis.html">analysis</a> </span> </td> <td class="border-left">&nbsp;</td> </tr> <tr> <td class="classNavigation"> <p class="mainTextName"><A href="controller_class_controller.html">Controller</A></p> <p class="methodName">mute</p> </td> <td class="mainText border-left"> <p class="memberSectionHeader">Description</p> Mutes the sound. <p class="memberSectionHeader">Signature</p> <pre>void mute() </pre> <p class="memberSectionHeader">Returns</p> <p>None</p> <p class="memberSectionHeader">Related</p> <A href="audiosample_method_unmute.html">unmute ( )</A><BR> <A href="audiosample_method_ismuted.html">isMuted ( )</A><BR> <p class="memberSectionHeader">Example</p> <pre>None available</pre> <p class="memberSectionHeader">Usage</p> Web & Application </td> </tr> </table> </center> </body> </html>
{'content_hash': '372c16faad41ee81e05f565709e3eed5', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 90, 'avg_line_length': 26.83050847457627, 'alnum_prop': 0.5862286797220467, 'repo_name': 'UTSDataArena/examples', 'id': '9fe9036c495ae317e616fa16d4a028e58272168a', 'size': '1583', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'processing/sketchbook/libraries/minim/documentation/audiosample_method_mute.html', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '76811'}, {'name': 'HTML', 'bytes': '791628'}, {'name': 'Java', 'bytes': '1060796'}, {'name': 'JavaScript', 'bytes': '1863596'}, {'name': 'Matlab', 'bytes': '16205'}, {'name': 'Processing', 'bytes': '506308'}, {'name': 'Python', 'bytes': '118339'}, {'name': 'Shell', 'bytes': '165'}]}
// This code is auto-generated, do not modify package com.spectralogic.ds3client.commands.parsers; import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser; import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils; import com.spectralogic.ds3client.commands.spectrads3.notifications.GetPoolFailureNotificationRegistrationSpectraS3Response; import com.spectralogic.ds3client.models.PoolFailureNotificationRegistration; import com.spectralogic.ds3client.networking.WebResponse; import com.spectralogic.ds3client.serializer.XmlOutput; import java.io.IOException; import java.io.InputStream; public class GetPoolFailureNotificationRegistrationSpectraS3ResponseParser extends AbstractResponseParser<GetPoolFailureNotificationRegistrationSpectraS3Response> { private final int[] expectedStatusCodes = new int[]{200}; @Override public GetPoolFailureNotificationRegistrationSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException { final int statusCode = response.getStatusCode(); if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) { switch (statusCode) { case 200: try (final InputStream inputStream = response.getResponseStream()) { final PoolFailureNotificationRegistration result = XmlOutput.fromXml(inputStream, PoolFailureNotificationRegistration.class); return new GetPoolFailureNotificationRegistrationSpectraS3Response(result, this.getChecksum(), this.getChecksumType()); } default: assert false: "validateStatusCode should have made it impossible to reach this line"; } } throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes); } }
{'content_hash': '59a2e766680916f5b837f6d89dfc5c3d', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 164, 'avg_line_length': 51.27777777777778, 'alnum_prop': 0.776273022751896, 'repo_name': 'DenverM80/ds3_java_sdk', 'id': '285ec7d4bab75a52a6e6d54bc773024886d536d8', 'size': '2603', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/parsers/GetPoolFailureNotificationRegistrationSpectraS3ResponseParser.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '4841457'}, {'name': 'Kotlin', 'bytes': '9285'}, {'name': 'Ruby', 'bytes': '3144'}, {'name': 'Shell', 'bytes': '474'}]}
package com.google.errorprone.refaster; import com.google.auto.value.AutoValue; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.Iterables; import com.google.errorprone.refaster.ControlFlowVisitor.Result; import com.sun.source.tree.IfTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.TreeVisitor; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.util.List; import javax.annotation.Nullable; /** * {@link UTree} representation of an {@link IfTree}. * * @author [email protected] (Louis Wasserman) */ @AutoValue abstract class UIf implements UStatement, IfTree { public static UIf create( UExpression condition, UStatement thenStatement, UStatement elseStatement) { return new AutoValue_UIf(condition, thenStatement, elseStatement); } @Override public abstract UExpression getCondition(); @Override public abstract UStatement getThenStatement(); @Override @Nullable public abstract UStatement getElseStatement(); @Override public <R, D> R accept(TreeVisitor<R, D> visitor, D data) { return visitor.visitIf(this, data); } @Override public Kind getKind() { return Kind.IF; } private static Function<Unifier, Choice<Unifier>> unifyUStatementWithSingleStatement( @Nullable final UStatement toUnify, @Nullable final StatementTree target) { return (Unifier unifier) -> { if (toUnify == null) { return (target == null) ? Choice.of(unifier) : Choice.<Unifier>none(); } List<StatementTree> list = (target == null) ? List.<StatementTree>nil() : List.of(target); return toUnify .apply(UnifierWithUnconsumedStatements.create(unifier, list)) .condition(s -> s.unconsumedStatements().isEmpty()) .transform(UnifierWithUnconsumedStatements::unifier); }; } @Override @Nullable public Choice<UnifierWithUnconsumedStatements> apply(UnifierWithUnconsumedStatements state) { java.util.List<? extends StatementTree> unconsumedStatements = state.unconsumedStatements(); if (unconsumedStatements.isEmpty()) { return Choice.none(); } final java.util.List<? extends StatementTree> unconsumedStatementsTail = unconsumedStatements.subList(1, unconsumedStatements.size()); StatementTree firstStatement = unconsumedStatements.get(0); if (firstStatement.getKind() != Kind.IF) { return Choice.none(); } final IfTree ifTree = (IfTree) firstStatement; Unifier unifier = state.unifier(); Choice<UnifierWithUnconsumedStatements> forwardMatch = getCondition() .unify(ifTree.getCondition(), unifier.fork()) .thenChoose( unifyUStatementWithSingleStatement(getThenStatement(), ifTree.getThenStatement())) .thenChoose( unifierAfterThen -> { if (getElseStatement() != null && ifTree.getElseStatement() == null && ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement()) == Result.ALWAYS_RETURNS) { Choice<UnifierWithUnconsumedStatements> result = getElseStatement() .apply( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); if (getElseStatement() instanceof UBlock) { Choice<UnifierWithUnconsumedStatements> alternative = Choice.of( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); for (UStatement stmt : ((UBlock) getElseStatement()).getStatements()) { alternative = alternative.thenChoose(stmt); } result = result.or(alternative); } return result; } else { return unifyUStatementWithSingleStatement( getElseStatement(), ifTree.getElseStatement()) .apply(unifierAfterThen) .transform( unifierAfterElse -> UnifierWithUnconsumedStatements.create( unifierAfterElse, unconsumedStatementsTail)); } }); Choice<UnifierWithUnconsumedStatements> backwardMatch = getCondition() .negate() .unify(ifTree.getCondition(), unifier.fork()) .thenChoose( unifierAfterCond -> { if (getElseStatement() == null) { return Choice.none(); } return getElseStatement() .apply( UnifierWithUnconsumedStatements.create( unifierAfterCond, List.of(ifTree.getThenStatement()))) .thenOption( (UnifierWithUnconsumedStatements stateAfterThen) -> stateAfterThen.unconsumedStatements().isEmpty() ? Optional.of(stateAfterThen.unifier()) : Optional.<Unifier>absent()); }) .thenChoose( unifierAfterThen -> { if (ifTree.getElseStatement() == null && ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement()) == Result.ALWAYS_RETURNS) { Choice<UnifierWithUnconsumedStatements> result = getThenStatement() .apply( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); if (getThenStatement() instanceof UBlock) { Choice<UnifierWithUnconsumedStatements> alternative = Choice.of( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); for (UStatement stmt : ((UBlock) getThenStatement()).getStatements()) { alternative = alternative.thenChoose(stmt); } result = result.or(alternative); } return result; } else { return unifyUStatementWithSingleStatement( getThenStatement(), ifTree.getElseStatement()) .apply(unifierAfterThen) .transform( unifierAfterElse -> UnifierWithUnconsumedStatements.create( unifierAfterElse, unconsumedStatementsTail)); } }); return forwardMatch.or(backwardMatch); } @Override public List<JCStatement> inlineStatements(Inliner inliner) throws CouldNotResolveImportException { return List.<JCStatement>of( inliner .maker() .If( getCondition().inline(inliner), Iterables.getOnlyElement(getThenStatement().inlineStatements(inliner)), (getElseStatement() == null) ? null : Iterables.getOnlyElement(getElseStatement().inlineStatements(inliner)))); } }
{'content_hash': '2c0b4be3dd2147a31d89f107fb938bad', 'timestamp': '', 'source': 'github', 'line_count': 180, 'max_line_length': 100, 'avg_line_length': 43.15, 'alnum_prop': 0.5664992918758851, 'repo_name': 'cushon/error-prone', 'id': '88b624e65c581fde18b04fe60a17366bf957a88e', 'size': '8372', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/com/google/errorprone/refaster/UIf.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '2061'}, {'name': 'Java', 'bytes': '7364383'}, {'name': 'Python', 'bytes': '10499'}, {'name': 'Shell', 'bytes': '1815'}]}
'use strict'; const expect = require('../../helpers/expect'); const WriteImages = require('../../../src/utils/write-images'); const fs = require('fs'); const sizeOf = require('image-size'); const _forOwn = require('lodash').forOwn; describe('WriteImages', function() { // Hitting the file system is slow this.timeout(0); before(() => { if (!fs.existsSync('tmp')) fs.mkdirSync('tmp'); }); context('when source, projectPath, dest, and platformSizes', () => { const source = 'node-tests/fixtures/icon.svg'; const projectPath = 'tmp'; const dest = 'icons'; const platformSizes = { ios: { sizeKey: 'width', sizes: [ { size: 57, id: 'icon' } ] } }; let subject; before(() => { subject = WriteImages({ source: source, projectPath: projectPath, dest: dest, platformSizes: platformSizes }); }); after(() => { platformSizes['ios'].sizes.forEach((rasterize) => { fs.unlinkSync(`${projectPath}/${rasterize.path}`); }); }); it('resolves to platform sizes updated with paths', (done) => { subject.then((updatedPlatformSizes) => { try { _forOwn(updatedPlatformSizes, (icons, platform) => { icons.sizes.map((size) => { const path = `${dest}/${platform}/${size.id}.png`; expect(size.path).to.equal(path); }); }); done(); } catch(e) { done(e); } }); }); it('writes the files to rasterize at the right size', (done) => { subject.then((updatedPlatformSizes) => { try { updatedPlatformSizes['ios'].sizes.forEach((rasterize) => { const writePath = `${projectPath}/${rasterize.path}`; expect(fs.existsSync(writePath)).to.equal(true); expect(sizeOf(writePath).width).to.equal(rasterize.size); expect(sizeOf(writePath).height).to.equal(rasterize.size); }); done(); } catch(e) { done(e); } }); }); }); });
{'content_hash': 'd21cf1bd3dead2a17affc844d954fedf', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 70, 'avg_line_length': 26.40963855421687, 'alnum_prop': 0.5086678832116789, 'repo_name': 'isleofcode/splicon', 'id': '183e13ebd76446bc84602ab0294ff2c2d5b2bc03', 'size': '2192', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node-tests/unit/utils/write-images-test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '37934'}]}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd"> <sun-web-app error-url=""> <context-root>/Gateway/AdminDistribution/2_0</context-root> <class-loader delegate="false"/> <jsp-config> <property name="keepgenerated" value="true"> <description>Keep a copy of the generated servlet class' java code.</description> </property> </jsp-config> </sun-web-app>
{'content_hash': '43670b2a67b0f399b43fb07b8f7751f1', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 168, 'avg_line_length': 48.27272727272727, 'alnum_prop': 0.6949152542372882, 'repo_name': 'sailajaa/CONNECT', 'id': '4f561b11a0dc1aa417869695d3405788e28a89e0', 'size': '531', 'binary': False, 'copies': '2', 'ref': 'refs/heads/CONNECT_integration', 'path': 'Product/Production/Gateway/AdminDistribution_20/src/main/webapp/WEB-INF/sun-web.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '5539'}, {'name': 'Groovy', 'bytes': '1641'}, {'name': 'Java', 'bytes': '12552183'}, {'name': 'Python', 'bytes': '773'}, {'name': 'Shell', 'bytes': '14607'}, {'name': 'XSLT', 'bytes': '35057'}]}
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace GRA.SRP.ControlRoom.Modules.Setup { public partial class SurveyEmbedCode { /// <summary> /// SID control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList SID; /// <summary> /// DDSourceType control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList DDSourceType; /// <summary> /// IWidth control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox IWidth; /// <summary> /// revIWidth control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RegularExpressionValidator revIWidth; /// <summary> /// rvIWidth control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator rvIWidth; /// <summary> /// DDSourceID control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList DDSourceID; /// <summary> /// IHeight control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox IHeight; /// <summary> /// RegularExpressionValidator1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator1; /// <summary> /// RangeValidator1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RangeValidator RangeValidator1; /// <summary> /// btnFilter control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnFilter; /// <summary> /// btnFilter0 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnFilter0; /// <summary> /// odsDDSurveys control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ObjectDataSource odsDDSurveys; /// <summary> /// pnlResults control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnlResults; /// <summary> /// lblInfo control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblInfo; /// <summary> /// txtResults control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtResults; } }
{'content_hash': 'd629095c405935f7e0753d3f80454e26', 'timestamp': '', 'source': 'github', 'line_count': 150, 'max_line_length': 107, 'avg_line_length': 35.846666666666664, 'alnum_prop': 0.5460293844151014, 'repo_name': 'justinmeiners/greatreadingadventure', 'id': '66e0b85c81ba5bf1407f1e44c2aae027ecdf2aae', 'size': '5379', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SRP/ControlRoom/Modules/Setup/SurveyEmbedCode.aspx.designer.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '2280623'}, {'name': 'C#', 'bytes': '3427541'}, {'name': 'CSS', 'bytes': '188580'}, {'name': 'HTML', 'bytes': '142'}, {'name': 'JavaScript', 'bytes': '632812'}, {'name': 'PLpgSQL', 'bytes': '57277'}, {'name': 'SQLPL', 'bytes': '51553'}]}
/** * Module dependencies */ var _ = require('lodash') , util = require('util'); /** * Sort the tuples in `data` using `comparator`. * * @param { Object[] } data * @param { Object } comparator * @return { Object[] } */ module.exports = function (data, comparator) { if( !comparator || !data ) return data; return sortData(_.clone(data), comparator); }; ////////////////////////// /// /// private methods || /// \/ /// ////////////////////////// /** * Sort `data` (tuples) using `sortCriteria` (comparator) * * Based on method described here: * http://stackoverflow.com/a/4760279/909625 * * @param { Object[] } data [tuples] * @param { Object } sortCriteria [mongo-style comparator object] * @return { Object[] } */ function sortData(data, sortCriteria) { function dynamicSort(property) { var sortOrder = 1; if(property[0] === '-') { sortOrder = -1; property = property.substr(1); } return function (a,b) { var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; return result * sortOrder; }; } function dynamicSortMultiple() { var props = arguments; return function (obj1, obj2) { var i = 0, result = 0, numberOfProperties = props.length; while(result === 0 && i < numberOfProperties) { result = dynamicSort(props[i])(obj1, obj2); i++; } return result; }; } // build sort criteria in the format ['firstName', '-lastName'] var sortArray = []; _.each(_.keys(sortCriteria), function(key) { if(sortCriteria[key] === -1) sortArray.push('-' + key.toLowerCase()); else sortArray.push(key.toLowerCase()); }); data.sort(dynamicSortMultiple.apply(null, sortArray)); return data; }
{'content_hash': '5e12aa3165a8a91e98a9740db33f4848', 'timestamp': '', 'source': 'github', 'line_count': 84, 'max_line_length': 90, 'avg_line_length': 21.738095238095237, 'alnum_prop': 0.56078860898138, 'repo_name': 'ShaneK/TibiaXMLParser', 'id': '92cfdb8e0b7cbb99f7ec3486bcdf5792c2daaebe', 'size': '1826', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node_modules/waterline/node_modules/waterline-criteria/lib/filters/sort.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '18831'}]}
module Typingtutor class Stats FILE = File.expand_path('~/.typingtutor') def initialize @stats = {} @stats.merge!(YAML.load(IO.read(FILE))) if File.exists?(FILE) @stats[:created_at] ||= Time.now @stats[:total] ||= {} @stats[:exercises] ||= {} @stats[:words] ||= {} @stats[:letters] ||= {} end def save @stats[:updated_at] = Time.now IO.write(FILE, YAML.dump(@stats)) end def record_exercise(exercise) @stats[:exercises][exercise.name] ||= {} @stats[:exercises][exercise.name][:runs] ||= 0 @stats[:exercises][exercise.name][:runs] += 1 @stats[:exercises][exercise.name][:last_run] = Time.now @stats[:exercises][exercise.name][:last_run_results] = exercise.results # update totals @stats[:total][:runs] ||= 0 @stats[:total][:runs] += 1 [:time, :chars, :correct_chars, :words, :keystrokes].each do |metric| @stats[:total][metric] ||= 0 @stats[:total][metric] += exercise.results[metric] end @stats[:total][:max_wpm] ||= 0 @stats[:total][:max_wpm] = [@stats[:total][:max_wpm], exercise.results[:gross_wpm]].max @stats[:total][:avg_wpm] = @stats[:total][:words] / (@stats[:total][:time] / 60) end def record_word(word) # TODO end def record_letter(letter, ok) return if letter == ' ' @stats[:letters][letter] ||= {} @stats[:letters][letter][:total] ||= {} @stats[:letters][letter][:total][:count] ||= 0 @stats[:letters][letter][:total][:count] += 1 @stats[:letters][letter][:total][:correct] ||= 0 @stats[:letters][letter][:total][:correct] += 1 if ok @stats[:letters][letter][:total][:accuracy] = (@stats[:letters][letter][:total][:correct].to_f / @stats[:letters][letter][:total][:count].to_f * 100).round end def print puts "------------------------" puts "Your avg speed: #{@stats[:total][:avg_wpm].round} wpm" puts "Your max speed: #{@stats[:total][:max_wpm].round} wpm" end def print_full puts "Accuracy per letter:" worst_letters.each {|letter, accuracy| puts "#{letter}: #{accuracy.round}%"} if @stats[:exercises].size > 0 puts puts "Exercises:" @stats[:exercises].each do |name, data| puts "- #{name}: #{data[:runs]} runs, #{data[:last_run_results][:gross_wpm].round} wpm" end end puts puts "Exercises played: #{@stats[:total][:runs] || 0}" puts "Time played: #{(@stats[:total][:time] || 0).round.divmod(60).join('m ')}s" puts "Avg speed: #{(@stats[:total][:avg_wpm] || 0).round} wpm" puts "Max speed: #{(@stats[:total][:max_wpm] || 0).round} wpm" end def worst_letters accuracy = @stats[:letters].map {|letter, data| [letter, data[:total][:accuracy]]}.to_h # { "a" => 100, "b" => 98 } accuracy.reject! {|key, value| value == 100} accuracy.reject! {|key, value| key !~ /\w/ } accuracy = accuracy.sort_by {|key, value| value }.to_h accuracy end end end
{'content_hash': '72561e44f45265a945da83541784281d', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 161, 'avg_line_length': 35.07954545454545, 'alnum_prop': 0.5562034337544541, 'repo_name': 'paolodona/typingtutor', 'id': '98a4c6115c9fd619778e09b149b60ba66a910fc1', 'size': '3087', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/typingtutor/stats.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '11768'}]}
require 'cloud_formation/bridge/request' require 'cloud_formation/bridge/names' require 'cloud_formation/bridge/resources/elasti_cache_replication_group' describe CloudFormation::Bridge::Resources::ElastiCacheReplicationGroup do include FileSupport FIELDS = CloudFormation::Bridge::Names::FIELDS ELASTI_CACHE = CloudFormation::Bridge::Names::ELASTI_CACHE let(:replication_group_id) { "dev-redis-rep" } def stub_describe_replication_group expect(subject.client).to receive(:describe_replication_groups). with(replication_group_id: replication_group_id). and_return(parse_json("describe-replication-group-primary-only")) end context "#create" do let(:request) { CloudFormation::Bridge::Request.new(parse_json("create-replication-group-message", false)) } it 'creates the replication group' do expect(subject.client).to receive(:create_replication_group).with( replication_group_id: replication_group_id, primary_cluster_id: "cluster-id-here", replication_group_description: "Sample replication group for the redis instances", ) stub_describe_replication_group outputs = subject.create(request) expect(outputs).to eq( FIELDS::DATA => { ELASTI_CACHE::REPLICATION_GROUP_ID => replication_group_id, }, FIELDS::PHYSICAL_RESOURCE_ID => replication_group_id, ) end end context "#delete" do let(:request) { CloudFormation::Bridge::Request.new(parse_json("delete-replication-group-message", false)) } it 'should delete the group' do stub_describe_replication_group expect(subject.client).to receive(:delete_replication_group).with( replication_group_id: replication_group_id, retain_primary_cluster: true, ) subject.delete(request) end it 'should ignore if the replication group does not exist' do expect(subject).to receive(:replication_group_available?).and_raise(AWS::ElastiCache::Errors::ReplicationGroupNotFoundFault) expect { subject.delete(request) }.not_to raise_error end end end
{'content_hash': 'f07f4f3fe7d0d531278419bb2ac6c1e2', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 130, 'avg_line_length': 37.50769230769231, 'alnum_prop': 0.6119770303527482, 'repo_name': 'TheNeatCompany/cfn-bridge', 'id': '956e5b49f687785390c9c9757a239e7a84d387cf', 'size': '2438', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/lib/cloud_formation/bridge/resources/elasti_cache_replication_group_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '49994'}]}
package com.thoughtworks.go.config; import com.thoughtworks.go.config.helper.ValidationContextMother; import com.thoughtworks.go.config.policy.Allow; import com.thoughtworks.go.config.policy.Policy; import com.thoughtworks.go.config.policy.SupportedAction; import com.thoughtworks.go.domain.config.ConfigurationKey; import com.thoughtworks.go.domain.config.ConfigurationProperty; import com.thoughtworks.go.domain.config.ConfigurationValue; import com.thoughtworks.go.plugin.access.authorization.AuthorizationMetadataStore; import com.thoughtworks.go.plugin.api.info.PluginDescriptor; import com.thoughtworks.go.plugin.domain.authorization.AuthorizationPluginInfo; import com.thoughtworks.go.plugin.domain.authorization.SupportedAuthType; import com.thoughtworks.go.plugin.domain.common.Metadata; import com.thoughtworks.go.plugin.domain.common.PluggableInstanceSettings; import com.thoughtworks.go.plugin.domain.common.PluginConfiguration; import com.thoughtworks.go.security.CryptoException; import com.thoughtworks.go.security.GoCipher; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import static com.thoughtworks.go.config.policy.SupportedEntity.ENVIRONMENT; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PluginRoleConfigTest { @AfterEach public void teardown() { AuthorizationMetadataStore.instance().clear(); } @Test public void validate_shouldValidatePresenceOfRoleName() { validatePresenceOfRoleName(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { pluginRoleConfig.validate(context); } }); } @Test public void validate_shouldValidateNullRoleName() { validateNullRoleName(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { pluginRoleConfig.validate(context); } }); } @Test public void validate_presenceAuthConfigId() { validatePresenceAuthConfigId(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { pluginRoleConfig.validate(context); } }); } @Test public void validate_presenceOfAuthConfigIdInSecurityConfig() throws Exception { validatePresenceOfAuthConfigIdInSecurityConfig(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { pluginRoleConfig.validate(context); } }); } @Test public void validate_uniquenessOfRoleName() throws Exception { validateUniquenessOfRoleName(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { pluginRoleConfig.validate(context); } }); } @Test public void validateTree_shouldValidatePresenceOfRoleName() { validatePresenceOfRoleName(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { assertFalse(pluginRoleConfig.validateTree(context)); } }); } @Test public void validateTree_shouldValidateNullRoleName() { validateNullRoleName(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { pluginRoleConfig.validateTree(context); } }); } @Test public void validateTree_presenceAuthConfigId() { validatePresenceAuthConfigId(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { assertFalse(pluginRoleConfig.validateTree(context)); } }); } @Test public void validateTree_presenceOfAuthConfigIdInSecurityConfig() throws Exception { validatePresenceOfAuthConfigIdInSecurityConfig(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { assertFalse(pluginRoleConfig.validateTree(context)); } }); } @Test public void validateTree_uniquenessOfRoleName() throws Exception { validateUniquenessOfRoleName(new Validator() { @Override public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) { assertFalse(pluginRoleConfig.validateTree(context)); } }); } @Test public void hasErrors_shouldBeTrueIfRoleHasErrors() throws Exception { Role role = new PluginRoleConfig("", "auth_config_id"); SecurityConfig securityConfig = new SecurityConfig(); securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id")); role.validate(ValidationContextMother.validationContext(securityConfig)); assertTrue(role.hasErrors()); } @Test public void hasErrors_shouldBeTrueIfConfigurationPropertiesHasErrors() throws Exception { ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("view")); PluginRoleConfig roleConfig = new PluginRoleConfig("admin", "auth_id", property); property.addError("username", "username format is incorrect"); assertTrue(roleConfig.hasErrors()); assertTrue(roleConfig.errors().isEmpty()); } @Test public void shouldAnswerWhetherItHasPermissionsForGivenEntityOfTypeAndName() { final Policy directives = new Policy(); directives.add(new Allow("view", ENVIRONMENT.getType(), "env_1")); RoleConfig role = new RoleConfig(new CaseInsensitiveString(""), new Users(), directives); assertTrue(role.hasPermissionsFor(SupportedAction.VIEW, EnvironmentConfig.class, "env_1")); assertFalse(role.hasPermissionsFor(SupportedAction.VIEW, EnvironmentConfig.class, "env_2")); assertFalse(role.hasPermissionsFor(SupportedAction.VIEW, PipelineConfig.class, "*")); } private void validatePresenceOfRoleName(Validator v) { PluginRoleConfig role = new PluginRoleConfig("", "auth_config_id"); SecurityConfig securityConfig = new SecurityConfig(); securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id")); v.validate(role, ValidationContextMother.validationContext(securityConfig)); assertTrue(role.hasErrors()); assertThat(role.errors().size(), is(1)); assertThat(role.errors().get("name").get(0), is("Invalid role name name ''. This must be alphanumeric and can" + " contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.")); } private void validateNullRoleName(Validator v) { PluginRoleConfig role = new PluginRoleConfig("", "auth_config_id"); role.setName(null); SecurityConfig securityConfig = new SecurityConfig(); securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id")); v.validate(role, ValidationContextMother.validationContext(securityConfig)); assertTrue(role.hasErrors()); assertThat(role.errors().size(), is(1)); assertThat(role.errors().get("name").get(0), is("Invalid role name name 'null'. This must be alphanumeric and can" + " contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.")); } public void validatePresenceAuthConfigId(Validator v) { PluginRoleConfig role = new PluginRoleConfig("admin", ""); SecurityConfig securityConfig = new SecurityConfig(); v.validate(role, ValidationContextMother.validationContext(securityConfig)); assertThat(role.errors().size(), is(1)); assertThat(role.errors().get("authConfigId").size(), is(1)); assertThat(role.errors().get("authConfigId").get(0), is("Invalid plugin role authConfigId name ''. This must be alphanumeric and can" + " contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters.")); } public void validatePresenceOfAuthConfigIdInSecurityConfig(Validator v) throws Exception { PluginRoleConfig role = new PluginRoleConfig("admin", "auth_config_id"); SecurityConfig securityConfig = new SecurityConfig(); v.validate(role, ValidationContextMother.validationContext(securityConfig)); assertThat(role.errors().size(), is(1)); assertThat(role.errors().get("authConfigId").size(), is(1)); assertThat(role.errors().get("authConfigId").get(0), is("No such security auth configuration present for id: `auth_config_id`")); } public void validateUniquenessOfRoleName(Validator v) throws Exception { PluginRoleConfig role = new PluginRoleConfig("admin", "auth_config_id"); SecurityConfig securityConfig = new SecurityConfig(); ValidationContext validationContext = ValidationContextMother.validationContext(securityConfig); securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id")); securityConfig.getRoles().add(new RoleConfig(new CaseInsensitiveString("admin"))); securityConfig.getRoles().add(role); v.validate(role, validationContext); assertThat(role.errors().size(), is(1)); assertThat(role.errors().get("name").get(0), is("Role names should be unique. Role with the same name exists.")); } @Test public void shouldEncryptSecurePluginProperties() throws CryptoException { setAuthorizationPluginInfo(); String authConfigId = "auth_config_id"; String pluginId = "cd.go.github"; BasicCruiseConfig basicCruiseConfig = new BasicCruiseConfig(); basicCruiseConfig.server().security().securityAuthConfigs().add(new SecurityAuthConfig(authConfigId, pluginId)); PluginRoleConfig role = new PluginRoleConfig("admin", authConfigId); role.addConfigurations(asList( new ConfigurationProperty(new ConfigurationKey("k1"), new ConfigurationValue("pub_v1")), new ConfigurationProperty(new ConfigurationKey("k2"), new ConfigurationValue("pub_v2")), new ConfigurationProperty(new ConfigurationKey("k3"), new ConfigurationValue("pub_v3")))); GoCipher goCipher = new GoCipher(); assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1")); assertThat(role.getProperty("k1").getValue(), is("pub_v1")); assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2")); assertThat(role.getProperty("k2").getValue(), is("pub_v2")); assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3")); assertThat(role.getProperty("k3").getValue(), is("pub_v3")); role.encryptSecureProperties(basicCruiseConfig); assertThat(role.getProperty("k1").getEncryptedValue(), is(goCipher.encrypt("pub_v1"))); assertThat(role.getProperty("k1").getConfigValue(), is(nullValue())); assertThat(role.getProperty("k1").getValue(), is("pub_v1")); assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2")); assertThat(role.getProperty("k2").getValue(), is("pub_v2")); assertThat(role.getProperty("k3").getEncryptedValue(), is(goCipher.encrypt("pub_v3"))); assertThat(role.getProperty("k3").getConfigValue(), is(nullValue())); assertThat(role.getProperty("k3").getValue(), is("pub_v3")); } @Test public void shouldNotEncryptSecurePluginProperties_WhenPluginInfosIsAbsent() throws CryptoException { String authConfigId = "auth_config_id"; String pluginId = "cd.go.github"; BasicCruiseConfig basicCruiseConfig = new BasicCruiseConfig(); basicCruiseConfig.server().security().securityAuthConfigs().add(new SecurityAuthConfig(authConfigId, pluginId)); PluginRoleConfig role = new PluginRoleConfig("admin", authConfigId); role.addConfigurations(asList( new ConfigurationProperty(new ConfigurationKey("k1"), new ConfigurationValue("pub_v1")), new ConfigurationProperty(new ConfigurationKey("k2"), new ConfigurationValue("pub_v2")), new ConfigurationProperty(new ConfigurationKey("k3"), new ConfigurationValue("pub_v3")))); assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1")); assertThat(role.getProperty("k1").getValue(), is("pub_v1")); assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2")); assertThat(role.getProperty("k2").getValue(), is("pub_v2")); assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3")); assertThat(role.getProperty("k3").getValue(), is("pub_v3")); role.encryptSecureProperties(basicCruiseConfig); assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1")); assertThat(role.getProperty("k1").getValue(), is("pub_v1")); assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2")); assertThat(role.getProperty("k2").getValue(), is("pub_v2")); assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3")); assertThat(role.getProperty("k3").getValue(), is("pub_v3")); } @Test public void shouldNotEncryptSecurePluginProperties_WhenReferencedAuthConfigDoesNotExists() throws CryptoException { setAuthorizationPluginInfo(); String authConfigId = "auth_config_id"; BasicCruiseConfig basicCruiseConfig = new BasicCruiseConfig(); PluginRoleConfig role = new PluginRoleConfig("admin", authConfigId); role.addConfigurations(asList( new ConfigurationProperty(new ConfigurationKey("k1"), new ConfigurationValue("pub_v1")), new ConfigurationProperty(new ConfigurationKey("k2"), new ConfigurationValue("pub_v2")), new ConfigurationProperty(new ConfigurationKey("k3"), new ConfigurationValue("pub_v3")))); assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1")); assertThat(role.getProperty("k1").getValue(), is("pub_v1")); assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2")); assertThat(role.getProperty("k2").getValue(), is("pub_v2")); assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3")); assertThat(role.getProperty("k3").getValue(), is("pub_v3")); role.encryptSecureProperties(basicCruiseConfig); assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1")); assertThat(role.getProperty("k1").getValue(), is("pub_v1")); assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2")); assertThat(role.getProperty("k2").getValue(), is("pub_v2")); assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue())); assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3")); assertThat(role.getProperty("k3").getValue(), is("pub_v3")); } interface Validator { void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context); } private void setAuthorizationPluginInfo() { PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); PluginConfiguration k1 = new PluginConfiguration("k1", new Metadata(false, true)); PluginConfiguration k2 = new PluginConfiguration("k2", new Metadata(false, false)); PluginConfiguration k3 = new PluginConfiguration("k3", new Metadata(false, true)); PluggableInstanceSettings authConfigSettins = new PluggableInstanceSettings(asList(k1, k2, k3)); PluggableInstanceSettings roleConfigSettings = new PluggableInstanceSettings(asList(k1, k2, k3)); com.thoughtworks.go.plugin.domain.authorization.Capabilities capabilities = new com.thoughtworks.go.plugin.domain.authorization.Capabilities(SupportedAuthType.Web, true, true, true); AuthorizationPluginInfo artifactPluginInfo = new AuthorizationPluginInfo(pluginDescriptor, authConfigSettins, roleConfigSettings, null, capabilities); when(pluginDescriptor.id()).thenReturn("cd.go.github"); AuthorizationMetadataStore.instance().setPluginInfo(artifactPluginInfo); } }
{'content_hash': '454914ca9d899c90900f01b24c100a6b', 'timestamp': '', 'source': 'github', 'line_count': 368, 'max_line_length': 190, 'avg_line_length': 49.26358695652174, 'alnum_prop': 0.6927574604225274, 'repo_name': 'arvindsv/gocd', 'id': 'c1ed6c07818014c9c8c20af8db7d9f56eb2ab865', 'size': '18730', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'config/config-api/src/test/java/com/thoughtworks/go/config/PluginRoleConfigTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '466'}, {'name': 'CSS', 'bytes': '797200'}, {'name': 'FreeMarker', 'bytes': '9764'}, {'name': 'Groovy', 'bytes': '2240189'}, {'name': 'HTML', 'bytes': '640932'}, {'name': 'Java', 'bytes': '21023083'}, {'name': 'JavaScript', 'bytes': '2539209'}, {'name': 'NSIS', 'bytes': '23526'}, {'name': 'PowerShell', 'bytes': '691'}, {'name': 'Ruby', 'bytes': '1888167'}, {'name': 'Shell', 'bytes': '169149'}, {'name': 'TSQL', 'bytes': '200114'}, {'name': 'TypeScript', 'bytes': '3070898'}, {'name': 'XSLT', 'bytes': '203240'}]}
export interface Serializable { serialize(): any; deserialize(obj: any): Serializable; }
{'content_hash': '4ab5f5117d91ad8801edfebdc7dce9bb', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 38, 'avg_line_length': 23.25, 'alnum_prop': 0.7311827956989247, 'repo_name': 'hyperboloide/udapi', 'id': '900d3aa2638d992b0fbbe4df75d2b3db385cc4c1', 'size': '94', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/interfaces/basic.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1319'}, {'name': 'Makefile', 'bytes': '525'}, {'name': 'TypeScript', 'bytes': '74865'}]}
Helixcoin 0.8.5 BETA ==================== Copyright (c) 2009-2013 Bitcoin Developers Copyright (c) 2014 Helixcoin Developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](http://www.openssl.org/). This product includes cryptographic software written by Eric Young ([[email protected]](mailto:[email protected])), and UPnP software written by Thomas Bernard. This product also includes software developed by [Crypto++](http://www.cryptopp.com/) which is released under the Boost Software License 1.0. Intro --------------------- Helixcoin is a free open source peer-to-peer electronic cash system that is completely decentralized, without the need for a central server or trusted parties. Users hold the crypto keys to their own money and transact directly with each other, with the help of a P2P network to check for double-spending. Setup --------------------- You need the Qt4 run-time libraries to run Helixcoin-Qt. On Debian or Ubuntu: `sudo apt-get install libqtgui4` Unpack the files into a directory and run: - bin/32/helixcoin-qt (GUI, 32-bit) - bin/32/helixcoind (headless, 32-bit) - bin/64/helixcoin-qt (GUI, 64-bit) - bin/64/helixcoind (headless, 64-bit) See the documentation at the [Bitcoin Wiki](https://en.bitcoin.it/wiki/Main_Page) for help and more information. Other Pages --------------------- - [Unix Build Notes](build-unix.md) - [OSX Build Notes](build-osx.md) - [Windows Build Notes](build-msw.md) - [Coding Guidelines](coding.md) - [Release Process](release-process.md) - [Release Notes](release-notes.md) - [Multiwallet Qt Development](multiwallet-qt.md) - [Unit Tests](unit-tests.md) - [Translation Process](translation_process.md)
{'content_hash': 'd2579d83dec582759ce40ed71db07762', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 280, 'avg_line_length': 39.57446808510638, 'alnum_prop': 0.736021505376344, 'repo_name': 'HelixCoin/HelixCoin', 'id': 'dca34540d20e4381c3cabed1994aaa6a546a1aa3', 'size': '1860', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/README.md', 'mode': '33261', 'license': 'mit', 'language': []}
<?php $strQuery = sprintf("select s.*,sp.seq as publish_seq,sp.start_date,sp.finish_date,unix_timestamp(sp.start_date) as start_time,unix_timestamp(sp.finish_date) as finish_time from test_published as sp join test as s on sp.test_seq=s.seq where sp.seq=%d",$intPublishedSeq); ?>
{'content_hash': '44e903c12eb18b7d2d38ea7b3fc3b49f', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 270, 'avg_line_length': 93.66666666666667, 'alnum_prop': 0.7473309608540926, 'repo_name': 'inkukyang/MamaOMR', 'id': '7d3beafda7e0afbdc697c755df7f69cff51fd91c', 'size': '281', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Model/Tests/SQL/MySQL/Tests/getTestsByPublishedSeq.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '721406'}, {'name': 'HTML', 'bytes': '5867'}, {'name': 'JavaScript', 'bytes': '711879'}, {'name': 'PHP', 'bytes': '646163'}]}
package org.wso2.siddhi.core.table; import org.apache.hadoop.util.bloom.CountingBloomFilter; import org.apache.hadoop.util.bloom.Key; import org.apache.hadoop.util.hash.Hash; import org.apache.log4j.Logger; import org.wso2.siddhi.core.config.SiddhiContext; import org.wso2.siddhi.core.event.*; import org.wso2.siddhi.core.event.in.InEvent; import org.wso2.siddhi.core.event.in.InStateEvent; import org.wso2.siddhi.core.executor.conditon.ConditionExecutor; import org.wso2.siddhi.core.table.cache.CachingTable; import org.wso2.siddhi.core.table.predicate.PredicateToken; import org.wso2.siddhi.core.table.predicate.PredicateTreeNode; import org.wso2.siddhi.core.table.predicate.sql.SQLPredicateBuilder; import org.wso2.siddhi.query.api.definition.Attribute; import org.wso2.siddhi.query.api.definition.TableDefinition; import org.wso2.siddhi.query.api.query.QueryEventSource; import javax.sql.DataSource; import java.nio.ByteBuffer; import java.sql.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class RDBMSEventTable implements EventTable { static final String PARAM_TABLE_NAME = "table.name"; static final String PARAM_DATASOURCE_NAME = "datasource.name"; static final String PARAM_CREATE_QUERY = "create.query"; static final String PARAM_CACHING_ALGORITHM = "caching.algorithm"; static final String PARAM_CACHE_SIZE = "cache.size"; static final String PARAM_CACHE_LOADING = "cache.loading"; static final String PARAM_BLOOM_FILTERS = "bloom.filters"; public static final int BLOOM_FILTER_SIZE = 10000; public static final int BLOOM_FILTER_HASH_FUNCTIONS = 4; static final Logger log = Logger.getLogger(RDBMSEventTable.class); private TableDefinition tableDefinition; private QueryEventSource queryEventSource; // attribute list used for accessing the table. private List<Attribute> attributeList; // full attribute list of the table private boolean eagerCacheLoading; private DataSource dataSource; private String databaseName; private String tableName; private String fullTableName; // schema.tableName private String tableColumnList; // for insertion queries. private boolean isInitialized; // db connection init status private String insertQuery; private boolean bloomFiltersEnabled; private CachingTable cachedTable; // private BloomFilter[] bloomFilters; // bloom filters for each column private CountingBloomFilter[] bloomFilters; public RDBMSEventTable( ) { } public void init(TableDefinition tableDefinition, SiddhiContext siddhiContext) { this.tableDefinition = tableDefinition; this.queryEventSource = new QueryEventSource(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), tableDefinition.getTableId(), tableDefinition, null, null, null); this.dataSource = siddhiContext.getDataSource(tableDefinition.getExternalTable().getParameter(PARAM_DATASOURCE_NAME)); this.attributeList = new ArrayList<Attribute>(); // caching is enabled by default. if ((tableDefinition.getExternalTable().getParameter(PARAM_CACHING_ALGORITHM) != null) && (!tableDefinition.getExternalTable().getParameter(PARAM_CACHING_ALGORITHM).equalsIgnoreCase("disable"))) { this.cachedTable = new CachingTable(tableDefinition.getTableId(), tableDefinition.getExternalTable().getParameter(PARAM_CACHING_ALGORITHM), tableDefinition.getExternalTable().getParameter(PARAM_CACHE_SIZE), siddhiContext); } // cache is by default loaded Lazily if (cachedTable != null && (tableDefinition.getExternalTable().getParameter(PARAM_CACHE_LOADING) != null) && (tableDefinition.getExternalTable().getParameter(PARAM_CACHE_LOADING).equalsIgnoreCase("eager"))) { this.eagerCacheLoading = true; } // bloom filters are disabled by default if ((tableDefinition.getExternalTable().getParameter(PARAM_BLOOM_FILTERS) != null) && (tableDefinition.getExternalTable().getParameter(PARAM_BLOOM_FILTERS).equalsIgnoreCase("enabled"))) { this.bloomFiltersEnabled = true; } try { initializeConnection(); createPreparedStatementQueries(); if (eagerCacheLoading) { preloadCache(); } if (bloomFiltersEnabled) { buildBloomFilters(); } } catch (ClassNotFoundException e) { log.error("Class not found. Can't continue to initialize the table.", e); throw new RuntimeException(e); } catch (Exception e) { log.error("Unable to connect to the database.", e); } } private void initializeConnection() throws SQLException, ClassNotFoundException { if (!isInitialized) { synchronized (this) { // synchronized double checking to ensure this doesn't get hit when there are concurrent calls if (!isInitialized) { Connection con = null; Statement statement = null; try { tableName = tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME); if (dataSource == null) { throw new RuntimeException("Data source doesn't exist: " + tableDefinition.getExternalTable().getParameter(PARAM_DATASOURCE_NAME)); } con = dataSource.getConnection(); // default mysql jdbc driver databaseName = con.getCatalog(); fullTableName = databaseName + "." + tableName; statement = con.createStatement(); String createQuery = tableDefinition.getExternalTable().getParameter(PARAM_CREATE_QUERY); // table creation. if (createQuery == null || createQuery.length() < 1) { StringBuilder stringBuilder = new StringBuilder("CREATE TABLE IF NOT EXISTS "); stringBuilder.append(fullTableName); stringBuilder.append(" ("); boolean appendComma = false; for (Attribute column : tableDefinition.getAttributeList()) { if (appendComma) { stringBuilder.append(", "); } else { appendComma = true; } stringBuilder.append(column.getName()); stringBuilder.append(" "); switch (column.getType()) { case INT: stringBuilder.append("INT"); break; case LONG: stringBuilder.append("BIGINT"); break; case FLOAT: stringBuilder.append("DECIMAL(30,10)"); break; case DOUBLE: stringBuilder.append("DECIMAL(40,15)"); break; case BOOL: stringBuilder.append("BOOL"); break; default: stringBuilder.append("VARCHAR(255)"); break; } } stringBuilder.append(");"); createQuery = stringBuilder.toString(); statement.execute(createQuery); } else { // users may not use 'IF NOT EXISTS' clause, so need to check whether the table exists before // executing their create queries. try { statement.execute("SELECT 1 FROM " + fullTableName + " LIMIT 1"); } catch (SQLException e) { statement.execute(createQuery); } } StringBuilder builder = new StringBuilder("("); boolean appendComma = false; for (Attribute att : tableDefinition.getAttributeList()) { attributeList.add(att); if (appendComma) { builder.append(","); } builder.append(att.getName()); appendComma = true; } builder.append(")"); tableColumnList = builder.toString(); isInitialized = true; } finally { cleanUpConnections(statement, con); } } } } } private synchronized void buildBloomFilters() { this.bloomFilters = new CountingBloomFilter[tableDefinition.getAttributeList().size()]; for (int i = 0; i < bloomFilters.length; i++) { // number of hashes: 4 bloomFilters[i] = new CountingBloomFilter(BLOOM_FILTER_SIZE, BLOOM_FILTER_HASH_FUNCTIONS, Hash.MURMUR_HASH); } Connection con = null; Statement stmt = null; try { con = dataSource.getConnection(); stmt = con.createStatement(); ResultSet results = stmt.executeQuery("SELECT * FROM " + fullTableName); int count = 0; while (results.next()) { count++; for (int i = 0; i < bloomFilters.length; i++) { switch (tableDefinition.getAttributeList().get(i).getType()) { case INT: bloomFilters[i].add(new Key(Integer.toString(results.getInt(i + 1)).getBytes())); break; case LONG: bloomFilters[i].add(new Key(Long.toString(results.getLong(i + 1)).getBytes())); break; case FLOAT: bloomFilters[i].add(new Key(Float.toString(results.getFloat(i + 1)).getBytes())); break; case DOUBLE: bloomFilters[i].add(new Key(Double.toString(results.getDouble(i + 1)).getBytes())); break; case STRING: bloomFilters[i].add(new Key(results.getString(i + 1).getBytes())); break; case BOOL: bloomFilters[i].add(new Key(Boolean.toString(results.getBoolean(i + 1)).getBytes())); break; } } } results.close(); } catch (Exception ex) { log.error(ex); } finally { cleanUpConnections(stmt, con); } } @Override public TableDefinition getTableDefinition() { return tableDefinition; } @Override public void add(StreamEvent streamEvent) { Connection con = null; PreparedStatement statement = null; try { initializeConnection(); con = dataSource.getConnection(); con.setAutoCommit(false); statement = con.prepareStatement(insertQuery); ArrayList<Event> bloomFilterInsertionList = null; if (bloomFiltersEnabled) { bloomFilterInsertionList = new ArrayList<Event>(); } if (streamEvent instanceof AtomicEvent) { populateInsertQuery((Event) streamEvent, statement); statement.executeUpdate(); if (bloomFiltersEnabled) { bloomFilterInsertionList.add((Event) streamEvent); } } else { ListEvent listEvent = ((ListEvent) streamEvent); for (int i = 0, size = listEvent.getActiveEvents(); i < size; i++) { populateInsertQuery(listEvent.getEvent(i), statement); statement.addBatch(); if (bloomFiltersEnabled) { bloomFilterInsertionList.add(listEvent.getEvent(i)); } } statement.executeBatch(); } con.commit(); if (cachedTable != null) { cachedTable.add(streamEvent); } if (bloomFiltersEnabled) { addToBloomFilters(bloomFilterInsertionList); } } catch (SQLException e) { log.error("Unable to insert the records to the table", e); } catch (Exception e) { log.error("Error while inserting data.", e); } finally { cleanUpConnections(statement, con); } } private void addToBloomFilters(List<Event> eventList) { for (Event event : eventList) { for (int i = 0; i < attributeList.size(); i++) { Attribute at = attributeList.get(i); switch (at.getType()) { case INT: bloomFilters[i].add(new Key(Integer.toString((Integer) event.getData(i)).getBytes())); break; case LONG: bloomFilters[i].add(new Key(Long.toString((Long) event.getData(i)).getBytes())); break; case FLOAT: bloomFilters[i].add(new Key(Float.toString((Float) event.getData(i)).getBytes())); break; case DOUBLE: bloomFilters[i].add(new Key(Double.toString((Double) event.getData(i)).getBytes())); break; case STRING: bloomFilters[i].add(new Key(event.getData(i).toString().getBytes())); break; case BOOL: bloomFilters[i].add(new Key(Boolean.toString((Boolean) event.getData(i)).getBytes())); break; } } } } private void removeFromBloomFilters(List<Event> eventList) { for (Event event : eventList) { for (int i = 0; i < attributeList.size(); i++) { Attribute at = attributeList.get(i); switch (at.getType()) { case INT: bloomFilters[i].delete(new Key(ByteBuffer.allocate(4).putInt((Integer) event.getData(i)).array())); break; case LONG: bloomFilters[i].delete(new Key(ByteBuffer.allocate(8).putLong((Long) event.getData(i)).array())); break; case FLOAT: bloomFilters[i].delete(new Key(ByteBuffer.allocate(4).putFloat((Float) event.getData(i)).array())); break; case DOUBLE: bloomFilters[i].delete(new Key(ByteBuffer.allocate(8).putDouble((Double) event.getData(i)).array())); break; case STRING: bloomFilters[i].delete(new Key(event.getData(i).toString().getBytes())); break; case BOOL: bloomFilters[i].delete(new Key(Boolean.toString((Boolean) event.getData(i)).getBytes())); break; } } } } private void preloadCache() { Connection con = null; Statement statement = null; try { con = dataSource.getConnection(); statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM " + fullTableName + " LIMIT 0, " + cachedTable.getCacheLimit()); resultSet.setFetchSize(cachedTable.getCacheLimit()); List<StreamEvent> eventList = new ArrayList<StreamEvent>(); long timestamp = System.currentTimeMillis(); while (resultSet.next()) { Object[] data = new Object[attributeList.size()]; for (int i = 0; i < attributeList.size(); i++) { switch (attributeList.get(i).getType()) { case BOOL: data[i] = resultSet.getBoolean(attributeList.get(i).getName()); break; case DOUBLE: data[i] = resultSet.getDouble(attributeList.get(i).getName()); break; case FLOAT: data[i] = resultSet.getFloat(attributeList.get(i).getName()); break; case INT: data[i] = resultSet.getInt(attributeList.get(i).getName()); break; case LONG: data[i] = resultSet.getLong(attributeList.get(i).getName()); break; case STRING: data[i] = resultSet.getString(attributeList.get(i).getName()); break; default: data[i] = resultSet.getObject(attributeList.get(i).getName()); } } Event event = new InEvent(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), timestamp, data); eventList.add(event); } if (cachedTable != null) { cachedTable.addAll(eventList); // checking whether the table size is equal to the current cache size ResultSet resultCount = statement.executeQuery("SELECT COUNT(*) FROM " + fullTableName); int rowCount = 0; while (resultCount.next()) { rowCount = resultCount.getInt(1); } if (rowCount <= cachedTable.getCacheLimit()) { // this is later used for optimizations when reading cachedTable.setFullyLoaded(true); } resultCount.close(); } resultSet.close(); } catch (SQLException e) { log.error("Unable to read the table: " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e); } finally { cleanUpConnections(statement, con); } } private void populateInsertQuery(Event event, PreparedStatement statement) throws SQLException { for (int i = 0; i < attributeList.size(); i++) { switch (attributeList.get(i).getType()) { case INT: statement.setInt(i + 1, ((Number) event.getData(i)).intValue()); break; case LONG: statement.setLong(i + 1, ((Number) event.getData(i)).longValue()); break; case FLOAT: statement.setFloat(i + 1, ((Number) event.getData(i)).floatValue()); break; case DOUBLE: statement.setDouble(i + 1, ((Number) event.getData(i)).doubleValue()); break; case BOOL: statement.setBoolean(i + 1, (Boolean) event.getData(i)); break; default: statement.setString(i + 1, event.getData(i).toString()); break; } } } private void createPreparedStatementQueries() { // only the insert query can be created since update, delete have query-specific predicates StringBuilder builder = new StringBuilder("INSERT INTO "); builder.append(fullTableName); builder.append(tableColumnList); builder.append(" VALUES ("); for (int i = 0; i < attributeList.size(); i++) { if (i > 0) { builder.append(", "); } builder.append("?"); } builder.append(")"); insertQuery = builder.toString(); } @Override public void delete(StreamEvent streamEvent, ConditionExecutor conditionExecutor) { PreparedStatement statement = null; Connection con = null; try { initializeConnection(); con = dataSource.getConnection(); con.setAutoCommit(false); StringBuilder statementBuilder = new StringBuilder("DELETE FROM "); statementBuilder.append(fullTableName); statementBuilder.append(" WHERE "); ArrayList<Event> bloomFilterDeletionList = null; if (bloomFiltersEnabled) { bloomFilterDeletionList = new ArrayList<Event>(); } if (streamEvent instanceof AtomicEvent) { PredicateTreeNode predicate = conditionExecutor.constructPredicate((Event) streamEvent, tableDefinition, new SQLPredicateBuilder()); statementBuilder.append(predicate.buildPredicateString()); statement = con.prepareStatement(statementBuilder.toString()); ArrayList paramList = new ArrayList(); predicate.populateParameters(paramList); for (int i = 0; i < paramList.size(); i++) { populateStatement(statement, i + 1, paramList.get(i)); } if (bloomFiltersEnabled) { bloomFilterDeletionList.add((Event) streamEvent); } statement.executeUpdate(); } else { for (int i = 0, size = ((ListEvent) streamEvent).getActiveEvents(); i < size; i++) { // deleting the entire event set using an aggregate query with OR conditions if (i > 0) { statementBuilder.append(" OR "); } statementBuilder.append("("); statementBuilder.append(conditionExecutor.constructPredicate(((ListEvent) streamEvent).getEvent(i), tableDefinition, new SQLPredicateBuilder()).buildPredicateString()); statementBuilder.append(")"); if (bloomFiltersEnabled) { bloomFilterDeletionList.add(((ListEvent) streamEvent).getEvent(i)); } } statement = con.prepareStatement(statementBuilder.toString()); statement.executeUpdate(); } con.commit(); if (cachedTable != null) { cachedTable.delete(streamEvent, conditionExecutor); } if (bloomFiltersEnabled) { removeFromBloomFilters(bloomFilterDeletionList); } } catch (SQLException e) { log.error("Unable to execute deletion.", e); } catch (ClassNotFoundException e) { log.error("Unable to load the database driver.", e); } finally { cleanUpConnections(statement, con); } } @Override public void update(StreamEvent streamEvent, ConditionExecutor conditionExecutor, int[] attributeUpdateMappingPosition) { Connection con = null; PreparedStatement statement = null; try { initializeConnection(); con = dataSource.getConnection(); con.setAutoCommit(false); Event atomicEvent = null; SQLPredicateBuilder predicateBuilder = new SQLPredicateBuilder(); if (streamEvent instanceof AtomicEvent) { atomicEvent = (Event) streamEvent; // used to execute the condition executor } else { if (((ListEvent) streamEvent).getActiveEvents() > 0) { atomicEvent = ((ListEvent) streamEvent).getEvent(0); } } PredicateTreeNode predicate = conditionExecutor.constructPredicate(atomicEvent, tableDefinition, predicateBuilder); String query = createUpdateQuery(predicate.buildPredicateString(), attributeUpdateMappingPosition); statement = con.prepareStatement(query); ArrayList paramList = new ArrayList(); if (streamEvent instanceof AtomicEvent) { for (int i = 0; i < attributeUpdateMappingPosition.length; i++) { populateStatement(statement, i + 1, atomicEvent.getData(i)); } predicate.populateParameters(paramList); for (int i = 0; i < paramList.size(); i++) { populateStatement(statement, attributeUpdateMappingPosition.length + i + 1, paramList.get(i)); } statement.executeUpdate(); } else { // streamEvent instanceof ListEvent statement.clearParameters(); for (int j = 0, size = ((ListEvent) streamEvent).getActiveEvents(); j < size; j++) { Event event = ((ListEvent) streamEvent).getEvent(j); predicate = conditionExecutor.constructPredicate(event, tableDefinition, predicateBuilder); paramList.clear(); predicate.populateParameters(paramList); for (int i = 0; i < attributeList.size(); i++) { populateStatement(statement, i + 1, event.getData(i)); } for (int i = 0; i < paramList.size(); i++) { populateStatement(statement, attributeList.size() + i + 1, paramList.get(i)); } statement.addBatch(); } statement.executeBatch(); } con.commit(); if (cachedTable != null) { cachedTable.update(streamEvent, conditionExecutor, attributeUpdateMappingPosition); } if (bloomFiltersEnabled) { buildBloomFilters(); } } catch (SQLException e) { log.error("Unable to execute update on " + streamEvent, e); } catch (ClassNotFoundException e) { log.error("Unable to load the database driver for " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e); } finally { cleanUpConnections(statement, con); } } @Override public boolean contains(AtomicEvent atomicEvent, ConditionExecutor conditionExecutor) { PredicateTreeNode predicate = null; if (bloomFiltersEnabled) { // bloom filters used only for the equal conditions. predicate = conditionExecutor.constructPredicate(atomicEvent, tableDefinition, new SQLPredicateBuilder()); ArrayList<PredicateToken> tokenList = new ArrayList<PredicateToken>(3); predicate.populateTokens(tokenList); // looking for two sided equals conditions (operators) only. if (tokenList.size() < 4) { // not using bloom filters for complex conditions for (int operatorIndex = 1; operatorIndex < tokenList.size() - 1; operatorIndex++) { // at this level the operator becomes '=' instead of '==' if (tokenList.get(operatorIndex).getGetTokenType() == PredicateToken.Type.OPERATOR && tokenList.get(operatorIndex).getTokenValue().trim().equals("=")) { // param and value can be in any order i.e. price = 3 or 1 = price. this is to handle such scenarios. String param = tokenList.get(operatorIndex - 1).getGetTokenType() == PredicateToken.Type.VARIABLE ? tokenList.get(operatorIndex - 1).getTokenValue().trim() : tokenList.get(operatorIndex + 1).getTokenValue().toString().trim(); String value = tokenList.get(operatorIndex - 1).getGetTokenType() == PredicateToken.Type.VARIABLE ? tokenList.get(operatorIndex + 1).getTokenValue().toString().trim() : tokenList.get(operatorIndex - 1).getTokenValue().trim(); for (int i = 0; i < attributeList.size(); i++) { if (attributeList.get(i).getName().equals(param)) { boolean mightContain = bloomFilters[i].membershipTest(new Key(value.getBytes())); if (!mightContain) { return false; } } } } } } } if ((cachedTable != null) && cachedTable.contains(atomicEvent, conditionExecutor)) { return true; } else { Connection con = null; PreparedStatement statement = null; try { initializeConnection(); if (predicate == null) { predicate = conditionExecutor.constructPredicate(atomicEvent, tableDefinition, new SQLPredicateBuilder()); } con = dataSource.getConnection(); // need to construct this each time since there are multiple queries and their predicates differ. statement = con.prepareStatement("SELECT * FROM " + fullTableName + " WHERE " + predicate.buildPredicateString() + " LIMIT 0,1"); ArrayList paramList = new ArrayList(); predicate.populateParameters(paramList); for (int i = 0; i < paramList.size(); i++) { populateStatement(statement, i + 1, paramList.get(i)); } ResultSet resultSet = statement.executeQuery(); boolean contains = false; long timestamp = System.currentTimeMillis(); while (resultSet.next()) { contains = true; if (cachedTable != null) { Object[] data = new Object[attributeList.size()]; for (int i = 0; i < attributeList.size(); i++) { switch (attributeList.get(i).getType()) { case BOOL: data[i] = resultSet.getBoolean(attributeList.get(i).getName()); break; case DOUBLE: data[i] = resultSet.getDouble(attributeList.get(i).getName()); break; case FLOAT: data[i] = resultSet.getFloat(attributeList.get(i).getName()); break; case INT: data[i] = resultSet.getInt(attributeList.get(i).getName()); break; case LONG: data[i] = resultSet.getLong(attributeList.get(i).getName()); break; case STRING: data[i] = resultSet.getString(attributeList.get(i).getName()); break; default: data[i] = resultSet.getObject(attributeList.get(i).getName()); } } // lazy loading caches since we've already read the event Event event = new InEvent(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), timestamp, data); cachedTable.add(event); } else { break; } } resultSet.close(); return contains; } catch (SQLException e) { log.error("Can't read the database table: " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e); } catch (Exception e) { log.error("Can't connect to the database.", e); } finally { cleanUpConnections(statement, con); } return false; } } private String createUpdateQuery(String predicate, int[] attributeMappingPositions) { StringBuilder statementBuilder = new StringBuilder("UPDATE "); statementBuilder.append(fullTableName); statementBuilder.append(" SET "); for (int i = 0; i < attributeMappingPositions.length; i++) { if (i > 0) { statementBuilder.append(", "); } statementBuilder.append(attributeList.get(attributeMappingPositions[i]).getName()); statementBuilder.append(" = ?"); } statementBuilder.append(" WHERE "); if (predicate != null) { statementBuilder.append(predicate); } return statementBuilder.toString(); } @Override public QueryEventSource getQueryEventSource() { return queryEventSource; } @Override public Iterator<StreamEvent> iterator(StreamEvent event, ConditionExecutor conditionExecutor) { if (cachedTable != null && cachedTable.isFullyLoaded()) { if (event instanceof AtomicEvent) { synchronized (this) { ArrayList<StreamEvent> resultEvents = new ArrayList<StreamEvent>(); Iterator<StreamEvent> iterator = cachedTable.iterator(); StateEvent stateEvent = new InStateEvent(new StreamEvent[2]); stateEvent.setStreamEvent(0, event); while (iterator.hasNext()) { StreamEvent cachedEvent = iterator.next(); stateEvent.setStreamEvent(1, cachedEvent); if (conditionExecutor.execute(stateEvent)) { resultEvents.add(cachedEvent); } } return resultEvents.iterator(); } } } PredicateTreeNode predicate = conditionExecutor.constructPredicate((AtomicEvent) event, tableDefinition, new SQLPredicateBuilder()); String sqlPredicate = predicate.buildPredicateString(); if (sqlPredicate.trim().equals("?")) { return iterator(); } ArrayList paramList = new ArrayList(); predicate.populateParameters(paramList); for (int i = 0; i < paramList.size(); i++) { Object value = paramList.get(i); if (value != null) { value = value.toString().replaceAll("'", "''"); } sqlPredicate = sqlPredicate.replaceFirst("\\?", "'" + value.toString() + "'"); // populate one by one. } return iterator(sqlPredicate); } @Override public Iterator<StreamEvent> iterator(String sqlPredicate) { Connection con = null; Statement statement = null; try { con = dataSource.getConnection(); statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM " + fullTableName + ((sqlPredicate == null) ? "" : (" WHERE " + sqlPredicate))); resultSet.setFetchSize(10000); ArrayList<StreamEvent> eventList = new ArrayList<StreamEvent>(); long timestamp = System.currentTimeMillis(); while (resultSet.next()) { Object[] data = new Object[attributeList.size()]; for (int i = 0; i < attributeList.size(); i++) { switch (attributeList.get(i).getType()) { case BOOL: data[i] = resultSet.getBoolean(attributeList.get(i).getName()); break; case DOUBLE: data[i] = resultSet.getDouble(attributeList.get(i).getName()); break; case FLOAT: data[i] = resultSet.getFloat(attributeList.get(i).getName()); break; case INT: data[i] = resultSet.getInt(attributeList.get(i).getName()); break; case LONG: data[i] = resultSet.getLong(attributeList.get(i).getName()); break; case STRING: data[i] = resultSet.getString(attributeList.get(i).getName()); break; default: data[i] = resultSet.getObject(attributeList.get(i).getName()); } } Event event = new InEvent(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), timestamp, data); eventList.add(event); } resultSet.close(); return eventList.iterator(); } catch (SQLException e) { log.error("Unable to read the table: " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e); } finally { cleanUpConnections(statement, con); } return null; } @Override public Iterator<StreamEvent> iterator() { return iterator(null); } private void cleanUpConnections(Statement stmt, Connection con) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { log.error("unable to release statement", e); } } if (con != null) { try { con.close(); } catch (SQLException e) { log.error("unable to release connection", e); } } } private void populateStatement(PreparedStatement stmt, int index, Object value) throws SQLException { if (value instanceof String) { stmt.setString(index, (String) value); } else if (value instanceof Integer) { stmt.setInt(index, (Integer) value); } else if (value instanceof Double) { stmt.setDouble(index, (Double) value); } else if (value instanceof Boolean) { stmt.setBoolean(index, (Boolean) value); } else if (value instanceof Float) { stmt.setFloat(index, (Float) value); } else if (value instanceof Long) { stmt.setLong(index, (Long) value); } else { stmt.setString(index, (String) value); } } }
{'content_hash': 'eca1e6b1fbf0b38d55ff8bb9f57edf40', 'timestamp': '', 'source': 'github', 'line_count': 873, 'max_line_length': 234, 'avg_line_length': 45.49942726231386, 'alnum_prop': 0.5168550640719015, 'repo_name': 'mohanvive/siddhi-2.x', 'id': 'ad3e241de9fbf76dab438ac0eb4477e38e6cc5db', 'size': '40388', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'modules/siddhi-core/src/main/java/org/wso2/siddhi/core/table/RDBMSEventTable.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2652'}, {'name': 'GAP', 'bytes': '42178'}, {'name': 'Java', 'bytes': '2547522'}]}
4.0 Functional Description ========================== .. toctree:: :glob: digital tri_state_1 tri_state_2 input_only analog power
{'content_hash': 'cbab8dfcf66b2ed6cbd83bf955d01c4d', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 26, 'avg_line_length': 11.571428571428571, 'alnum_prop': 0.4876543209876543, 'repo_name': 'google/globalfoundries-pdk-libs-gf180mcu_fd_io', 'id': 'e89404fb719bae6804e7feb64018d63f8ba45343', 'size': '162', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'docs/functional.rst', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Verilog', 'bytes': '16964'}]}
package com.innovez.sample; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc @ComponentScan(basePackages="com.innovez.sample.web") public class WebappConfiguration extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/assets/**").addResourceLocations("/WEB-INF/assets/**"); } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("/WEB-INF/templates/index.html"); registry.addViewController("/employee").setViewName("/WEB-INF/views/employees.html"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
{'content_hash': 'ce5debbfdda4bd2b2bafbe42a7122cbb', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 90, 'avg_line_length': 42.03333333333333, 'alnum_prop': 0.8350515463917526, 'repo_name': 'zakyalvan/spring-envers-audit', 'id': 'e720db959e41fcb6382cb922554a08e334b74c3c', 'size': '1261', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-envers-audit-sample/src/main/java/com/innovez/sample/WebappConfiguration.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '46039'}]}
class Announcement < ActiveRecord::Base named_scope :active, lambda { { :conditions => ['starts_at <= ? AND ends_at >= ?', Time.now.utc, Time.now.utc] } } named_scope :since, lambda { |hide_time| { :conditions => (hide_time ? ['updated_at > ? OR starts_at > ?', hide_time.utc, hide_time.utc] : nil) } } def self.display(hide_time) active.since(hide_time) end end
{'content_hash': '90ca176f2d7f8d5ee3855e2fa04859d7', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 149, 'avg_line_length': 38.4, 'alnum_prop': 0.625, 'repo_name': 'agileblaze/RFP', 'id': '13c06d8fd20810781b97b938af9c2a7b929ad62d', 'size': '384', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/models/announcement.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '64000'}, {'name': 'ColdFusion', 'bytes': '169639'}, {'name': 'JavaScript', 'bytes': '2145502'}, {'name': 'PHP', 'bytes': '67590'}, {'name': 'Perl', 'bytes': '38659'}, {'name': 'Python', 'bytes': '47611'}, {'name': 'Ruby', 'bytes': '174303'}, {'name': 'Shell', 'bytes': '1704'}]}
tinymce.dom.TreeWalker = function(start_node, root_node) { var node = start_node; function findSibling(node, start_name, sibling_name, shallow) { var sibling, parent; if (node) { // Walk into nodes if it has a start if (!shallow && node[start_name]) return node[start_name]; // Return the sibling if it has one if (node != root_node) { sibling = node[sibling_name]; if (sibling) return sibling; // Walk up the parents to look for siblings for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) { sibling = parent[sibling_name]; if (sibling) return sibling; } } } }; /** * Returns the current node. * * @return {Node} Current node where the walker is. */ this.current = function() { return node; }; /** * Walks to the next node in tree. * * @return {Node} Current node where the walker is after moving to the next node. */ this.next = function(shallow) { return (node = findSibling(node, 'firstChild', 'nextSibling', shallow)); }; /** * Walks to the previous node in tree. * * @return {Node} Current node where the walker is after moving to the previous node. */ this.prev = function(shallow) { return (node = findSibling(node, 'lastChild', 'lastSibling', shallow)); }; };
{'content_hash': '6c5909cd113751688918b22d0f09553b', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 95, 'avg_line_length': 24.642857142857142, 'alnum_prop': 0.6115942028985507, 'repo_name': 'nathanvda/substructd', 'id': 'c7fc06047c66ea7eed2529b11b3a1514f3311e7b', 'size': '1598', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'assets/javascripts/tiny_mce/classes/dom/TreeWalker.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '5998'}, {'name': 'Ruby', 'bytes': '304980'}]}
package com.fangzhou.manatee.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import java.io.Serializable; import java.util.Objects; /** * A Team. */ @Entity @Table(name = "team") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Team implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "organization") private String organization; @Column(name = "name") private String name; @Column(name = "specialty") private String specialty; @Column(name = "max_patients") private Long maxPatients; @Column(name = "monday") private Long monday; @Column(name = "tuesday") private Long tuesday; @Column(name = "wednesday") private Long wednesday; @Column(name = "thursday") private Long thursday; @Column(name = "friday") private Long friday; @Column(name = "saturday") private Long saturday; @Column(name = "sunday") private Long sunday; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSpecialty() { return specialty; } public void setSpecialty(String specialty) { this.specialty = specialty; } public Long getMaxPatients() { return maxPatients; } public void setMaxPatients(Long maxPatients) { this.maxPatients = maxPatients; } public Long getMonday() { return monday; } public void setMonday(Long monday) { this.monday = monday; } public Long getTuesday() { return tuesday; } public void setTuesday(Long tuesday) { this.tuesday = tuesday; } public Long getWednesday() { return wednesday; } public void setWednesday(Long wednesday) { this.wednesday = wednesday; } public Long getThursday() { return thursday; } public void setThursday(Long thursday) { this.thursday = thursday; } public Long getFriday() { return friday; } public void setFriday(Long friday) { this.friday = friday; } public Long getSaturday() { return saturday; } public void setSaturday(Long saturday) { this.saturday = saturday; } public Long getSunday() { return sunday; } public void setSunday(Long sunday) { this.sunday = sunday; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Team team = (Team) o; if(team.id == null || id == null) { return false; } return Objects.equals(id, team.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Team{" + "id=" + id + ", organization='" + organization + "'" + ", name='" + name + "'" + ", specialty='" + specialty + "'" + ", maxPatients='" + maxPatients + "'" + ", monday='" + monday + "'" + ", tuesday='" + tuesday + "'" + ", wednesday='" + wednesday + "'" + ", thursday='" + thursday + "'" + ", friday='" + friday + "'" + ", saturday='" + saturday + "'" + ", sunday='" + sunday + "'" + '}'; } }
{'content_hash': 'c29538662c0d78abd1ac89f3c139b61a', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 61, 'avg_line_length': 21.063157894736843, 'alnum_prop': 0.5594702648675662, 'repo_name': 'magnumresearch/manatee', 'id': '15c62a5999e3a4d89840ab120f28f7b9c61da425', 'size': '4002', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/fangzhou/manatee/domain/Team.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15472'}, {'name': 'Dockerfile', 'bytes': '312'}, {'name': 'HTML', 'bytes': '171124'}, {'name': 'Java', 'bytes': '328631'}, {'name': 'JavaScript', 'bytes': '242731'}, {'name': 'Scala', 'bytes': '17164'}]}
{% extends "base_site.html" %} {% block title %}Meetings{% endblock %} {% block extrahead %}{{ block.super }} <link rel="stylesheet" type="text/css" href="{{ SECR_STATIC_URL }}css/jquery-ui-1.8.1.custom.css" /> <link rel="stylesheet" type="text/css" href="{{ SECR_STATIC_URL }}css/jquery.ui.autocomplete.css" /> <script type="text/javascript" src="{{ SECR_STATIC_URL }}js/jquery-ui-1.8.1.custom.min.js"></script> <script type="text/javascript" src="{{ SECR_STATIC_URL }}js/utils.js"></script> <script type="text/javascript" src="{{ SECR_STATIC_URL }}js/dynamic_inlines.js"></script> {% endblock %} {% block breadcrumbs %}{{ block.super }} &raquo; <a href="../../">Meetings</a> &raquo; <a href="../">{{ meeting.number }}</a> &raquo; Rooms and Times {% endblock %} {% block content %} <div id="nav" class="rooms-times-nav"> <ul id="list-nav"> <li id="nav-room" class="leftmost"><a href="{% url meetings_rooms meeting_id=meeting.number %}">Rooms</a></li> <li id="nav-time"><a href="{% url meetings_times meeting_id=meeting.number %}">Times</a></li> <li id="nav-non-session"><a href="{% url meetings_non_session meeting_id=meeting.number %}">Non-Session</a></li> </ul> </div> {% block subsection %}{% endblock %} {% endblock %}
{'content_hash': '04f4dd448eff362552fad3529e724a8a', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 116, 'avg_line_length': 39.53125, 'alnum_prop': 0.6324110671936759, 'repo_name': 'mcr/ietfdb', 'id': '4d56537993ac11b94f707e1e769ea91576a66d7d', 'size': '1265', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ietf/secr/templates/meetings/base_rooms_times.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '239198'}, {'name': 'JavaScript', 'bytes': '450755'}, {'name': 'Perl', 'bytes': '3223'}, {'name': 'Python', 'bytes': '10286676'}, {'name': 'Ruby', 'bytes': '3468'}, {'name': 'Shell', 'bytes': '39950'}, {'name': 'TeX', 'bytes': '23944'}]}
module Projects class ForkService < BaseService def execute(fork_to_project = nil) if fork_to_project link_existing_project(fork_to_project) else fork_new_project end end private def allowed_fork? current_user.can?(:fork_project, @project) end def link_existing_project(fork_to_project) return if fork_to_project.forked? build_fork_network_member(fork_to_project) if link_fork_network(fork_to_project) # A forked project stores its LFS objects in the `forked_from_project`. # So the LFS objects become inaccessible, and therefore delete them from # the database so they'll get cleaned up. # # TODO: refactor this to get the correct lfs objects when implementing # https://gitlab.com/gitlab-org/gitlab-ce/issues/39769 fork_to_project.lfs_objects_projects.delete_all fork_to_project end end def fork_new_project new_params = { visibility_level: allowed_visibility_level, description: @project.description, name: @project.name, path: @project.path, shared_runners_enabled: @project.shared_runners_enabled, namespace_id: target_namespace.id, fork_network: fork_network, # We need to assign the fork network membership after the project has # been instantiated to avoid ActiveRecord trying to create it when # initializing the project, as that would cause a foreign key constraint # exception. relations_block: -> (project) { build_fork_network_member(project) } } if @project.avatar.present? && @project.avatar.image? new_params[:avatar] = @project.avatar end new_params.merge!(@project.object_pool_params) new_project = CreateService.new(current_user, new_params).execute return new_project unless new_project.persisted? # Set the forked_from_project relation after saving to avoid having to # reload the project to reset the association information and cause an # extra query. new_project.forked_from_project = @project builds_access_level = @project.project_feature.builds_access_level new_project.project_feature.update(builds_access_level: builds_access_level) new_project end def fork_network @fork_network ||= @project.fork_network || @project.build_root_of_fork_network end def build_fork_network_member(fork_to_project) if allowed_fork? fork_to_project.build_fork_network_member(forked_from_project: @project, fork_network: fork_network) else fork_to_project.errors.add(:forked_from_project_id, 'is forbidden') end end def link_fork_network(fork_to_project) return if fork_to_project.errors.any? fork_to_project.fork_network_member.save && refresh_forks_count end def refresh_forks_count Projects::ForksCountService.new(@project).refresh_cache end def target_namespace @target_namespace ||= @params[:namespace] || current_user.namespace end def allowed_visibility_level target_level = [@project.visibility_level, target_namespace.visibility_level].min Gitlab::VisibilityLevel.closest_allowed_level(target_level) end end end
{'content_hash': '74ad4dcaad161f38d28ecab483c0f913', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 87, 'avg_line_length': 33.08571428571429, 'alnum_prop': 0.6450777202072538, 'repo_name': 'axilleas/gitlabhq', 'id': '91091c4393dc1dbcabe2e2d69f24758586232ec8', 'size': '3505', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/services/projects/fork_service.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '683690'}, {'name': 'Clojure', 'bytes': '79'}, {'name': 'Dockerfile', 'bytes': '1907'}, {'name': 'HTML', 'bytes': '1340167'}, {'name': 'JavaScript', 'bytes': '4309733'}, {'name': 'Ruby', 'bytes': '19732082'}, {'name': 'Shell', 'bytes': '44575'}, {'name': 'Vue', 'bytes': '1040466'}]}