{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \"),n.close(),g.iframeHeight&&(r=!0,setTimeout(function(){r=!1,i()},3e3)),d(m).on(\"load\",i).on(\"unload\",j),o=m.MutationObserver||m.WebKitMutationObserver||m.MozMutationObserver)n.body?k():n.addEventListener(\"DOMContentLoaded\",k,!1);else for(q=1;q<6;q++)setTimeout(i,700*q);e&&e.call(g,f,h)}},f)},setLoader:function(a){this.setContent('
')},setError:function(a,b){this.setContent('

'+a+\"

\")},match:function(a){var b=c.next(this.type,a);if(b)return{index:b.index,content:b.content,options:{shortcode:b.shortcode}}},update:function(a,c,f,g){_.find(e,function(e,h){var i=e.prototype.match(a);if(i)return d(f).data(\"rendered\",!1),c.dom.setAttrib(f,\"data-wpview-text\",encodeURIComponent(a)),b.mce.views.createInstance(h,a,i.options,g).render(),c.focus(),!0})},remove:function(a,b){this.unbindNode.call(this,a,b),a.dom.remove(b),a.focus()}})}(window,window.wp,window.wp.shortcode,window.jQuery),function(a,b,c,d){function e(b){var c={};return a.tinymce?!b||b.indexOf(\"<\")===-1&&b.indexOf(\">\")===-1?b:(j=j||new a.tinymce.html.Schema(c),k=k||new a.tinymce.html.DomParser(c,j),l=l||new a.tinymce.html.Serializer(c,j),l.serialize(k.parse(b,{forced_root_block:!1}))):b.replace(/<[^>]+>/g,\"\")}var f,g,h,i,j,k,l;f={state:[],edit:function(a,b){var d=this.type,e=c[d].edit(a);this.pausePlayers&&this.pausePlayers(),_.each(this.state,function(a){e.state(a).on(\"update\",function(a){b(c[d].shortcode(a).string(),\"gallery\"===d)})}),e.on(\"close\",function(){e.detach()}),e.open()}},g=_.extend({},f,{state:[\"gallery-edit\"],template:c.template(\"editor-gallery\"),initialize:function(){var a=c.gallery.attachments(this.shortcode,c.view.settings.post.id),b=this.shortcode.attrs.named,d=this;a.more().done(function(){a=a.toJSON(),_.each(a,function(a){a.sizes&&(b.size&&a.sizes[b.size]?a.thumbnail=a.sizes[b.size]:a.sizes.thumbnail?a.thumbnail=a.sizes.thumbnail:a.sizes.full&&(a.thumbnail=a.sizes.full))}),d.render(d.template({verifyHTML:e,attachments:a,columns:b.columns?parseInt(b.columns,10):c.galleryDefaults.columns}))}).fail(function(a,b){d.setError(b)})}}),h=_.extend({},f,{action:\"parse-media-shortcode\",initialize:function(){var a=this;this.url&&(this.loader=!1,this.shortcode=c.embed.shortcode({url:this.text})),wp.ajax.post(this.action,{post_ID:c.view.settings.post.id,type:this.shortcode.tag,shortcode:this.shortcode.string()}).done(function(b){a.render(b)}).fail(function(b){a.url?(a.ignore=!0,a.removeMarkers()):a.setError(b.message||b.statusText,\"admin-media\")}),this.getEditors(function(b){b.on(\"wpview-selected\",function(){a.pausePlayers()})})},pausePlayers:function(){this.getNodes(function(a,b,c){var e=d(\"iframe.wpview-sandbox\",c).get(0);e&&(e=e.contentWindow)&&e.mejs&&_.each(e.mejs.players,function(a){try{a.pause()}catch(b){}})})}}),i=_.extend({},h,{action:\"parse-embed\",edit:function(a,b){var d=c.embed.edit(a,this.url),e=this;this.pausePlayers(),d.state(\"embed\").props.on(\"change:url\",function(a,b){b&&a.get(\"url\")&&(d.state(\"embed\").metadata=a.toJSON())}),d.state(\"embed\").on(\"select\",function(){var a=d.state(\"embed\").metadata;b(e.url?a.url:c.embed.shortcode(a).string())}),d.on(\"close\",function(){d.detach()}),d.open()}}),b.register(\"gallery\",_.extend({},g)),b.register(\"audio\",_.extend({},h,{state:[\"audio-details\"]})),b.register(\"video\",_.extend({},h,{state:[\"video-details\"]})),b.register(\"playlist\",_.extend({},h,{state:[\"playlist-edit\",\"video-playlist-edit\"]})),b.register(\"embed\",_.extend({},i)),b.register(\"embedURL\",_.extend({},i,{match:function(a){var b=/(^|

)(https?:\\/\\/[^\\s\"]+?)(<\\/p>\\s*|$)/gi,c=b.exec(a);if(c)return{index:c.index+c[1].length,content:c[2],options:{url:!0}}}}))}(window,window.wp.mce.views,window.wp.media,window.jQuery);"},"repo_name":{"kind":"string","value":"WordPress_WordPress"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"1015c3b3a07ad6b530bb3aed7e0e11549da791cb"}}},{"rowIdx":15,"cells":{"file_path":{"kind":"string","value":"wp-includes/js/wp-api.min.js"},"num_changed_lines":{"kind":"number","value":1,"string":"1"},"code":{"kind":"string","value":"!function(a,b){\"use strict\";function c(){this.models={},this.collections={},this.views={}}a.wp=a.wp||{},wp.api=wp.api||new c,wp.api.versionString=wp.api.versionString||\"wp/v2/\",!_.isFunction(_.includes)&&_.isFunction(_.contains)&&(_.includes=_.contains)}(window),function(a,b){\"use strict\";var c,d;a.wp=a.wp||{},wp.api=wp.api||{},wp.api.utils=wp.api.utils||{},Date.prototype.toISOString||(c=function(a){return d=String(a),1===d.length&&(d=\"0\"+d),d},Date.prototype.toISOString=function(){return this.getUTCFullYear()+\"-\"+c(this.getUTCMonth()+1)+\"-\"+c(this.getUTCDate())+\"T\"+c(this.getUTCHours())+\":\"+c(this.getUTCMinutes())+\":\"+c(this.getUTCSeconds())+\".\"+String((this.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+\"Z\"}),wp.api.utils.parseISO8601=function(a){var c,d,e,f,g=0,h=[1,4,5,6,7,10,11];if(d=/^(\\d{4}|[+\\-]\\d{6})(?:-(\\d{2})(?:-(\\d{2}))?)?(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:(Z)|([+\\-])(\\d{2})(?::(\\d{2}))?)?)?$/.exec(a)){for(e=0;f=h[e];++e)d[f]=+d[f]||0;d[2]=(+d[2]||1)-1,d[3]=+d[3]||1,\"Z\"!==d[8]&&b!==d[9]&&(g=60*d[10]+d[11],\"+\"===d[9]&&(g=0-g)),c=Date.UTC(d[1],d[2],d[3],d[4],d[5]+g,d[6],d[7])}else c=Date.parse?Date.parse(a):NaN;return c},wp.api.utils.getRootUrl=function(){return a.location.origin?a.location.origin+\"/\":a.location.protocol+\"/\"+a.location.host+\"/\"},wp.api.utils.capitalize=function(a){return _.isUndefined(a)?a:a.charAt(0).toUpperCase()+a.slice(1)},wp.api.utils.extractRoutePart=function(a,b){var c;return b=b||1,a=a.replace(wp.api.versionString,\"\"),c=a.split(\"/\").reverse(),_.isUndefined(c[--b])?\"\":c[b]},wp.api.utils.extractParentName=function(a){var b,c=a.lastIndexOf(\"_id>[\\\\d]+)/\");return c<0?\"\":(b=a.substr(0,c-1),b=b.split(\"/\"),b.pop(),b=b.pop())},wp.api.utils.decorateFromRoute=function(a,b){_.each(a,function(a){_.includes(a.methods,\"POST\")||_.includes(a.methods,\"PUT\")?_.isEmpty(a.args)||(_.isEmpty(b.prototype.args)?b.prototype.args=a.args:b.prototype.args=_.union(a.args,b.prototype.defaults)):_.includes(a.methods,\"GET\")&&(_.isEmpty(a.args)||(_.isEmpty(b.prototype.options)?b.prototype.options=a.args:b.prototype.options=_.union(a.args,b.prototype.options)))})},wp.api.utils.addMixinsAndHelpers=function(a,b,c){var d=!1,e=[\"date\",\"modified\",\"date_gmt\",\"modified_gmt\"],f={setDate:function(a,b){var c=b||\"date\";return!(_.indexOf(e,c)<0)&&void this.set(c,a.toISOString())},getDate:function(a){var b=a||\"date\",c=this.get(b);return!(_.indexOf(e,b)<0||_.isNull(c))&&new Date(wp.api.utils.parseISO8601(c))}},g=function(a,b,c,d,e){var f,g,h,i;return i=jQuery.Deferred(),g=a.get(\"_embedded\")||{},_.isNumber(b)&&0!==b?(g[d]&&(h=_.findWhere(g[d],{id:b})),h||(h={id:b}),f=new wp.api.models[c](h),f.get(e)?i.resolve(f):f.fetch({success:function(a){i.resolve(a)},error:function(a,b){i.reject(b)}}),i.promise()):(i.reject(),i)},h=function(a,b,c,d){var e,f,g,h=\"\",j=\"\",k=jQuery.Deferred();return e=a.get(\"id\"),f=a.get(\"_embedded\")||{},_.isNumber(e)&&0!==e?(_.isUndefined(c)||_.isUndefined(f[c])?h={parent:e}:j=_.isUndefined(d)?f[c]:f[c][d],g=new wp.api.collections[b](j,h),_.isUndefined(g.models[0])?g.fetch({success:function(a){i(a,e),k.resolve(a)},error:function(a,b){k.reject(b)}}):(i(g,e),k.resolve(g)),k.promise()):(k.reject(),k)},i=function(a,b){_.each(a.models,function(a){a.set(\"parent_post\",b)})},j={getMeta:function(){return h(this,\"PostMeta\",\"https://api.w.org/meta\")}},k={getRevisions:function(){return h(this,\"PostRevisions\")}},l={getTags:function(){var a=this.get(\"tags\"),b=new wp.api.collections.Tags;return _.isEmpty(a)?jQuery.Deferred().resolve([]):b.fetch({data:{include:a}})},setTags:function(a){var b,c,d=this,e=[];return!_.isString(a)&&void(_.isArray(a)?(b=new wp.api.collections.Tags,b.fetch({data:{per_page:100},success:function(b){_.each(a,function(a){c=new wp.api.models.Tag(b.findWhere({slug:a})),c.set(\"parent_post\",d.get(\"id\")),e.push(c)}),a=new wp.api.collections.Tags(e),d.setTagsWithCollection(a)}})):this.setTagsWithCollection(a))},setTagsWithCollection:function(a){return this.set(\"tags\",a.pluck(\"id\")),this.save()}},m={getCategories:function(){var a=this.get(\"categories\"),b=new wp.api.collections.Categories;return _.isEmpty(a)?jQuery.Deferred().resolve([]):b.fetch({data:{include:a}})},setCategories:function(a){var b,c,d=this,e=[];return!_.isString(a)&&void(_.isArray(a)?(b=new wp.api.collections.Categories,b.fetch({data:{per_page:100},success:function(b){_.each(a,function(a){c=new wp.api.models.Category(b.findWhere({slug:a})),c.set(\"parent_post\",d.get(\"id\")),e.push(c)}),a=new wp.api.collections.Categories(e),d.setCategoriesWithCollection(a)}})):this.setCategoriesWithCollection(a))},setCategoriesWithCollection:function(a){return this.set(\"categories\",a.pluck(\"id\")),this.save()}},n={getAuthorUser:function(){return g(this,this.get(\"author\"),\"User\",\"author\",\"name\")}},o={getFeaturedMedia:function(){return g(this,this.get(\"featured_media\"),\"Media\",\"wp:featuredmedia\",\"source_url\")}};return _.isUndefined(a.prototype.args)?a:(_.each(e,function(b){_.isUndefined(a.prototype.args[b])||(d=!0)}),d&&(a=a.extend(f)),_.isUndefined(a.prototype.args.author)||(a=a.extend(n)),_.isUndefined(a.prototype.args.featured_media)||(a=a.extend(o)),_.isUndefined(a.prototype.args.categories)||(a=a.extend(m)),_.isUndefined(c.collections[b+\"Meta\"])||(a=a.extend(j)),_.isUndefined(a.prototype.args.tags)||(a=a.extend(l)),_.isUndefined(c.collections[b+\"Revisions\"])||(a=a.extend(k)),a)}}(window),function(){\"use strict\";var a=window.wpApiSettings||{};wp.api.WPApiBaseModel=Backbone.Model.extend({sync:function(b,c,d){var e;return d=d||{},_.isNull(c.get(\"date_gmt\"))&&c.unset(\"date_gmt\"),_.isEmpty(c.get(\"slug\"))&&c.unset(\"slug\"),_.isUndefined(a.nonce)||_.isNull(a.nonce)||(e=d.beforeSend,d.beforeSend=function(b){if(b.setRequestHeader(\"X-WP-Nonce\",a.nonce),e)return e.apply(this,arguments)}),this.requireForceForDelete&&\"delete\"===b&&(c.url=c.url()+\"?force=true\"),Backbone.sync(b,c,d)},save:function(a,b){return!(!_.includes(this.methods,\"PUT\")&&!_.includes(this.methods,\"POST\"))&&Backbone.Model.prototype.save.call(this,a,b)},destroy:function(a){return!!_.includes(this.methods,\"DELETE\")&&Backbone.Model.prototype.destroy.call(this,a)}}),wp.api.models.Schema=wp.api.WPApiBaseModel.extend({defaults:{_links:{},namespace:null,routes:{}},initialize:function(b,c){var d=this;c=c||{},wp.api.WPApiBaseModel.prototype.initialize.call(d,b,c),d.apiRoot=c.apiRoot||a.root,d.versionString=c.versionString||a.versionString},url:function(){return this.apiRoot+this.versionString}})}(),function(){\"use strict\";var a=window.wpApiSettings||{};wp.api.WPApiBaseCollection=Backbone.Collection.extend({initialize:function(a,b){this.state={data:{},currentPage:null,totalPages:null,totalObjects:null},_.isUndefined(b)?this.parent=\"\":this.parent=b.parent},sync:function(b,c,d){var e,f,g=this;return d=d||{},e=d.beforeSend,\"undefined\"!=typeof a.nonce&&(d.beforeSend=function(b){if(b.setRequestHeader(\"X-WP-Nonce\",a.nonce),e)return e.apply(g,arguments)}),\"read\"===b&&(d.data?(g.state.data=_.clone(d.data),delete g.state.data.page):g.state.data=d.data={},\"undefined\"==typeof d.data.page?(g.state.currentPage=null,g.state.totalPages=null,g.state.totalObjects=null):g.state.currentPage=d.data.page-1,f=d.success,d.success=function(a,b,c){if(_.isUndefined(c)||(g.state.totalPages=parseInt(c.getResponseHeader(\"x-wp-totalpages\"),10),g.state.totalObjects=parseInt(c.getResponseHeader(\"x-wp-total\"),10)),null===g.state.currentPage?g.state.currentPage=1:g.state.currentPage++,f)return f.apply(this,arguments)}),Backbone.sync(b,c,d)},more:function(a){if(a=a||{},a.data=a.data||{},_.extend(a.data,this.state.data),\"undefined\"==typeof a.data.page){if(!this.hasMore())return!1;null===this.state.currentPage||this.state.currentPage<=1?a.data.page=2:a.data.page=this.state.currentPage+1}return this.fetch(a)},hasMore:function(){return null===this.state.totalPages||null===this.state.totalObjects||null===this.state.currentPage?null:this.state.currentPage\"+window.decodeURIComponent(b)+\"

\"}return a?a.replace(/]+data-wpview-text=\"([^\"]+)\"[^>]*>(?:\\.|[\\s\\S]+?wpview-end[^>]+>\\s*<\\/span>\\s*)?<\\/div>/g,b).replace(/]+data-wpview-marker=\"([^\"]+)\"[^>]*>[\\s\\S]*?<\\/p>/g,b):a}return b&&b.mce&&b.mce.views?(c.on(\"init\",function(){var a=window.MutationObserver||window.WebKitMutationObserver;a&&new a(function(){c.fire(\"wp-body-class-change\")}).observe(c.getBody(),{attributes:!0,attributeFilter:[\"class\"]}),c.on(\"wp-body-class-change\",function(){var a=c.getBody().className;c.$('iframe[class=\"wpview-sandbox\"]').each(function(b,c){if(!c.src||'javascript:\"\"'===c.src)try{c.contentWindow.document.body.className=a}catch(d){}})})}),c.on(\"beforesetcontent\",function(a){var d;if(a.selection||b.mce.views.unbind(),a.content){if(!a.load&&(d=c.selection.getNode(),d&&d!==c.getBody()&&/^\\s*https?:\\/\\/\\S+\\s*$/i.test(a.content))){if(d=c.dom.getParent(d,\"p\"),!d||!/^[\\s\\uFEFF\\u00A0]*$/.test(c.$(d).text()||\"\"))return;d.innerHTML=\"\"}a.content=b.mce.views.setMarkers(a.content)}}),c.on(\"setcontent\",function(a){a.load&&!a.initial&&c.quirks.refreshContentEditable&&c.quirks.refreshContentEditable(),b.mce.views.render()}),c.on(\"preprocess hide\",function(a){c.$(\"div[data-wpview-text], p[data-wpview-marker]\",a.node).each(function(a,b){b.innerHTML=\".\"})},!0),c.on(\"postprocess\",function(a){a.content=f(a.content)}),c.on(\"beforeaddundo\",function(a){a.level.content=f(a.level.content)}),c.on(\"drop objectselected\",function(a){e(a.targetClone)&&(a.targetClone=c.getDoc().createTextNode(window.decodeURIComponent(c.dom.getAttrib(a.targetClone,\"data-wpview-text\"))))}),c.on(\"pastepreprocess\",function(b){var c=b.content;c&&(c=a.trim(c.replace(/<[^>]+>/g,\"\")),/^https?:\\/\\/\\S+$/i.test(c)&&(b.content=c))}),c.on(\"resolvename\",function(a){e(a.target)&&(a.name=c.dom.getAttrib(a.target,\"data-wpview-type\")||\"object\")}),c.on(\"click keyup\",function(){var a=c.selection.getNode();e(a)&&c.dom.getAttrib(a,\"data-mce-selected\")&&a.setAttribute(\"data-mce-selected\",\"2\")}),c.addButton(\"wp_view_edit\",{tooltip:\"Edit \",icon:\"dashicon dashicons-edit\",onclick:function(){var a=c.selection.getNode();e(a)&&b.mce.views.edit(c,a)}}),c.addButton(\"wp_view_remove\",{tooltip:\"Remove\",icon:\"dashicon dashicons-no\",onclick:function(){c.fire(\"cut\")}}),c.once(\"preinit\",function(){var a;c.wp&&c.wp._createToolbar&&(a=c.wp._createToolbar([\"wp_view_edit\",\"wp_view_remove\"]),c.on(\"wptoolbar\",function(b){!b.collapsed&&e(b.element)&&(b.toolbar=a)}))}),c.wp=c.wp||{},c.wp.getView=d,c.wp.setViewCursor=d,{getView:d}):{getView:d}})}(window.tinymce,window.wp);"},"repo_name":{"kind":"string","value":"WordPress_WordPress"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"1015c3b3a07ad6b530bb3aed7e0e11549da791cb"}}},{"rowIdx":17,"cells":{"file_path":{"kind":"string","value":"libmscore/style.cpp"},"num_changed_lines":{"kind":"number","value":955,"string":"955"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2002-2011 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENCE.GPL\n//=============================================================================\n\n#include \"mscore.h\"\n#include \"style.h\"\n#include \"xml.h\"\n#include \"score.h\"\n#include \"articulation.h\"\n#include \"harmony.h\"\n#include \"chordlist.h\"\n#include \"page.h\"\n#include \"mscore.h\"\n#include \"clef.h\"\n#include \"tuplet.h\"\n#include \"layout.h\"\n#include \"property.h\"\n\nnamespace Ms {\n\n// 20 points font design size\n// 72 points/inch point size\n// 120 dpi screen resolution\n// spatium = 20/4 points\n\n//---------------------------------------------------------\n// StyleType\n//---------------------------------------------------------\n\nstruct StyleType {\n StyleIdx _idx;\n const char* _name; // xml name for read()/write()\n QVariant _defaultValue;\n\n public:\n StyleIdx styleIdx() const { return _idx; }\n int idx() const { return int(_idx); }\n const char* valueType() const { return _defaultValue.typeName(); }\n const char* name() const { return _name; }\n const QVariant& defaultValue() const { return _defaultValue; }\n };\n\n#define MM(x) ((x)/INCH)\n\nstatic const StyleType styleTypes[] {\n { StyleIdx::pageWidth, \"pageWidth\", 210.0/INCH },\n { StyleIdx::pageHeight, \"pageHeight\", 297.0/INCH }, // A4\n { StyleIdx::pagePrintableWidth, \"pagePrintableWidth\", 190.0/INCH },\n { StyleIdx::pageEvenLeftMargin, \"pageEvenLeftMargin\", 10.0/INCH },\n { StyleIdx::pageOddLeftMargin, \"pageOddLeftMargin\", 10.0/INCH },\n { StyleIdx::pageEvenTopMargin, \"pageEvenTopMargin\", 10.0/INCH },\n { StyleIdx::pageEvenBottomMargin, \"pageEvenBottomMargin\", 20.0/INCH },\n { StyleIdx::pageOddTopMargin, \"pageOddTopMargin\", 10.0/INCH },\n { StyleIdx::pageOddBottomMargin, \"pageOddBottomMargin\", 20.0/INCH },\n { StyleIdx::pageTwosided, \"pageTwosided\", true },\n\n { StyleIdx::staffUpperBorder, \"staffUpperBorder\", Spatium(7.0) },\n { StyleIdx::staffLowerBorder, \"staffLowerBorder\", Spatium(7.0) },\n { StyleIdx::staffDistance, \"staffDistance\", Spatium(6.5) },\n { StyleIdx::akkoladeDistance, \"akkoladeDistance\", Spatium(6.5) },\n { StyleIdx::minSystemDistance, \"minSystemDistance\", Spatium(8.5) },\n { StyleIdx::maxSystemDistance, \"maxSystemDistance\", Spatium(15.0) },\n\n { StyleIdx::lyricsPlacement, \"lyricsPlacement\", int(Element::Placement::BELOW) },\n { StyleIdx::lyricsPosAbove, \"lyricsPosAbove\", Spatium(-2.0) },\n { StyleIdx::lyricsPosBelow, \"lyricsPosBelow\", Spatium(2.0) },\n { StyleIdx::lyricsMinTopDistance, \"lyricsMinTopDistance\", Spatium(1.0) },\n { StyleIdx::lyricsMinBottomDistance, \"lyricsMinBottomDistance\", Spatium(3.0) },\n { StyleIdx::lyricsLineHeight, \"lyricsLineHeight\", 1.0 },\n { StyleIdx::lyricsDashMinLength, \"lyricsDashMinLength\", Spatium(0.4) },\n { StyleIdx::lyricsDashMaxLength, \"lyricsDashMaxLegth\", Spatium(0.8) },\n { StyleIdx::lyricsDashMaxDistance, \"lyricsDashMaxDistance\", Spatium(16.0) },\n { StyleIdx::lyricsDashForce, \"lyricsDashForce\", QVariant(true) },\n { StyleIdx::lyricsAlignVerseNumber, \"lyricsAlignVerseNumber\", true },\n { StyleIdx::lyricsLineThickness, \"lyricsLineThickness\", Spatium(0.1) },\n\n { StyleIdx::figuredBassFontFamily, \"figuredBassFontFamily\", QString(\"MScoreBC\") },\n\n// { StyleIdx::figuredBassFontSize, \"figuredBassFontSize\", QVariant(8.0) },\n { StyleIdx::figuredBassYOffset, \"figuredBassYOffset\", QVariant(6.0) },\n { StyleIdx::figuredBassLineHeight, \"figuredBassLineHeight\", QVariant(1.0) },\n { StyleIdx::figuredBassAlignment, \"figuredBassAlignment\", QVariant(0) },\n { StyleIdx::figuredBassStyle, \"figuredBassStyle\" , QVariant(0) },\n { StyleIdx::systemFrameDistance, \"systemFrameDistance\", Spatium(7.0) },\n { StyleIdx::frameSystemDistance, \"frameSystemDistance\", Spatium(7.0) },\n { StyleIdx::minMeasureWidth, \"minMeasureWidth\", Spatium(5.0) },\n { StyleIdx::barWidth, \"barWidth\", Spatium(0.16) }, // 0.1875\n { StyleIdx::doubleBarWidth, \"doubleBarWidth\", Spatium(0.16) },\n\n { StyleIdx::endBarWidth, \"endBarWidth\", Spatium(0.5) }, // 0.5\n { StyleIdx::doubleBarDistance, \"doubleBarDistance\", Spatium(0.30) },\n { StyleIdx::endBarDistance, \"endBarDistance\", Spatium(0.40) }, // 0.3\n { StyleIdx::repeatBarlineDotSeparation, \"repeatBarlineDotSeparation\", Spatium(0.40) },\n { StyleIdx::repeatBarTips, \"repeatBarTips\", QVariant(false) },\n { StyleIdx::startBarlineSingle, \"startBarlineSingle\", QVariant(false) },\n { StyleIdx::startBarlineMultiple, \"startBarlineMultiple\", QVariant(true) },\n { StyleIdx::bracketWidth, \"bracketWidth\", Spatium(0.45) },\n { StyleIdx::bracketDistance, \"bracketDistance\", Spatium(0.1) },\n { StyleIdx::akkoladeWidth, \"akkoladeWidth\", Spatium(1.6) },\n { StyleIdx::akkoladeBarDistance, \"akkoladeBarDistance\", Spatium(.4) },\n\n { StyleIdx::dividerLeft, \"dividerLeft\", QVariant(false) },\n { StyleIdx::dividerLeftSym, \"dividerLeftSym\", QVariant(QString(\"systemDivider\")) },\n { StyleIdx::dividerLeftX, \"dividerLeftX\", QVariant(0.0) },\n { StyleIdx::dividerLeftY, \"dividerLeftY\", QVariant(0.0) },\n { StyleIdx::dividerRight, \"dividerRight\", QVariant(false) },\n { StyleIdx::dividerRightSym, \"dividerRightSym\", QVariant(QString(\"systemDivider\")) },\n { StyleIdx::dividerRightX, \"dividerRightX\", QVariant(0.0) },\n { StyleIdx::dividerRightY, \"dividerRightY\", QVariant(0.0) },\n\n { StyleIdx::clefLeftMargin, \"clefLeftMargin\", Spatium(0.8) }, // 0.64 (gould: <= 1)\n { StyleIdx::keysigLeftMargin, \"keysigLeftMargin\", Spatium(0.5) },\n { StyleIdx::ambitusMargin, \"ambitusMargin\", Spatium(0.5) },\n\n { StyleIdx::timesigLeftMargin, \"timesigLeftMargin\", Spatium(0.5) },\n { StyleIdx::clefKeyRightMargin, \"clefKeyRightMargin\", Spatium(0.8) },\n { StyleIdx::clefKeyDistance, \"clefKeyDistance\", Spatium(1.0) }, // gould: 1 - 1.25\n { StyleIdx::clefTimesigDistance, \"clefTimesigDistance\", Spatium(1.0) },\n { StyleIdx::keyTimesigDistance, \"keyTimesigDistance\", Spatium(1.0) }, // gould: 1 - 1.5\n { StyleIdx::keyBarlineDistance, \"keyTimesigDistance\", Spatium(1.0) },\n { StyleIdx::systemHeaderDistance, \"systemHeaderDistance\", Spatium(2.5) }, // gould: 2.5\n { StyleIdx::systemHeaderTimeSigDistance, \"systemHeaderTimeSigDistance\", Spatium(2.0) }, // gould: 2.0\n\n { StyleIdx::clefBarlineDistance, \"clefBarlineDistance\", Spatium(0.18) }, // was 0.5\n { StyleIdx::timesigBarlineDistance, \"timesigBarlineDistance\", Spatium(0.5) },\n { StyleIdx::stemWidth, \"stemWidth\", Spatium(0.13) }, // 0.09375\n { StyleIdx::shortenStem, \"shortenStem\", QVariant(true) },\n { StyleIdx::shortStemProgression, \"shortStemProgression\", Spatium(0.25) },\n { StyleIdx::shortestStem, \"shortestStem\", Spatium(2.25) },\n { StyleIdx::beginRepeatLeftMargin, \"beginRepeatLeftMargin\", Spatium(1.0) },\n { StyleIdx::minNoteDistance, \"minNoteDistance\", Spatium(0.25) }, // 0.4\n { StyleIdx::barNoteDistance, \"barNoteDistance\", Spatium(1.2) },\n\n { StyleIdx::barAccidentalDistance, \"barAccidentalDistance\", Spatium(.3) },\n { StyleIdx::multiMeasureRestMargin, \"multiMeasureRestMargin\", Spatium(1.2) },\n { StyleIdx::noteBarDistance, \"noteBarDistance\", Spatium(1.0) },\n { StyleIdx::measureSpacing, \"measureSpacing\", QVariant(1.2) },\n { StyleIdx::staffLineWidth, \"staffLineWidth\", Spatium(0.08) }, // 0.09375\n { StyleIdx::ledgerLineWidth, \"ledgerLineWidth\", Spatium(0.16) }, // 0.1875\n { StyleIdx::ledgerLineLength, \"ledgerLineLength\", Spatium(.6) }, // notehead width + this value\n { StyleIdx::accidentalDistance, \"accidentalDistance\", Spatium(0.22) },\n { StyleIdx::accidentalNoteDistance, \"accidentalNoteDistance\", Spatium(0.22) },\n { StyleIdx::beamWidth, \"beamWidth\", Spatium(0.5) }, // was 0.48\n\n { StyleIdx::beamDistance, \"beamDistance\", QVariant(0.5) }, // 0.25sp units\n { StyleIdx::beamMinLen, \"beamMinLen\", Spatium(1.32) }, // 1.316178 exactly notehead widthen beams\n { StyleIdx::beamNoSlope, \"beamNoSlope\", QVariant(false) },\n { StyleIdx::dotMag, \"dotMag\", QVariant(1.0) },\n { StyleIdx::dotNoteDistance, \"dotNoteDistance\", Spatium(0.35) },\n { StyleIdx::dotRestDistance, \"dotRestDistance\", Spatium(0.25) },\n { StyleIdx::dotDotDistance, \"dotDotDistance\", Spatium(0.5) },\n { StyleIdx::propertyDistanceHead, \"propertyDistanceHead\", Spatium(1.0) },\n { StyleIdx::propertyDistanceStem, \"propertyDistanceStem\", Spatium(1.8) },\n { StyleIdx::propertyDistance, \"propertyDistance\", Spatium(1.0) },\n\n { StyleIdx::articulationMag, \"articulationMag\", QVariant(1.0) },\n { StyleIdx::lastSystemFillLimit, \"lastSystemFillLimit\", QVariant(0.3) },\n\n { StyleIdx::hairpinPlacement, \"hairpinPlacement\", int(Element::Placement::BELOW) },\n { StyleIdx::hairpinPosAbove, \"hairpinPosAbove\", Spatium(-3.5) },\n { StyleIdx::hairpinPosBelow, \"hairpinPosBelow\", Spatium(3.5) },\n { StyleIdx::hairpinHeight, \"hairpinHeight\", Spatium(1.2) },\n { StyleIdx::hairpinContHeight, \"hairpinContHeight\", Spatium(0.5) },\n { StyleIdx::hairpinLineWidth, \"hairpinWidth\", Spatium(0.13) },\n\n { StyleIdx::pedalPlacement, \"pedalPlacement\", int(Element::Placement::BELOW) },\n { StyleIdx::pedalPosAbove, \"pedalPosAbove\", Spatium(-4) },\n { StyleIdx::pedalPosBelow, \"pedalPosBelow\", Spatium(4) },\n { StyleIdx::pedalLineWidth, \"pedalLineWidth\", Spatium(.15) },\n { StyleIdx::pedalLineStyle, \"pedalListStyle\", QVariant(int(Qt::SolidLine)) },\n\n { StyleIdx::trillPlacement, \"trillPlacement\", int(Element::Placement::ABOVE) },\n { StyleIdx::trillPosAbove, \"trillPosAbove\", Spatium(-1) },\n { StyleIdx::trillPosBelow, \"trillPosBelow\", Spatium(1) },\n\n { StyleIdx::harmonyY, \"harmonyY\", Spatium(2.5) },\n { StyleIdx::harmonyFretDist, \"harmonyFretDist\", Spatium(0.5) },\n { StyleIdx::minHarmonyDistance, \"minHarmonyDistance\", Spatium(0.5) },\n { StyleIdx::maxHarmonyBarDistance, \"maxHarmonyBarDistance\", Spatium(3.0) },\n { StyleIdx::capoPosition, \"capoPosition\", QVariant(0) },\n { StyleIdx::fretNumMag, \"fretNumMag\", QVariant(2.0) },\n { StyleIdx::fretNumPos, \"fretNumPos\", QVariant(0) },\n { StyleIdx::fretY, \"fretY\", Spatium(2.0) },\n { StyleIdx::showPageNumber, \"showPageNumber\", QVariant(true) },\n { StyleIdx::showPageNumberOne, \"showPageNumberOne\", QVariant(false) },\n\n { StyleIdx::pageNumberOddEven, \"pageNumberOddEven\", QVariant(true) },\n { StyleIdx::showMeasureNumber, \"showMeasureNumber\", QVariant(true) },\n { StyleIdx::showMeasureNumberOne, \"showMeasureNumberOne\", QVariant(false) },\n { StyleIdx::measureNumberInterval, \"measureNumberInterval\", QVariant(5) },\n { StyleIdx::measureNumberSystem, \"measureNumberSystem\", QVariant(true) },\n { StyleIdx::measureNumberAllStaffs, \"measureNumberAllStaffs\", QVariant(false) },\n { StyleIdx::smallNoteMag, \"smallNoteMag\", QVariant(.7) },\n { StyleIdx::graceNoteMag, \"graceNoteMag\", QVariant(0.7) },\n { StyleIdx::smallStaffMag, \"smallStaffMag\", QVariant(0.7) },\n { StyleIdx::smallClefMag, \"smallClefMag\", QVariant(0.8) },\n\n { StyleIdx::genClef, \"genClef\", QVariant(true) },\n { StyleIdx::genKeysig, \"genKeysig\", QVariant(true) },\n { StyleIdx::genCourtesyTimesig, \"genCourtesyTimesig\", QVariant(true) },\n { StyleIdx::genCourtesyKeysig, \"genCourtesyKeysig\", QVariant(true) },\n { StyleIdx::genCourtesyClef, \"genCourtesyClef\", QVariant(true) },\n { StyleIdx::swingRatio, \"swingRatio\", QVariant(60) },\n { StyleIdx::swingUnit, \"swingUnit\", QVariant(QString(\"\")) },\n { StyleIdx::useStandardNoteNames, \"useStandardNoteNames\", QVariant(true) },\n { StyleIdx::useGermanNoteNames, \"useGermanNoteNames\", QVariant(false) },\n { StyleIdx::useFullGermanNoteNames, \"useFullGermanNoteNames\", QVariant(false) },\n\n { StyleIdx::useSolfeggioNoteNames, \"useSolfeggioNoteNames\", QVariant(false) },\n { StyleIdx::useFrenchNoteNames, \"useFrenchNoteNames\", QVariant(false) },\n { StyleIdx::automaticCapitalization, \"automaticCapitalization\", QVariant(true) },\n { StyleIdx::lowerCaseMinorChords, \"lowerCaseMinorChords\", QVariant(false) },\n { StyleIdx::lowerCaseBassNotes, \"lowerCaseBassNotes\", QVariant(false) },\n { StyleIdx::allCapsNoteNames, \"allCapsNoteNames\", QVariant(false) },\n { StyleIdx::chordStyle, \"chordStyle\", QVariant(QString(\"std\")) },\n { StyleIdx::chordsXmlFile, \"chordsXmlFile\", QVariant(false) },\n { StyleIdx::chordDescriptionFile, \"chordDescriptionFile\", QVariant(QString(\"chords_std.xml\")) },\n { StyleIdx::concertPitch, \"concertPitch\", QVariant(false) },\n\n { StyleIdx::createMultiMeasureRests, \"createMultiMeasureRests\", QVariant(false) },\n { StyleIdx::minEmptyMeasures, \"minEmptyMeasures\", QVariant(2) },\n { StyleIdx::minMMRestWidth, \"minMMRestWidth\", Spatium(4) },\n { StyleIdx::hideEmptyStaves, \"hideEmptyStaves\", QVariant(false) },\n { StyleIdx::dontHideStavesInFirstSystem,\n \"dontHidStavesInFirstSystm\", QVariant(true) },\n { StyleIdx::hideInstrumentNameIfOneInstrument,\n \"hideInstrumentNameIfOneInstrument\", QVariant(true) },\n { StyleIdx::gateTime, \"gateTime\", QVariant(100) },\n { StyleIdx::tenutoGateTime, \"tenutoGateTime\", QVariant(100) },\n { StyleIdx::staccatoGateTime, \"staccatoGateTime\", QVariant(50) },\n { StyleIdx::slurGateTime, \"slurGateTime\", QVariant(100) },\n\n { StyleIdx::ArpeggioNoteDistance, \"ArpeggioNoteDistance\", Spatium(.5) },\n { StyleIdx::ArpeggioLineWidth, \"ArpeggioLineWidth\", Spatium(.18) },\n { StyleIdx::ArpeggioHookLen, \"ArpeggioHookLen\", Spatium(.8) },\n { StyleIdx::SlurEndWidth, \"slurEndWidth\", Spatium(.07) },\n { StyleIdx::SlurMidWidth, \"slurMidWidth\", Spatium(.15) },\n { StyleIdx::SlurDottedWidth, \"slurDottedWidth\", Spatium(.1) },\n { StyleIdx::MinTieLength, \"minTieLength\", Spatium(1.0) },\n { StyleIdx::SectionPause, \"sectionPause\", QVariant(qreal(3.0)) },\n { StyleIdx::MusicalSymbolFont, \"musicalSymbolFont\", QVariant(QString(\"Emmentaler\")) },\n { StyleIdx::MusicalTextFont, \"musicalTextFont\", QVariant(QString(\"MScore Text\")) },\n\n { StyleIdx::showHeader, \"showHeader\", QVariant(false) },\n { StyleIdx::headerFirstPage, \"headerFirstPage\", QVariant(false) },\n { StyleIdx::headerOddEven, \"headerOddEven\", QVariant(true) },\n { StyleIdx::evenHeaderL, \"evenHeaderL\", QVariant(QString()) },\n { StyleIdx::evenHeaderC, \"evenHeaderC\", QVariant(QString()) },\n { StyleIdx::evenHeaderR, \"evenHeaderR\", QVariant(QString()) },\n { StyleIdx::oddHeaderL, \"oddHeaderL\", QVariant(QString()) },\n { StyleIdx::oddHeaderC, \"oddHeaderC\", QVariant(QString()) },\n { StyleIdx::oddHeaderR, \"oddHeaderR\", QVariant(QString()) },\n { StyleIdx::showFooter, \"showFooter\", QVariant(true) },\n\n { StyleIdx::footerFirstPage, \"footerFirstPage\", QVariant(true) },\n { StyleIdx::footerOddEven, \"footerOddEven\", QVariant(true) },\n { StyleIdx::evenFooterL, \"evenFooterL\", QVariant(QString(\"$p\")) },\n { StyleIdx::evenFooterC, \"evenFooterC\", QVariant(QString(\"$:copyright:\")) },\n { StyleIdx::evenFooterR, \"evenFooterR\", QVariant(QString()) },\n { StyleIdx::oddFooterL, \"oddFooterL\", QVariant(QString()) },\n { StyleIdx::oddFooterC, \"oddFooterC\", QVariant(QString(\"$:copyright:\")) },\n { StyleIdx::oddFooterR, \"oddFooterR\", QVariant(QString(\"$p\")) },\n { StyleIdx::voltaY, \"voltaY\", Spatium(-3.0) },\n { StyleIdx::voltaHook, \"voltaHook\", Spatium(1.9) },\n\n { StyleIdx::voltaLineWidth, \"voltaLineWidth\", Spatium(.1) },\n { StyleIdx::voltaLineStyle, \"voltaLineStyle\", QVariant(int(Qt::SolidLine)) },\n\n { StyleIdx::ottavaPlacement, \"ottavaPlacement\", int(Element::Placement::ABOVE) },\n { StyleIdx::ottavaPosAbove, \"ottavaPosAbove\", Spatium(-3.0) },\n { StyleIdx::ottavaPosBelow, \"ottavaPosBelow\", Spatium(3.0) },\n { StyleIdx::ottavaHook, \"ottavaHook\", Spatium(1.9) },\n { StyleIdx::ottavaLineWidth, \"ottavaLineWidth\", Spatium(.1) },\n { StyleIdx::ottavaLineStyle, \"ottavaLineStyle\", QVariant(int(Qt::DashLine)) },\n { StyleIdx::ottavaNumbersOnly, \"ottavaNumbersOnly\", true },\n\n { StyleIdx::tabClef, \"tabClef\", QVariant(int(ClefType::TAB)) },\n { StyleIdx::tremoloWidth, \"tremoloWidth\", Spatium(1.2) }, // tremolo stroke width: notehead width\n { StyleIdx::tremoloBoxHeight, \"tremoloBoxHeight\", Spatium(0.65) },\n\n { StyleIdx::tremoloStrokeWidth, \"tremoloLineWidth\", Spatium(0.5) }, // was 0.35\n { StyleIdx::tremoloDistance, \"tremoloDistance\", Spatium(0.8) },\n { StyleIdx::linearStretch, \"linearStretch\", QVariant(qreal(1.5)) },\n { StyleIdx::crossMeasureValues, \"crossMeasureValues\", QVariant(false) },\n { StyleIdx::keySigNaturals, \"keySigNaturals\", QVariant(int(KeySigNatural::NONE)) },\n\n { StyleIdx::tupletMaxSlope, \"tupletMaxSlope\", QVariant(qreal(0.5)) },\n { StyleIdx::tupletOufOfStaff, \"tupletOufOfStaff\", QVariant(true) },\n { StyleIdx::tupletVHeadDistance, \"tupletVHeadDistance\", Spatium(.5) },\n { StyleIdx::tupletVStemDistance, \"tupletVStemDistance\", Spatium(.25) },\n { StyleIdx::tupletStemLeftDistance, \"tupletStemLeftDistance\", Spatium(.5) },\n { StyleIdx::tupletStemRightDistance, \"tupletStemRightDistance\", Spatium(.5) },\n { StyleIdx::tupletNoteLeftDistance, \"tupletNoteLeftDistance\", Spatium(0.0) },\n { StyleIdx::tupletNoteRightDistance, \"tupletNoteRightDistance\", Spatium(0.0) },\n { StyleIdx::tupletBracketWidth, \"tupletBracketWidth\", Spatium(0.1) },\n { StyleIdx::tupletDirection, \"tupletDirection\", Direction(Direction::AUTO) },\n { StyleIdx::tupletNumberType, \"tupletNumberType\", int(Tuplet::NumberType::SHOW_NUMBER) },\n { StyleIdx::tupletBracketType, \"tupletBracketType\", int(Tuplet::BracketType::AUTO_BRACKET) },\n\n { StyleIdx::barreLineWidth, \"barreLineWidth\", QVariant(1.0) },\n { StyleIdx::fretMag, \"fretMag\", QVariant(1.0) },\n { StyleIdx::scaleBarlines, \"scaleBarlines\", QVariant(true) },\n { StyleIdx::barGraceDistance, \"barGraceDistance\", Spatium(.6) },\n { StyleIdx::minVerticalDistance, \"minVerticalDistance\", Spatium(0.5) },\n { StyleIdx::ornamentStyle, \"ornamentStyle\", int(MScore::OrnamentStyle::DEFAULT) },\n { StyleIdx::spatium, \"Spatium\", SPATIUM20 },\n\n { StyleIdx::autoplaceHairpinDynamicsDistance, \"autoplaceHairpinDynamicsDistance\", Spatium(0.5) },\n\n { StyleIdx::dynamicsPlacement, \"dynamicsPlacement\", int(Element::Placement::BELOW) },\n { StyleIdx::dynamicsPosAbove, \"dynamicsPosAbove\", Spatium(-2.0) },\n { StyleIdx::dynamicsPosBelow, \"dynamicsPosBelow\", Spatium(1.0) },\n\n { StyleIdx::dynamicsMinDistance, \"dynamicsMinDistance\", Spatium(0.5) },\n { StyleIdx::autoplaceVerticalAlignRange, \"autoplaceVerticalAlignRange\", int(VerticalAlignRange::SYSTEM) },\n\n { StyleIdx::textLinePlacement, \"textLinePlacement\", int(Element::Placement::ABOVE) },\n { StyleIdx::textLinePosAbove, \"textLinePosAbove\", Spatium(-3.5) },\n { StyleIdx::textLinePosBelow, \"textLinePosBelow\", Spatium(3.5) },\n\n { StyleIdx::tremoloBarLineWidth, \"tremoloBarLineWidth\", Spatium(0.1) },\n\n//====\n\n { StyleIdx::defaultFontFace, \"defaultFontFace\", \"FreeSerif\" },\n { StyleIdx::defaultFontSize, \"defaultFontSize\", 10.0 },\n { StyleIdx::defaultFontSpatiumDependent, \"defaultFontSpatiumDependent\", true },\n { StyleIdx::defaultFontBold, \"defaultFontBold\", false },\n { StyleIdx::defaultFontItalic, \"defaultFontItalic\", false },\n { StyleIdx::defaultFontUnderline, \"defaultFontUnderline\", false },\n { StyleIdx::defaultAlign, \"defaultAlign\", int(Align::LEFT) },\n { StyleIdx::defaultFrame, \"defaultFrame\", false },\n { StyleIdx::defaultFrameSquare, \"defaultFrameSquare\", false },\n { StyleIdx::defaultFrameCircle, \"defaultFrameCircle\", false },\n { StyleIdx::defaultFramePadding, \"defaultFramePadding\", 0.0 },\n { StyleIdx::defaultFrameWidth, \"defaultFrameWidth\", 0.0 },\n { StyleIdx::defaultFrameRound, \"defaultFrameRound\", 0 },\n { StyleIdx::defaultFrameFgColor, \"defaultFrameFgColor\", QColor(0, 0, 0, 255) },\n { StyleIdx::defaultFrameBgColor, \"defaultFrameBgColor\", QColor(255, 255, 255, 0) },\n { StyleIdx::defaultOffset, \"defaultOffset\", QPointF() },\n { StyleIdx::defaultOffsetType, \"defaultOffsetType\", int(OffsetType::SPATIUM) },\n { StyleIdx::defaultSystemFlag, \"defaultSystemFlag\", false },\n\n { StyleIdx::titleFontFace, \"titleFontFace\", \"FreeSerif\" },\n { StyleIdx::titleFontSize, \"titleFontSize\", 24.0 },\n { StyleIdx::titleFontSpatiumDependent, \"titleFontSpatiumDependent\", false },\n { StyleIdx::titleFontBold, \"titleFontBold\", false },\n { StyleIdx::titleFontItalic, \"titleFontItalic\", false },\n { StyleIdx::titleFontUnderline, \"titleFontUnderline\", false },\n { StyleIdx::titleAlign, \"titleAlign\", int(Align::HCENTER | Align::TOP) },\n { StyleIdx::titleOffset, \"titleOffset\", QPointF() },\n { StyleIdx::titleOffsetType, \"titleOffsetType\", int(OffsetType::ABS) },\n\n { StyleIdx::subTitleFontFace, \"subTitleFontFace\", \"FreeSerif\" },\n { StyleIdx::subTitleFontSize, \"subTitleFontSize\", 14.0 },\n { StyleIdx::subTitleFontSpatiumDependent, \"subTitleFontSpatiumDependent\", false },\n { StyleIdx::subTitleFontBold, \"subTitleFontBold\", false },\n { StyleIdx::subTitleFontItalic, \"subTtitleFontItalic\", false },\n { StyleIdx::subTitleFontUnderline, \"subTitleFontUnderline\", false },\n { StyleIdx::subTitleAlign, \"subTitleAlign\", int(Align::HCENTER | Align::TOP) },\n { StyleIdx::subTitleOffset, \"subTitleOffset\", QPointF(0.0, MM(10.0)) },\n { StyleIdx::subTitleOffsetType, \"subTitleOffsetType\", int(OffsetType::ABS) },\n\n { StyleIdx::composerFontFace, \"composerFontFace\", \"FreeSerif\" },\n { StyleIdx::composerFontSize, \"composerFontSize\", 12.0 },\n { StyleIdx::composerFontSpatiumDependent, \"composerFontSpatiumDependent\", false },\n { StyleIdx::composerFontBold, \"composerFontBold\", false },\n { StyleIdx::composerFontItalic, \"composerFontItalic\", false },\n { StyleIdx::composerFontUnderline, \"composerFontUnderline\", false },\n { StyleIdx::composerAlign, \"composerAlign\", int(Align::RIGHT | Align::BOTTOM) },\n { StyleIdx::composerOffset, \"composerOffset\", QPointF() },\n { StyleIdx::composerOffsetType, \"composerOffsetType\", int(OffsetType::ABS) },\n\n { StyleIdx::lyricistFontFace, \"lyricistFontFace\", \"FreeSerif\" },\n { StyleIdx::lyricistFontSize, \"lyricistFontSize\", 12.0 },\n { StyleIdx::lyricistFontSpatiumDependent, \"lyricistFontSpatiumDependent\", false },\n { StyleIdx::lyricistFontBold, \"lyricistFontBold\", false },\n { StyleIdx::lyricistFontItalic, \"lyricistFontItalic\", false },\n { StyleIdx::lyricistFontUnderline, \"lyricistFontUnderline\", false },\n { StyleIdx::lyricistAlign, \"lyricistAlign\", int(Align::LEFT | Align::BOTTOM) },\n { StyleIdx::lyricistOffset, \"lyricistOffset\", QPointF() },\n { StyleIdx::lyricistOffsetType, \"lyricistOffsetType\", int(OffsetType::ABS) },\n\n { StyleIdx::lyricsOddFontFace, \"lyricsOddFontFace\", \"FreeSerif\" },\n { StyleIdx::lyricsOddFontSize, \"lyricsOddFontSize\", 11.0 },\n { StyleIdx::lyricsOddFontBold, \"lyricsOddFontBold\", false },\n { StyleIdx::lyricsOddFontItalic, \"lyricsOddFontItalic\", false },\n { StyleIdx::lyricsOddFontUnderline, \"lyricsOddFontUnderline\", false },\n { StyleIdx::lyricsOddAlign, \"lyricistOddAlign\", int(Align::HCENTER | Align::BASELINE) },\n { StyleIdx::lyricsOddOffset, \"lyricistOddOffset\", QPointF(0.0, 6.0) },\n\n { StyleIdx::lyricsEvenFontFace, \"lyricsEvenFontFace\", \"FreeSerif\" },\n { StyleIdx::lyricsEvenFontSize, \"lyricsEvenFontSize\", 11.0 },\n { StyleIdx::lyricsEvenFontBold, \"lyricsEvenFontBold\", false },\n { StyleIdx::lyricsEvenFontItalic, \"lyricsEvenFontItalic\", false },\n { StyleIdx::lyricsEvenFontUnderline, \"lyricsEventFontUnderline\", false },\n { StyleIdx::lyricsEvenAlign, \"lyricistEvenAlign\", int(Align::HCENTER | Align::BASELINE) },\n { StyleIdx::lyricsEvenOffset, \"lyricistEvenOffset\", QPointF(0.0, 6.0) },\n\n { StyleIdx::fingeringFontFace, \"fingeringFontFace\", \"FreeSerif\" },\n { StyleIdx::fingeringFontSize, \"fingeringFontSize\", 8.0 },\n { StyleIdx::fingeringFontBold, \"fingeringFontBold\", false },\n { StyleIdx::fingeringFontItalic, \"fingeringFontItalic\", false },\n { StyleIdx::fingeringFontUnderline, \"fingeringFontUnderline\", false },\n { StyleIdx::fingeringAlign, \"fingeringAlign\", int(Align::CENTER) },\n { StyleIdx::fingeringFrame, \"fingeringFrame\", false },\n { StyleIdx::fingeringFrameSquare, \"fingeringFrameSquare\", false },\n { StyleIdx::fingeringFrameCircle, \"fingeringFrameCircle\", false },\n { StyleIdx::fingeringFramePadding, \"fingeringFramePadding\", 0.0 },\n { StyleIdx::fingeringFrameWidth, \"fingeringFrameWidth\", 0.0 },\n { StyleIdx::fingeringFrameRound, \"fingeringFrameRound\", 0 },\n { StyleIdx::fingeringFrameFgColor, \"fingeringFrameFgColor\", QColor(0, 0, 0, 255) },\n { StyleIdx::fingeringFrameBgColor, \"fingeringFrameBgColor\", QColor(255, 255, 255, 0) },\n { StyleIdx::fingeringOffset, \"fingeringOffset\", QPointF() },\n\n { StyleIdx::lhGuitarFingeringFontFace, \"lhGuitarFingeringFontFace\", \"FreeSerif\" },\n { StyleIdx::lhGuitarFingeringFontSize, \"lhGuitarFingeringFontSize\", 8.0 },\n { StyleIdx::lhGuitarFingeringFontBold, \"lhGuitarFingeringFontBold\", false },\n { StyleIdx::lhGuitarFingeringFontItalic, \"lhGuitarFingeringFontItalic\", false },\n { StyleIdx::lhGuitarFingeringFontUnderline,\"lhGuitarFingeringFontUnderline\",false },\n { StyleIdx::lhGuitarFingeringAlign, \"lhGuitarFingeringAlign\", int(Align::RIGHT | Align::VCENTER) },\n { StyleIdx::lhGuitarFingeringFrame, \"lhGuitarFingeringFrame\", false },\n { StyleIdx::lhGuitarFingeringFrameSquare, \"lhGuitarFingeringFrameSquare\", false },\n { StyleIdx::lhGuitarFingeringFrameCircle, \"lhGuitarFingeringFrameCircle\", false },\n { StyleIdx::lhGuitarFingeringFramePadding, \"lhGuitarFingeringFramePadding\", 0.0 },\n { StyleIdx::lhGuitarFingeringFrameWidth, \"lhGuitarFingeringFrameWidth\", 0.0 },\n { StyleIdx::lhGuitarFingeringFrameRound, \"lhGuitarFingeringFrameRound\", 0 },\n { StyleIdx::lhGuitarFingeringFrameFgColor, \"lhGuitarFingeringFrameFgColor\", QColor(0, 0, 0, 255) },\n { StyleIdx::lhGuitarFingeringFrameBgColor, \"lhGuitarFingeringFrameBgColor\", QColor(255, 255, 255, 0) },\n { StyleIdx::lhGuitarFingeringOffset, \"lhGuitarFingeringOffset\", QPointF(-0.5, 0.0) },\n\n { StyleIdx::rhGuitarFingeringFontFace, \"rhGuitarFingeringFontFace\", \"FreeSerif\" },\n { StyleIdx::rhGuitarFingeringFontSize, \"rhGuitarFingeringFontSize\", 8.0 },\n { StyleIdx::rhGuitarFingeringFontBold, \"rhGuitarFingeringFontBold\", false },\n { StyleIdx::rhGuitarFingeringFontItalic, \"rhGuitarFingeringFontItalic\", false },\n { StyleIdx::rhGuitarFingeringFontUnderline,\"rhGuitarFingeringFontUnderline\",false },\n { StyleIdx::rhGuitarFingeringAlign, \"rhGuitarFingeringAlign\", int(Align::CENTER) },\n { StyleIdx::rhGuitarFingeringFrame, \"rhGuitarFingeringFrame\", false },\n { StyleIdx::rhGuitarFingeringFrameSquare, \"rhGuitarFingeringFrameSquare\", false },\n { StyleIdx::rhGuitarFingeringFrameCircle, \"rhGuitarFingeringFrameCircle\", false },\n { StyleIdx::rhGuitarFingeringFramePadding, \"rhGuitarFingeringFramePadding\", 0.0 },\n { StyleIdx::rhGuitarFingeringFrameWidth, \"rhGuitarFingeringFrameWidth\", 0.0 },\n { StyleIdx::rhGuitarFingeringFrameRound, \"rhGuitarFingeringFrameRound\", 0 },\n { StyleIdx::rhGuitarFingeringFrameFgColor, \"rhGuitarFingeringFrameFgColor\", QColor(0, 0, 0, 255) },\n { StyleIdx::rhGuitarFingeringFrameBgColor, \"rhGuitarFingeringFrameBgColor\", QColor(255, 255, 255, 0) },\n { StyleIdx::rhGuitarFingeringOffset, \"rhGuitarFingeringOffset\", QPointF() },\n\n { StyleIdx::stringNumberFontFace, \"stringNumberFontFace\", \"FreeSerif\" },\n { StyleIdx::stringNumberFontSize, \"stringNumberFontSize\", 8.0 },\n { StyleIdx::stringNumberFontBold, \"stringNumberFontBold\", false },\n { StyleIdx::stringNumberFontItalic, \"stringNumberFontItalic\", false },\n { StyleIdx::stringNumberFontUnderline, \"stringNumberFontUnderline\", false },\n { StyleIdx::stringNumberAlign, \"stringNumberAlign\", int(Align::CENTER) },\n { StyleIdx::stringNumberFrame, \"stringNumberFrame\", true },\n { StyleIdx::stringNumberFrameSquare, \"stringNumberFrameSquare\", false },\n { StyleIdx::stringNumberFrameCircle, \"stringNumberFrameCircle\", true },\n { StyleIdx::stringNumberFramePadding, \"stringNumberFramePadding\", 0.2 },\n { StyleIdx::stringNumberFrameWidth, \"stringNumberFrameWidth\", 0.1 },\n { StyleIdx::stringNumberFrameRound, \"stringNumberFrameRound\", 0 },\n { StyleIdx::stringNumberFrameFgColor, \"stringNumberFrameFgColor\", QColor(0, 0, 0, 255) },\n { StyleIdx::stringNumberFrameBgColor, \"stringNumberFrameBgColor\", QColor(255, 255, 255, 0) },\n { StyleIdx::stringNumberOffset, \"stringNumberOffset\", QPointF(0.0, -2.0) },\n\n { StyleIdx::longInstrumentFontFace, \"longInstrumentFontFace\", \"FreeSerif\" },\n { StyleIdx::longInstrumentFontSize, \"longInstrumentFontSize\", 12.0 },\n { StyleIdx::longInstrumentFontBold, \"longInstrumentFontBold\", false },\n { StyleIdx::longInstrumentFontItalic, \"longInstrumentFontItalic\", false },\n { StyleIdx::longInstrumentFontUnderline, \"longInstrumentFontUnderline\", false },\n\n { StyleIdx::shortInstrumentFontFace, \"shortInstrumentFontFace\", \"FreeSerif\" },\n { StyleIdx::shortInstrumentFontSize, \"shortInstrumentFontSize\", 12.0 },\n { StyleIdx::shortInstrumentFontBold, \"shortInstrumentFontBold\", false },\n { StyleIdx::shortInstrumentFontItalic, \"shortInstrumentFontItalic\", false },\n { StyleIdx::shortInstrumentFontUnderline, \"shortInstrumentFontUnderline\", false },\n\n { StyleIdx::partInstrumentFontFace, \"partInstrumentFontFace\", \"FreeSerif\" },\n { StyleIdx::partInstrumentFontSize, \"partInstrumentFontSize\", 18.0 },\n { StyleIdx::partInstrumentFontBold, \"partInstrumentFontBold\", false },\n { StyleIdx::partInstrumentFontItalic, \"partInstrumentFontItalic\", false },\n { StyleIdx::partInstrumentFontUnderline, \"partInstrumentFontUnderline\", false },\n\n { StyleIdx::dynamicsFontFace, \"dynamicsFontFace\", \"FreeSerif\" },\n { StyleIdx::dynamicsFontSize, \"dynamicsFontSize\", 12.0 },\n { StyleIdx::dynamicsFontBold, \"dynamicsFontBold\", false },\n { StyleIdx::dynamicsFontItalic, \"dynamicsFontItalic\", true },\n { StyleIdx::dynamicsFontUnderline, \"dynamicsFontUnderline\", false },\n { StyleIdx::dynamicsAlign, \"dynamicsAlign\", int(Align::HCENTER | Align::BASELINE) },\n\n { StyleIdx::expressionFontFace, \"expressionFontFace\", \"FreeSerif\" },\n { StyleIdx::expressionFontSize, \"expressionFontSize\", 11.0 },\n { StyleIdx::expressionFontBold, \"expressionFontBold\", false },\n { StyleIdx::expressionFontItalic, \"expressionFontItalic\", true },\n { StyleIdx::expressionFontUnderline, \"expressionFontUnderline\", false },\n { StyleIdx::expressionAlign, \"expressionAlign\", int(Align::LEFT | Align::BASELINE) },\n\n { StyleIdx::tempoFontFace, \"tempoFontFace\", \"FreeSerif\" },\n { StyleIdx::tempoFontSize, \"tempoFontSize\", 12.0 },\n { StyleIdx::tempoFontBold, \"tempoFontBold\", true },\n { StyleIdx::tempoFontItalic, \"tempoFontItalic\", false },\n { StyleIdx::tempoFontUnderline, \"tempoFontUnderline\", false },\n { StyleIdx::tempoAlign, \"tempoAlign\", int(Align::LEFT | Align::BASELINE) },\n { StyleIdx::tempoOffset, \"tempoOffset\", QPointF(0.0, -4.0) },\n { StyleIdx::tempoSystemFlag, \"tempoSystemFlag\", true },\n\n { StyleIdx::metronomeFontFace, \"metronomeFontFace\", \"FreeSerif\" },\n { StyleIdx::metronomeFontSize, \"metronomeFontSize\", 12.0 },\n { StyleIdx::metronomeFontBold, \"metronomeFontBold\", true },\n { StyleIdx::metronomeFontItalic, \"metronomeFontItalic\", false },\n { StyleIdx::metronomeFontUnderline, \"metronomeFontUnderline\", false },\n\n { StyleIdx::measureNumberFontFace, \"measureNumberFontFace\", \"FreeSerif\" },\n { StyleIdx::measureNumberFontSize, \"measureNumberFontSize\", 8.0 },\n { StyleIdx::measureNumberFontBold, \"measureNumberFontBold\", false },\n { StyleIdx::measureNumberFontItalic, \"measureNumberFontItalic\", false },\n { StyleIdx::measureNumberFontUnderline, \"measureNumberFontUnderline\", false },\n { StyleIdx::measureNumberOffset, \"measureNumberOffset\", QPointF(0.0, -2.0) },\n { StyleIdx::measureNumberOffsetType, \"measureNumberOffsetType\", int(OffsetType::SPATIUM) },\n\n { StyleIdx::translatorFontFace, \"translatorFontFace\", \"FreeSerif\" },\n { StyleIdx::translatorFontSize, \"translatorFontSize\", 11.0 },\n { StyleIdx::translatorFontBold, \"translatorFontBold\", false },\n { StyleIdx::translatorFontItalic, \"translatorFontItalic\", false },\n { StyleIdx::translatorFontUnderline, \"translatorFontUnderline\", false },\n\n { StyleIdx::tupletFontFace, \"tupletFontFace\", \"FreeSerif\" },\n { StyleIdx::tupletFontSize, \"tupletFontSize\", 10.0 },\n { StyleIdx::tupletFontBold, \"tupletFontBold\", false },\n { StyleIdx::tupletFontItalic, \"tupletFontItalic\", true },\n { StyleIdx::tupletFontUnderline, \"tupletFontUnderline\", false },\n\n { StyleIdx::systemFontFace, \"systemFontFace\", \"FreeSerif\" },\n { StyleIdx::systemFontSize, \"systemFontSize\", 10.0 },\n { StyleIdx::systemFontBold, \"systemFontBold\", false },\n { StyleIdx::systemFontItalic, \"systemFontItalic\", false },\n { StyleIdx::systemFontUnderline, \"systemFontUnderline\", false },\n { StyleIdx::systemOffset, \"systemOffset\", QPointF(0.0, -4.0) },\n { StyleIdx::systemOffsetType, \"defaultOffsetType\", int(OffsetType::SPATIUM) },\n// { StyleIdx::systemSystemFlag, \"systemSystemFlag\", true },\n\n { StyleIdx::staffFontFace, \"staffFontFace\", \"FreeSerif\" },\n { StyleIdx::staffFontSize, \"staffFontSize\", 10.0 },\n { StyleIdx::staffFontBold, \"staffFontBold\", false },\n { StyleIdx::staffFontItalic, \"staffFontItalic\", false },\n { StyleIdx::staffFontUnderline, \"staffFontUnderline\", false },\n { StyleIdx::staffOffset, \"staffOffset\", QPointF(0.0, -4.0) },\n { StyleIdx::staffOffsetType, \"defaultOffsetType\", int(OffsetType::SPATIUM) },\n// { StyleIdx::staffSystemFlag, \"staffSystemFlag\", false },\n\n { StyleIdx::chordSymbolFontFace, \"chordSymbolFontFace\", \"FreeSerif\" },\n { StyleIdx::chordSymbolFontSize, \"chordSymbolFontSize\", 12.0 },\n { StyleIdx::chordSymbolFontBold, \"chordSymbolFontBold\", false },\n { StyleIdx::chordSymbolFontItalic, \"chordSymbolFontItalic\", false },\n { StyleIdx::chordSymbolFontUnderline, \"chordSymbolFontUnderline\", false },\n\n { StyleIdx::rehearsalMarkFontFace, \"rehearsalMarkFontFace\", \"FreeSerif\" },\n { StyleIdx::rehearsalMarkFontSize, \"rehearsalMarkFontSize\", 14.0 },\n { StyleIdx::rehearsalMarkFontBold, \"rehearsalMarkFontBold\", true },\n { StyleIdx::rehearsalMarkFontItalic, \"rehearsalMarkFontItalic\", false },\n { StyleIdx::rehearsalMarkFontUnderline, \"rehearsalMarkFontUnderline\", false },\n { StyleIdx::rehearsalMarkFrame, \"rehearsalMarkFrame\", false },\n { StyleIdx::rehearsalMarkFrameSquare, \"rehearsalMarkFrameSquare\", false },\n { StyleIdx::rehearsalMarkFrameCircle, \"rehearsalMarkFrameCircle\", false },\n { StyleIdx::rehearsalMarkFramePadding, \"rehearsalMarkFramePadding\", 0.0 },\n { StyleIdx::rehearsalMarkFrameWidth, \"rehearsalMarkFrameWidth\", 0.0 },\n { StyleIdx::rehearsalMarkFrameRound, \"rehearsalMarkFrameRound\", 0 },\n { StyleIdx::rehearsalMarkFrameFgColor, \"rehearsalMarkFrameFgColor\", QColor(0, 0, 0, 255) },\n { StyleIdx::rehearsalMarkFrameBgColor, \"rehearsalMarkFrameBgColor\", QColor(255, 255, 255, 0) },\n { StyleIdx::rehearsalMarkSystemFlag, \"rehearsalMarkSystemFlag\", true },\n\n { StyleIdx::repeatLeftFontFace, \"repeatLeftFontFace\", \"FreeSerif\" },\n { StyleIdx::repeatLeftFontSize, \"repeatLeftFontSize\", 20.0 },\n { StyleIdx::repeatLeftFontBold, \"repeatLeftFontBold\", false },\n { StyleIdx::repeatLeftFontItalic, \"repeatLeftFontItalic\", false },\n { StyleIdx::repeatLeftFontUnderline, \"repeatLeftFontUnderline\", false },\n { StyleIdx::repeatLeftSystemFlag, \"repeatSystemFlag\", true },\n\n { StyleIdx::repeatRightFontFace, \"repeatRightFontFace\", \"FreeSerif\" },\n { StyleIdx::repeatRightFontSize, \"repeatRightFontSize\", 12.0 },\n { StyleIdx::repeatRightFontBold, \"repeatRightFontBold\", false },\n { StyleIdx::repeatRightFontItalic, \"repeatRightFontItalic\", false },\n { StyleIdx::repeatRightFontUnderline, \"repeatRightFontUnderline\", false },\n { StyleIdx::repeatRightSystemFlag, \"repeatRightSystemFlag\", true },\n\n { StyleIdx::voltaSubStyle, \"voltaSubStyle\", int(SubStyle::VOLTA) },\n { StyleIdx::voltaFontFace, \"voltaFontFace\", \"FreeSerif\" },\n { StyleIdx::voltaFontSize, \"voltaFontSize\", 11.0 },\n { StyleIdx::voltaFontBold, \"voltaFontBold\", true },\n { StyleIdx::voltaFontItalic, \"voltaFontItalic\", false },\n { StyleIdx::voltaFontUnderline, \"voltaFontUnderline\", false },\n { StyleIdx::voltaAlign, \"voltaAlign\", int(Align::LEFT | Align::BASELINE) },\n { StyleIdx::voltaOffset, \"voltaOffset\", QPointF(0.5, 1.9) },\n\n { StyleIdx::frameFontFace, \"frameFontFace\", \"FreeSerif\" },\n { StyleIdx::frameFontSize, \"frameFontSize\", 12.0 },\n { StyleIdx::frameFontBold, \"frameFontBold\", false },\n { StyleIdx::frameFontItalic, \"frameFontItalic\", false },\n { StyleIdx::frameFontUnderline, \"frameFontUnderline\", false },\n\n { StyleIdx::textLineFontFace, \"textLineFontFace\", \"FreeSerif\" },\n { StyleIdx::textLineFontSize, \"textLineFontSize\", 12.0 },\n { StyleIdx::textLineFontBold, \"textLineFontBold\", false },\n { StyleIdx::textLineFontItalic, \"textLineFontItalic\", false },\n { StyleIdx::textLineFontUnderline, \"textLineFontUnderline\", false },\n\n { StyleIdx::glissandoFontFace, \"glissandoFontFace\", \"FreeSerif\" },\n { StyleIdx::glissandoFontSize, \"glissandoFontSize\", 8.0 },\n { StyleIdx::glissandoFontBold, \"glissandoFontBold\", false },\n { StyleIdx::glissandoFontItalic, \"glissandoFontItalic\", true },\n { StyleIdx::glissandoFontUnderline, \"glissandoFontUnderline\", false },\n\n { StyleIdx::ottavaFontFace, \"ottavaFontFace\", \"FreeSerif\" },\n { StyleIdx::ottavaFontSize, \"ottavaFontSize\", 12.0 },\n { StyleIdx::ottavaFontBold, \"ottavaFontBold\", false },\n { StyleIdx::ottavaFontItalic, \"ottavaFontItalic\", false },\n { StyleIdx::ottavaFontUnderline, \"ottavaFontUnderline\", false },\n\n { StyleIdx::pedalFontFace, \"pedalFontFace\", \"FreeSerif\" },\n { StyleIdx::pedalFontSize, \"pedalFontSize\", 12.0 },\n { StyleIdx::pedalFontBold, \"pedalFontBold\", false },\n { StyleIdx::pedalFontItalic, \"pedalFontItalic\", false },\n { StyleIdx::pedalFontUnderline, \"pedalFontUnderline\", false },\n\n { StyleIdx::hairpinFontFace, \"hairpinFontFace\", \"FreeSerif\" },\n { StyleIdx::hairpinFontSize, \"hairpinFontSize\", 12.0 },\n { StyleIdx::hairpinFontBold, \"hairpinFontBold\", false },\n { StyleIdx::hairpinFontItalic, \"hairpinFontItalic\", true },\n { StyleIdx::hairpinFontUnderline, \"hairpinFontUnderline\", false },\n\n { StyleIdx::bendFontFace, \"bendFontFace\", \"FreeSerif\" },\n { StyleIdx::bendFontSize, \"bendFontSize\", 8.0 },\n { StyleIdx::bendFontBold, \"bendFontBold\", false },\n { StyleIdx::bendFontItalic, \"bendFontItalic\", false },\n { StyleIdx::bendFontUnderline, \"bendFontUnderline\", false },\n\n { StyleIdx::headerFontFace, \"headerFontFace\", \"FreeSerif\" },\n { StyleIdx::headerFontSize, \"headerFontSize\", 8.0 },\n { StyleIdx::headerFontBold, \"headerFontBold\", false },\n { StyleIdx::headerFontItalic, \"headerFontItalic\", false },\n { StyleIdx::headerFontUnderline, \"headerFontUnderline\", false },\n\n { StyleIdx::footerFontFace, \"footerFontFace\", \"FreeSerif\" },\n { StyleIdx::footerFontSize, \"footerFontSize\", 8.0 },\n { StyleIdx::footerFontBold, \"footerFontBold\", false },\n { StyleIdx::footerFontItalic, \"footerFontItalic\", false },\n { StyleIdx::footerFontUnderline, \"footerFontUnderline\", false },\n\n { StyleIdx::instrumentChangeFontFace, \"instrumentChangeFontFace\", \"FreeSerif\" },\n { StyleIdx::instrumentChangeFontSize, \"instrumentChangeFontSize\", 12.0 },\n { StyleIdx::instrumentChangeFontBold, \"instrumentChangeFontBold\", true },\n { StyleIdx::instrumentChangeFontItalic, \"instrumentChangeFontItalic\", false },\n { StyleIdx::instrumentChangeFontUnderline, \"instrumentChangeFontUnderline\",false },\n { StyleIdx::instrumentChangeOffset, \"instrumentChangeOffset\", QPointF(0, -3.0) },\n\n { StyleIdx::figuredBassFontFace, \"figuredBassFontFace\", \"MScoreBC\" },\n { StyleIdx::figuredBassFontSize, \"figuredBassFontSize\", 8.0 },\n { StyleIdx::figuredBassFontBold, \"figuredBassFontBold\", false },\n { StyleIdx::figuredBassFontItalic, \"figuredBassFontItalic\", false },\n { StyleIdx::figuredBassFontUnderline, \"figuredBassFontUnderline\", false },\n };\n#undef MM\n\n//---------------------------------------------------------\n// sets of styled properties\n//---------------------------------------------------------\n\nconst std::vector defaultStyle {\n { StyleIdx::defaultFontFace, P_ID::FONT_FACE },\n { StyleIdx::defaultFontSize, P_ID::FONT_SIZE },\n { StyleIdx::defaultFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT },\n { StyleIdx::defaultFontBold, P_ID::FONT_BOLD },\n { StyleIdx::defaultFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::defaultFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::defaultAlign, P_ID::ALIGN },\n { StyleIdx::defaultFrame, P_ID::FRAME },\n { StyleIdx::defaultFrameSquare, P_ID::FRAME_SQUARE },\n { StyleIdx::defaultFrameCircle, P_ID::FRAME_CIRCLE },\n { StyleIdx::defaultFramePadding, P_ID::FRAME_PADDING },\n { StyleIdx::defaultFrameWidth, P_ID::FRAME_WIDTH },\n { StyleIdx::defaultFrameRound, P_ID::FRAME_ROUND },\n { StyleIdx::defaultFrameFgColor, P_ID::FRAME_FG_COLOR },\n { StyleIdx::defaultFrameBgColor, P_ID::FRAME_BG_COLOR },\n { StyleIdx::defaultOffset, P_ID::OFFSET },\n { StyleIdx::defaultOffsetType, P_ID::OFFSET_TYPE },\n { StyleIdx::defaultSystemFlag, P_ID::SYSTEM_FLAG },\n };\n\nconst std::vector titleStyle {\n { StyleIdx::titleFontFace, P_ID::FONT_FACE },\n { StyleIdx::titleFontSize, P_ID::FONT_SIZE },\n { StyleIdx::titleFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT },\n { StyleIdx::titleFontBold, P_ID::FONT_BOLD },\n { StyleIdx::titleFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::titleFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::titleAlign, P_ID::ALIGN },\n { StyleIdx::titleOffset, P_ID::OFFSET },\n { StyleIdx::titleOffsetType, P_ID::OFFSET_TYPE },\n };\n\nconst std::vector subTitleStyle {\n { StyleIdx::subTitleFontFace, P_ID::FONT_FACE },\n { StyleIdx::subTitleFontSize, P_ID::FONT_SIZE },\n { StyleIdx::subTitleFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT },\n { StyleIdx::subTitleFontBold, P_ID::FONT_BOLD },\n { StyleIdx::subTitleFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::subTitleFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::subTitleAlign, P_ID::ALIGN },\n { StyleIdx::subTitleOffset, P_ID::OFFSET },\n { StyleIdx::subTitleOffsetType, P_ID::OFFSET_TYPE },\n { StyleIdx::subTitleOffset, P_ID::OFFSET },\n { StyleIdx::subTitleOffsetType, P_ID::OFFSET_TYPE },\n };\n\nconst std::vector composerStyle {\n { StyleIdx::composerFontFace, P_ID::FONT_FACE },\n { StyleIdx::composerFontSize, P_ID::FONT_SIZE },\n { StyleIdx::composerFontSpatiumDependent, P_ID::FONT_SPATIUM_DEPENDENT },\n { StyleIdx::composerFontBold, P_ID::FONT_BOLD },\n { StyleIdx::composerFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::composerFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::composerAlign, P_ID::ALIGN },\n { StyleIdx::composerOffset, P_ID::OFFSET },\n { StyleIdx::composerOffsetType, P_ID::OFFSET_TYPE },\n };\n\nconst std::vector lyricistStyle {\n { StyleIdx::lyricistFontFace, P_ID::FONT_FACE },\n { StyleIdx::lyricistFontSize, P_ID::FONT_SIZE },\n { StyleIdx::lyricistFontBold, P_ID::FONT_BOLD },\n { StyleIdx::lyricistFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::lyricistFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::lyricistAlign, P_ID::ALIGN },\n { StyleIdx::lyricistOffset, P_ID::OFFSET },\n { StyleIdx::lyricistOffsetType, P_ID::OFFSET_TYPE },\n };\n\nconst std::vector lyricsOddStyle {\n { StyleIdx::lyricsOddFontFace, P_ID::FONT_FACE },\n { StyleIdx::lyricsOddFontSize, P_ID::FONT_SIZE },\n { StyleIdx::lyricsOddFontBold, P_ID::FONT_BOLD },\n { StyleIdx::lyricsOddFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::lyricsOddFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::lyricsOddAlign, P_ID::ALIGN },\n };\n\nconst std::vector lyricsEvenStyle {\n { StyleIdx::lyricsEvenFontFace, P_ID::FONT_FACE },\n { StyleIdx::lyricsEvenFontSize, P_ID::FONT_SIZE },\n { StyleIdx::lyricsEvenFontBold, P_ID::FONT_BOLD },\n { StyleIdx::lyricsEvenFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::lyricsEvenFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::lyricsEvenAlign, P_ID::ALIGN },\n };\n\nconst std::vector fingeringStyle {\n { StyleIdx::fingeringFontFace, P_ID::FONT_FACE },\n { StyleIdx::fingeringFontSize, P_ID::FONT_SIZE },\n { StyleIdx::fingeringFontBold, P_ID::FONT_BOLD },\n { StyleIdx::fingeringFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::fingeringFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::fingeringAlign, P_ID::ALIGN },\n { StyleIdx::fingeringFrame, P_ID::FRAME },\n { StyleIdx::fingeringFrameSquare, P_ID::FRAME_SQUARE },\n { StyleIdx::fingeringFrameCircle, P_ID::FRAME_CIRCLE },\n { StyleIdx::fingeringFramePadding, P_ID::FRAME_PADDING },\n { StyleIdx::fingeringFrameWidth, P_ID::FRAME_WIDTH },\n { StyleIdx::fingeringFrameRound, P_ID::FRAME_ROUND },\n { StyleIdx::fingeringFrameFgColor, P_ID::FRAME_FG_COLOR },\n { StyleIdx::fingeringFrameBgColor, P_ID::FRAME_BG_COLOR },\n { StyleIdx::fingeringOffset, P_ID::OFFSET },\n };\n\nconst std::vector lhGuitarFingeringStyle {\n { StyleIdx::lhGuitarFingeringFontFace, P_ID::FONT_FACE },\n { StyleIdx::lhGuitarFingeringFontSize, P_ID::FONT_SIZE },\n { StyleIdx::lhGuitarFingeringFontBold, P_ID::FONT_BOLD },\n { StyleIdx::lhGuitarFingeringFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::lhGuitarFingeringFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::lhGuitarFingeringAlign, P_ID::ALIGN },\n { StyleIdx::lhGuitarFingeringFrame, P_ID::FRAME },\n { StyleIdx::lhGuitarFingeringFrameSquare, P_ID::FRAME_SQUARE },\n { StyleIdx::lhGuitarFingeringFrameCircle, P_ID::FRAME_CIRCLE },\n { StyleIdx::lhGuitarFingeringFramePadding, P_ID::FRAME_PADDING },\n { StyleIdx::lhGuitarFingeringFrameWidth, P_ID::FRAME_WIDTH },\n { StyleIdx::lhGuitarFingeringFrameRound, P_ID::FRAME_ROUND },\n { StyleIdx::lhGuitarFingeringFrameFgColor, P_ID::FRAME_FG_COLOR },\n { StyleIdx::lhGuitarFingeringFrameBgColor, P_ID::FRAME_BG_COLOR },\n { StyleIdx::lhGuitarFingeringOffset, P_ID::OFFSET },\n };\n\nconst std::vector rhGuitarFingeringStyle {\n { StyleIdx::rhGuitarFingeringFontFace, P_ID::FONT_FACE },\n { StyleIdx::rhGuitarFingeringFontSize, P_ID::FONT_SIZE },\n { StyleIdx::rhGuitarFingeringFontBold, P_ID::FONT_BOLD },\n { StyleIdx::rhGuitarFingeringFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::rhGuitarFingeringFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::rhGuitarFingeringAlign, P_ID::ALIGN },\n { StyleIdx::rhGuitarFingeringFrame, P_ID::FRAME },\n { StyleIdx::rhGuitarFingeringFrameSquare, P_ID::FRAME_SQUARE },\n { StyleIdx::rhGuitarFingeringFrameCircle, P_ID::FRAME_CIRCLE },\n { StyleIdx::rhGuitarFingeringFramePadding, P_ID::FRAME_PADDING },\n { StyleIdx::rhGuitarFingeringFrameWidth, P_ID::FRAME_WIDTH },\n { StyleIdx::rhGuitarFingeringFrameRound, P_ID::FRAME_ROUND },\n { StyleIdx::rhGuitarFingeringFrameFgColor, P_ID::FRAME_FG_COLOR },\n { StyleIdx::rhGuitarFingeringFrameBgColor, P_ID::FRAME_BG_COLOR },\n { StyleIdx::rhGuitarFingeringOffset, P_ID::OFFSET },\n };\n\nconst std::vector stringNumberStyle {\n { StyleIdx::stringNumberFontFace, P_ID::FONT_FACE },\n { StyleIdx::stringNumberFontSize, P_ID::FONT_SIZE },\n { StyleIdx::stringNumberFontBold, P_ID::FONT_BOLD },\n { StyleIdx::stringNumberFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::stringNumberFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::stringNumberAlign, P_ID::ALIGN },\n { StyleIdx::stringNumberFrame, P_ID::FRAME },\n { StyleIdx::stringNumberFrameSquare, P_ID::FRAME_SQUARE },\n { StyleIdx::stringNumberFrameCircle, P_ID::FRAME_CIRCLE },\n { StyleIdx::stringNumberFramePadding, P_ID::FRAME_PADDING },\n { StyleIdx::stringNumberFrameWidth, P_ID::FRAME_WIDTH },\n { StyleIdx::stringNumberFrameRound, P_ID::FRAME_ROUND },\n { StyleIdx::stringNumberFrameFgColor, P_ID::FRAME_FG_COLOR },\n { StyleIdx::stringNumberFrameBgColor, P_ID::FRAME_BG_COLOR },\n { StyleIdx::stringNumberOffset, P_ID::OFFSET },\n };\n\nconst std::vector longInstrumentStyle {\n { StyleIdx::longInstrumentFontFace, P_ID::FONT_FACE },\n { StyleIdx::longInstrumentFontSize, P_ID::FONT_SIZE },\n { StyleIdx::longInstrumentFontBold, P_ID::FONT_BOLD },\n { StyleIdx::longInstrumentFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::longInstrumentFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector shortInstrumentStyle {\n { StyleIdx::shortInstrumentFontFace, P_ID::FONT_FACE },\n { StyleIdx::shortInstrumentFontSize, P_ID::FONT_SIZE },\n { StyleIdx::shortInstrumentFontBold, P_ID::FONT_BOLD },\n { StyleIdx::shortInstrumentFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::shortInstrumentFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector partInstrumentStyle {\n { StyleIdx::partInstrumentFontFace, P_ID::FONT_FACE },\n { StyleIdx::partInstrumentFontSize, P_ID::FONT_SIZE },\n { StyleIdx::partInstrumentFontBold, P_ID::FONT_BOLD },\n { StyleIdx::partInstrumentFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::partInstrumentFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector dynamicsStyle {\n { StyleIdx::dynamicsFontFace, P_ID::FONT_FACE },\n { StyleIdx::dynamicsFontSize, P_ID::FONT_SIZE },\n { StyleIdx::dynamicsFontBold, P_ID::FONT_BOLD },\n { StyleIdx::dynamicsFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::dynamicsFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector expressionStyle {\n { StyleIdx::expressionFontFace, P_ID::FONT_FACE },\n { StyleIdx::expressionFontSize, P_ID::FONT_SIZE },\n { StyleIdx::expressionFontBold, P_ID::FONT_BOLD },\n { StyleIdx::expressionFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::expressionFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector tempoStyle {\n { StyleIdx::tempoFontFace, P_ID::FONT_FACE },\n { StyleIdx::tempoFontSize, P_ID::FONT_SIZE },\n { StyleIdx::tempoFontBold, P_ID::FONT_BOLD },\n { StyleIdx::tempoFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::tempoFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::tempoOffset, P_ID::OFFSET },\n { StyleIdx::tempoSystemFlag, P_ID::SYSTEM_FLAG },\n };\n\nconst std::vector metronomeStyle {\n { StyleIdx::metronomeFontFace, P_ID::FONT_FACE },\n { StyleIdx::metronomeFontSize, P_ID::FONT_SIZE },\n { StyleIdx::metronomeFontBold, P_ID::FONT_BOLD },\n { StyleIdx::metronomeFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::metronomeFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector measureNumberStyle {\n { StyleIdx::measureNumberFontFace, P_ID::FONT_FACE },\n { StyleIdx::measureNumberFontSize, P_ID::FONT_SIZE },\n { StyleIdx::measureNumberFontBold, P_ID::FONT_BOLD },\n { StyleIdx::measureNumberFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::measureNumberFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::measureNumberOffset, P_ID::OFFSET },\n { StyleIdx::measureNumberOffsetType, P_ID::OFFSET_TYPE },\n };\n\nconst std::vector translatorStyle {\n { StyleIdx::translatorFontFace, P_ID::FONT_FACE },\n { StyleIdx::translatorFontSize, P_ID::FONT_SIZE },\n { StyleIdx::translatorFontBold, P_ID::FONT_BOLD },\n { StyleIdx::translatorFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::translatorFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector tupletStyle {\n { StyleIdx::tupletFontFace, P_ID::FONT_FACE },\n { StyleIdx::tupletFontSize, P_ID::FONT_SIZE },\n { StyleIdx::tupletFontBold, P_ID::FONT_BOLD },\n { StyleIdx::tupletFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::tupletFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector systemStyle {\n { StyleIdx::systemFontFace, P_ID::FONT_FACE },\n { StyleIdx::systemFontSize, P_ID::FONT_SIZE },\n { StyleIdx::systemFontBold, P_ID::FONT_BOLD },\n { StyleIdx::systemFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::systemFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::systemOffset, P_ID::OFFSET },\n { StyleIdx::systemOffsetType, P_ID::OFFSET_TYPE },\n// { StyleIdx::systemSystemFlag, P_ID::SYSTEM_FLAG },\n };\n\nconst std::vector staffStyle {\n { StyleIdx::staffFontFace, P_ID::FONT_FACE },\n { StyleIdx::staffFontSize, P_ID::FONT_SIZE },\n { StyleIdx::staffFontBold, P_ID::FONT_BOLD },\n { StyleIdx::staffFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::staffFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::staffOffset, P_ID::OFFSET },\n { StyleIdx::staffOffsetType, P_ID::OFFSET_TYPE },\n// { StyleIdx::staffSystemFlag, P_ID::SYSTEM_FLAG },\n };\n\nconst std::vector chordSymbolStyle {\n { StyleIdx::chordSymbolFontFace, P_ID::FONT_FACE },\n { StyleIdx::chordSymbolFontSize, P_ID::FONT_SIZE },\n { StyleIdx::chordSymbolFontBold, P_ID::FONT_BOLD },\n { StyleIdx::chordSymbolFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::chordSymbolFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector rehearsalMarkStyle {\n { StyleIdx::rehearsalMarkFontFace, P_ID::FONT_FACE },\n { StyleIdx::rehearsalMarkFontSize, P_ID::FONT_SIZE },\n { StyleIdx::rehearsalMarkFontBold, P_ID::FONT_BOLD },\n { StyleIdx::rehearsalMarkFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::rehearsalMarkFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::rehearsalMarkFrame, P_ID::FRAME },\n { StyleIdx::rehearsalMarkFrameSquare, P_ID::FRAME_SQUARE },\n { StyleIdx::rehearsalMarkFrameCircle, P_ID::FRAME_CIRCLE },\n { StyleIdx::rehearsalMarkFramePadding, P_ID::FRAME_PADDING },\n { StyleIdx::rehearsalMarkFrameWidth, P_ID::FRAME_WIDTH },\n { StyleIdx::rehearsalMarkFrameRound, P_ID::FRAME_ROUND },\n { StyleIdx::rehearsalMarkFrameFgColor, P_ID::FRAME_FG_COLOR },\n { StyleIdx::rehearsalMarkFrameBgColor, P_ID::FRAME_BG_COLOR },\n { StyleIdx::rehearsalMarkSystemFlag, P_ID::SYSTEM_FLAG },\n };\n\nconst std::vector repeatLeftStyle {\n { StyleIdx::repeatLeftFontFace, P_ID::FONT_FACE },\n { StyleIdx::repeatLeftFontSize, P_ID::FONT_SIZE },\n { StyleIdx::repeatLeftFontBold, P_ID::FONT_BOLD },\n { StyleIdx::repeatLeftFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::repeatLeftFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::repeatLeftSystemFlag, P_ID::SYSTEM_FLAG },\n };\n\nconst std::vector repeatRightStyle {\n { StyleIdx::repeatRightFontFace, P_ID::FONT_FACE },\n { StyleIdx::repeatRightFontSize, P_ID::FONT_SIZE },\n { StyleIdx::repeatRightFontBold, P_ID::FONT_BOLD },\n { StyleIdx::repeatRightFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::repeatRightFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::repeatRightSystemFlag, P_ID::SYSTEM_FLAG },\n };\n\nconst std::vector voltaStyle {\n { StyleIdx::voltaSubStyle, P_ID::SUB_STYLE },\n { StyleIdx::voltaFontFace, P_ID::FONT_FACE },\n { StyleIdx::voltaFontSize, P_ID::FONT_SIZE },\n { StyleIdx::voltaFontBold, P_ID::FONT_BOLD },\n { StyleIdx::voltaFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::voltaFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::voltaAlign, P_ID::ALIGN },\n { StyleIdx::voltaOffset, P_ID::OFFSET },\n };\n\nconst std::vector frameStyle {\n { StyleIdx::frameFontFace, P_ID::FONT_FACE },\n { StyleIdx::frameFontSize, P_ID::FONT_SIZE },\n { StyleIdx::frameFontBold, P_ID::FONT_BOLD },\n { StyleIdx::frameFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::frameFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector textLineStyle {\n { StyleIdx::textLineFontFace, P_ID::FONT_FACE },\n { StyleIdx::textLineFontSize, P_ID::FONT_SIZE },\n { StyleIdx::textLineFontBold, P_ID::FONT_BOLD },\n { StyleIdx::textLineFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::textLineFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector glissandoStyle {\n { StyleIdx::glissandoFontFace, P_ID::FONT_FACE },\n { StyleIdx::glissandoFontSize, P_ID::FONT_SIZE },\n { StyleIdx::glissandoFontBold, P_ID::FONT_BOLD },\n { StyleIdx::glissandoFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::glissandoFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector ottavaStyle {\n { StyleIdx::ottavaFontFace, P_ID::FONT_FACE },\n { StyleIdx::ottavaFontSize, P_ID::FONT_SIZE },\n { StyleIdx::ottavaFontBold, P_ID::FONT_BOLD },\n { StyleIdx::ottavaFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::ottavaFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector pedalStyle {\n { StyleIdx::pedalFontFace, P_ID::FONT_FACE },\n { StyleIdx::pedalFontSize, P_ID::FONT_SIZE },\n { StyleIdx::pedalFontBold, P_ID::FONT_BOLD },\n { StyleIdx::pedalFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::pedalFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector hairpinStyle {\n { StyleIdx::hairpinFontFace, P_ID::FONT_FACE },\n { StyleIdx::hairpinFontSize, P_ID::FONT_SIZE },\n { StyleIdx::hairpinFontBold, P_ID::FONT_BOLD },\n { StyleIdx::hairpinFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::hairpinFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector bendStyle {\n { StyleIdx::bendFontFace, P_ID::FONT_FACE },\n { StyleIdx::bendFontSize, P_ID::FONT_SIZE },\n { StyleIdx::bendFontBold, P_ID::FONT_BOLD },\n { StyleIdx::bendFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::bendFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector headerStyle {\n { StyleIdx::headerFontFace, P_ID::FONT_FACE },\n { StyleIdx::headerFontSize, P_ID::FONT_SIZE },\n { StyleIdx::headerFontBold, P_ID::FONT_BOLD },\n { StyleIdx::headerFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::headerFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector footerStyle {\n { StyleIdx::footerFontFace, P_ID::FONT_FACE },\n { StyleIdx::footerFontSize, P_ID::FONT_SIZE },\n { StyleIdx::footerFontBold, P_ID::FONT_BOLD },\n { StyleIdx::footerFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::footerFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector instrumentChangeStyle {\n { StyleIdx::instrumentChangeFontFace, P_ID::FONT_FACE },\n { StyleIdx::instrumentChangeFontSize, P_ID::FONT_SIZE },\n { StyleIdx::instrumentChangeFontBold, P_ID::FONT_BOLD },\n { StyleIdx::instrumentChangeFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::instrumentChangeFontUnderline, P_ID::FONT_UNDERLINE },\n { StyleIdx::instrumentChangeOffset, P_ID::OFFSET },\n };\n\nconst std::vector figuredBassStyle {\n { StyleIdx::figuredBassFontFace, P_ID::FONT_FACE },\n { StyleIdx::figuredBassFontSize, P_ID::FONT_SIZE },\n { StyleIdx::figuredBassFontBold, P_ID::FONT_BOLD },\n { StyleIdx::figuredBassFontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::figuredBassFontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector user1Style {\n { StyleIdx::user1FontFace, P_ID::FONT_FACE },\n { StyleIdx::user1FontSize, P_ID::FONT_SIZE },\n { StyleIdx::user1FontBold, P_ID::FONT_BOLD },\n { StyleIdx::user1FontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::user1FontUnderline, P_ID::FONT_UNDERLINE },\n };\n\nconst std::vector user2Style {\n { StyleIdx::user2FontFace, P_ID::FONT_FACE },\n { StyleIdx::user2FontSize, P_ID::FONT_SIZE },\n { StyleIdx::user2FontBold, P_ID::FONT_BOLD },\n { StyleIdx::user2FontItalic, P_ID::FONT_ITALIC },\n { StyleIdx::user2FontUnderline, P_ID::FONT_UNDERLINE },\n };\n\n//---------------------------------------------------------\n// StyledPropertyListName\n//---------------------------------------------------------\n\nstruct StyledPropertyListName {\n const char* name;\n const std::vector* spl;\n SubStyle ss;\n };\n\n//---------------------------------------------------------\n// namedStyles\n// must be in sync with SubStyle enumeration\n//---------------------------------------------------------\n\nstatic const std::array namedStyles { {\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"default\"), &defaultStyle, SubStyle::DEFAULT },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Title\"), &titleStyle, SubStyle::TITLE },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Subtitle\"), &subTitleStyle, SubStyle::SUBTITLE },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Composer\"), &composerStyle, SubStyle::COMPOSER },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Lyricist\"), &lyricistStyle, SubStyle::POET },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Lyrics Odd Lines\"), &lyricsOddStyle, SubStyle::LYRIC1 },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Lyrics Even Lines\"), &lyricsEvenStyle, SubStyle::LYRIC2 },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Fingering\"), &fingeringStyle, SubStyle::FINGERING },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"LH Guitar Fingering\"), &lhGuitarFingeringStyle, SubStyle::LH_GUITAR_FINGERING },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"RH Guitar Fingering\"), &rhGuitarFingeringStyle, SubStyle::RH_GUITAR_FINGERING },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"String Number\"), &stringNumberStyle, SubStyle::STRING_NUMBER },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Instrument Name (Long)\"), &longInstrumentStyle, SubStyle::INSTRUMENT_LONG },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Instrument Name (Short)\"), &shortInstrumentStyle, SubStyle::INSTRUMENT_SHORT },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Instrument Name (Part)\"), &partInstrumentStyle, SubStyle::INSTRUMENT_EXCERPT },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Dynamics\"), &dynamicsStyle, SubStyle::DYNAMICS },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Expression\"), &expressionStyle, SubStyle::EXPRESSION },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Tempo\"), &tempoStyle, SubStyle::TEMPO },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Metronome\"), &metronomeStyle, SubStyle::METRONOME },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Measure Number\"), &measureNumberStyle, SubStyle::MEASURE_NUMBER },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Translator\"), &translatorStyle, SubStyle::TRANSLATOR },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Tuplet\"), &tupletStyle, SubStyle::TUPLET },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"System\"), &systemStyle, SubStyle::SYSTEM },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Staff\"), &staffStyle, SubStyle::STAFF },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Chord Symbol\"), &chordSymbolStyle, SubStyle::HARMONY },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Rehearsal Mark\"), &rehearsalMarkStyle, SubStyle::REHEARSAL_MARK },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Repeat Text Left\"), &repeatLeftStyle, SubStyle::REPEAT_LEFT },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Repeat Text Right\"), &repeatRightStyle, SubStyle::REPEAT_RIGHT },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Volta\"), &voltaStyle, SubStyle::VOLTA },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Frame\"), &frameStyle, SubStyle::FRAME },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Text Line\"), &textLineStyle, SubStyle::TEXTLINE },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Glissando\"), &glissandoStyle, SubStyle::GLISSANDO },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Ottava\"), &ottavaStyle, SubStyle::OTTAVA },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Pedal\"), &pedalStyle, SubStyle::PEDAL },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Hairpin\"), &hairpinStyle, SubStyle::HAIRPIN },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Bend\"), &bendStyle, SubStyle::BEND },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Header\"), &headerStyle, SubStyle::HEADER },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Footer\"), &footerStyle, SubStyle::FOOTER },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Instrument Change\"), &instrumentChangeStyle, SubStyle::INSTRUMENT_CHANGE },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"Figured Bass\"), &figuredBassStyle, SubStyle::FIGURED_BASS },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"User-1\"), &user1Style, SubStyle::USER1 },\n { QT_TRANSLATE_NOOP(\"TextStyle\", \"User-2\"), &user2Style, SubStyle::USER2 },\n } };\n\n//---------------------------------------------------------\n// subStyle\n//---------------------------------------------------------\n\nconst std::vector& subStyle(const char* name)\n {\n for (const StyledPropertyListName& s : namedStyles) {\n if (strcmp(s.name, name) == 0)\n return *s.spl;\n }\n qDebug(\"substyle <%s> not known\", name);\n return *namedStyles[0].spl;\n }\n\nconst std::vector& subStyle(SubStyle idx)\n {\n return *namedStyles[int(idx)].spl;\n }\n\n//---------------------------------------------------------\n// subStyleFromName\n//---------------------------------------------------------\n\nSubStyle subStyleFromName(const QString& name)\n {\n for (const StyledPropertyListName& s : namedStyles) {\n if (s.name == name)\n return SubStyle(s.ss);\n }\n qDebug(\"substyle <%s> not known\", qPrintable(name));\n return SubStyle::DEFAULT;\n }\n\n//---------------------------------------------------------\n// subStyleName\n//---------------------------------------------------------\n\nconst char* subStyleName(SubStyle idx)\n {\n return namedStyles[int(idx)].name;\n }\n\n//---------------------------------------------------------\n// subStyleUserName\n//---------------------------------------------------------\n\nQString subStyleUserName(SubStyle idx)\n {\n return qApp->translate(\"TextStyle\", subStyleName(idx));\n }\n\n//---------------------------------------------------------\n// valueType\n//---------------------------------------------------------\n\nconst char* MStyle::valueType(const StyleIdx i)\n {\n return styleTypes[int(i)].valueType();\n }\n\n//---------------------------------------------------------\n// valueName\n//---------------------------------------------------------\n\nconst char* MStyle::valueName(const StyleIdx i)\n {\n return styleTypes[int(i)].name();\n }\n\n//---------------------------------------------------------\n// styleIdx\n//---------------------------------------------------------\n\nStyleIdx MStyle::styleIdx(const QString &name)\n {\n for (StyleType st : styleTypes) {\n if (st.name() == name)\n return st.styleIdx();\n }\n return StyleIdx::NOSTYLE;\n }\n\n//---------------------------------------------------------\n// Style\n//---------------------------------------------------------\n\nMStyle::MStyle()\n {\n _customChordList = false;\n for (const StyleType& t : styleTypes)\n _values[t.idx()] = t.defaultValue();\n //precomputeValues();\n };\n\n//---------------------------------------------------------\n// precomputeValues\n//---------------------------------------------------------\n\nvoid MStyle::precomputeValues()\n {\n qreal _spatium = value(StyleIdx::spatium).toDouble();\n for (const StyleType& t : styleTypes) {\n if (!strcmp(t.valueType(), \"Ms::Spatium\"))\n _precomputedValues[t.idx()] = _values[t.idx()].value().val() * _spatium;\n }\n }\n\n//---------------------------------------------------------\n// isDefault\n// caution: custom types need to register comparison operator\n// to make this work\n//---------------------------------------------------------\n\nbool MStyle::isDefault(StyleIdx idx) const\n {\n return _values[int(idx)] == MScore::baseStyle().value(idx);\n }\n\n//---------------------------------------------------------\n// chordDescription\n//---------------------------------------------------------\n\nconst ChordDescription* MStyle::chordDescription(int id) const\n {\n if (!_chordList.contains(id))\n return 0;\n return &*_chordList.find(id);\n }\n\n//---------------------------------------------------------\n// setChordList\n//---------------------------------------------------------\n\nvoid MStyle::setChordList(ChordList* cl, bool custom)\n {\n _chordList = *cl;\n _customChordList = custom;\n }\n\n//---------------------------------------------------------\n// set\n//---------------------------------------------------------\n\nvoid MStyle::set(const StyleIdx t, const QVariant& val)\n {\n const int idx = int(t);\n _values[idx] = val;\n if (t == StyleIdx::spatium)\n precomputeValues();\n else {\n if (!strcmp(styleTypes[idx].valueType(), \"Ms::Spatium\")) {\n qreal _spatium = value(StyleIdx::spatium).toDouble();\n _precomputedValues[idx] = _values[idx].value().val() * _spatium;\n }\n }\n }\n\n//---------------------------------------------------------\n// readProperties\n//---------------------------------------------------------\n\nbool MStyle::readProperties(XmlReader& e)\n {\n const QStringRef& tag(e.name());\n QString val(e.readElementText());\n\n for (const StyleType& t : styleTypes) {\n StyleIdx idx = t.styleIdx();\n if (t.name() == tag) {\n const char* type = t.valueType();\n if (!strcmp(\"Ms::Spatium\", type))\n set(idx, Spatium(val.toDouble()));\n else if (!strcmp(\"double\", type))\n set(idx, QVariant(val.toDouble()));\n else if (!strcmp(\"bool\", type))\n set(idx, QVariant(bool(val.toInt())));\n else if (!strcmp(\"int\", type))\n set(idx, QVariant(val.toInt()));\n else if (!strcmp(\"Ms::Direction\", type))\n set(idx, QVariant::fromValue(Direction(val.toInt())));\n else if (!strcmp(\"QString\", type))\n set(idx, QVariant(val));\n else {\n qFatal(\"MStyle::load: unhandled type %s\", type);\n }\n return true;\n }\n }\n return false;\n }\n\n//---------------------------------------------------------\n// load\n//---------------------------------------------------------\n\nbool MStyle::load(QFile* qf)\n {\n XmlReader e(0, qf);\n while (e.readNextStartElement()) {\n if (e.name() == \"museScore\") {\n QString version = e.attribute(\"version\");\n QStringList sl = version.split('.');\n int mscVersion = sl[0].toInt() * 100 + sl[1].toInt();\n if (mscVersion != MSCVERSION)\n return false;\n while (e.readNextStartElement()) {\n if (e.name() == \"Style\")\n load(e);\n else\n e.unknown();\n }\n }\n }\n return true;\n }\n\nvoid MStyle::load(XmlReader& e)\n {\n QString oldChordDescriptionFile = value(StyleIdx::chordDescriptionFile).toString();\n bool chordListTag = false;\n while (e.readNextStartElement()) {\n const QStringRef& tag(e.name());\n\n if (tag == \"TextStyle\") {\n e.skipCurrentElement();\n // TextStyle s;\n //s.read(e);\n // setTextStyle(s);\n }\n else if (tag == \"Spatium\")\n set(StyleIdx::spatium, e.readDouble() * DPMM);\n else if (tag == \"page-layout\")\n // _pageFormat.read(e);\n e.skipCurrentElement();\n else if (tag == \"displayInConcertPitch\")\n set(StyleIdx::concertPitch, QVariant(bool(e.readInt())));\n else if (tag == \"ChordList\") {\n _chordList.clear();\n _chordList.read(e);\n _customChordList = true;\n chordListTag = true;\n }\n else\n readProperties(e);\n }\n\n // if we just specified a new chord description file\n // and didn't encounter a ChordList tag\n // then load the chord description file\n\n QString newChordDescriptionFile = value(StyleIdx::chordDescriptionFile).toString();\n if (newChordDescriptionFile != oldChordDescriptionFile && !chordListTag) {\n if (!newChordDescriptionFile.startsWith(\"chords_\") && value(StyleIdx::chordStyle).toString() == \"std\") {\n // should not normally happen,\n // but treat as \"old\" (114) score just in case\n set(StyleIdx::chordStyle, QVariant(QString(\"custom\")));\n set(StyleIdx::chordsXmlFile, QVariant(true));\n qDebug(\"StyleData::load: custom chord description file %s with chordStyle == std\", qPrintable(newChordDescriptionFile));\n }\n if (value(StyleIdx::chordStyle).toString() == \"custom\")\n _customChordList = true;\n else\n _customChordList = false;\n _chordList.unload();\n }\n\n // make sure we have a chordlist\n if (!_chordList.loaded() && !chordListTag) {\n if (value(StyleIdx::chordsXmlFile).toBool())\n _chordList.read(\"chords.xml\");\n _chordList.read(newChordDescriptionFile);\n }\n }\n\n//---------------------------------------------------------\n// save\n//---------------------------------------------------------\n\nvoid MStyle::save(XmlWriter& xml, bool optimize)\n {\n xml.stag(\"Style\");\n\n for (const StyleType& st : styleTypes) {\n StyleIdx idx = st.styleIdx();\n if (idx == StyleIdx::spatium) // special handling for spatium\n continue;\n if (optimize && isDefault(idx))\n continue;\n const char* type = st.valueType();\n if (!strcmp(\"Ms::Spatium\", type))\n xml.tag(st.name(), value(idx).value().val());\n else if (!strcmp(\"double\", type))\n xml.tag(st.name(), value(idx).toDouble());\n else if (!strcmp(\"bool\", type))\n xml.tag(st.name(), value(idx).toInt());\n else if (!strcmp(\"int\", type))\n xml.tag(st.name(), value(idx).toInt());\n else if (!strcmp(\"Ms::Direction\", type))\n xml.tag(st.name(), value(idx).toInt());\n else if (!strcmp(\"QString\", type))\n xml.tag(st.name(), value(idx).toString());\n else\n qFatal(\"bad style type\");\n }\n if (_customChordList && !_chordList.empty()) {\n xml.stag(\"ChordList\");\n _chordList.write(xml);\n xml.etag();\n }\n xml.tag(\"Spatium\", value(StyleIdx::spatium).toDouble() / DPMM);\n xml.etag();\n }\n\n#ifndef NDEBUG\n//---------------------------------------------------------\n// checkStyles\n//---------------------------------------------------------\n\nvoid checkStyles()\n {\n int idx = 0;\n for (const StyleType& t : styleTypes) {\n Q_ASSERT(t.idx() == idx);\n ++idx;\n }\n idx = 0;\n for (auto a : namedStyles) {\n Q_ASSERT(int(a.ss) == idx);\n ++idx;\n }\n }\n#endif\n\n//---------------------------------------------------------\n// _defaultStyle\n//---------------------------------------------------------\n\nMStyle MScore::_defaultStyle;\n\n}\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":18,"cells":{"file_path":{"kind":"string","value":"libmscore/fingering.cpp"},"num_changed_lines":{"kind":"number","value":170,"string":"170"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2010-2011 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENCE.GPL\n//=============================================================================\n\n#include \"fingering.h\"\n#include \"score.h\"\n#include \"staff.h\"\n#include \"undo.h\"\n#include \"xml.h\"\n#include \"chord.h\"\n#include \"part.h\"\n#include \"measure.h\"\n#include \"stem.h\"\n\nnamespace Ms {\n\n//---------------------------------------------------------\n// Fingering\n//---------------------------------------------------------\n\nFingering::Fingering(Score* s)\n : Text(SubStyle::FINGERING, s)\n {\n setFlag(ElementFlag::HAS_TAG, true); // this is a layered element\n }\n\n//---------------------------------------------------------\n// write\n//---------------------------------------------------------\n\nvoid Fingering::write(XmlWriter& xml) const\n {\n if (!xml.canWrite(this))\n return;\n xml.stag(name());\n Text::writeProperties(xml);\n xml.etag();\n }\n\n//---------------------------------------------------------\n// read\n//---------------------------------------------------------\n\nvoid Fingering::read(XmlReader& e)\n {\n while (e.readNextStartElement()) {\n if (!Text::readProperties(e))\n e.unknown();\n }\n }\n\n//---------------------------------------------------------\n// layout\n//---------------------------------------------------------\n\nvoid Fingering::layout()\n {\n Text::layout();\n\n if (autoplace() && note()) {\n Chord* chord = note()->chord();\n Staff* staff = chord->staff();\n Part* part = staff->part();\n int n = part->nstaves();\n bool voices = chord->measure()->hasVoices(staff->idx());\n bool below = voices ? !chord->up() : (n > 1) && (staff->rstaff() == n-1);\n bool tight = voices && !chord->beam();\n\n qreal x = 0.0;\n qreal y = 0.0;\n qreal headWidth = note()->headWidth();\n qreal headHeight = note()->headHeight();\n qreal fh = headHeight; // TODO: fingering number height\n\n if (chord->notes().size() == 1) {\n x = headWidth * .5;\n if (below) {\n // place fingering below note\n y = fh + spatium() * .4;\n if (tight) {\n y += 0.5 * spatium();\n if (chord->stem())\n x += 0.5 * spatium();\n }\n else if (chord->stem() && !chord->up()) {\n // on stem side\n y += chord->stem()->height();\n x -= spatium() * .4;\n }\n }\n else {\n // place fingering above note\n y = -headHeight - spatium() * .4;\n if (tight) {\n y -= 0.5 * spatium();\n if (chord->stem())\n x -= 0.5 * spatium();\n }\n else if (chord->stem() && chord->up()) {\n // on stem side\n y -= chord->stem()->height();\n x += spatium() * .4;\n }\n }\n }\n else {\n x -= spatium();\n }\n setUserOff(QPointF(x, y));\n }\n }\n\n//---------------------------------------------------------\n// draw\n//---------------------------------------------------------\n\nvoid Fingering::draw(QPainter* painter) const\n {\n Text::draw(painter);\n }\n\n//---------------------------------------------------------\n// accessibleInfo\n//---------------------------------------------------------\n\nQString Fingering::accessibleInfo() const\n {\n QString rez = Element::accessibleInfo();\n if (subStyle() == SubStyle::STRING_NUMBER) {\n rez += \" \" + tr(\"String number\");\n }\n return QString(\"%1: %2\").arg(rez).arg(plainText());\n }\n\n//---------------------------------------------------------\n// getProperty\n//---------------------------------------------------------\n\nQVariant Fingering::getProperty(P_ID propertyId) const\n {\n switch (propertyId) {\n default:\n return Text::getProperty(propertyId);\n }\n }\n\n//---------------------------------------------------------\n// setProperty\n//---------------------------------------------------------\n\nbool Fingering::setProperty(P_ID propertyId, const QVariant& v)\n {\n switch (propertyId) {\n default:\n return Text::setProperty(propertyId, v);\n }\n triggerLayout();\n return true;\n }\n\n//---------------------------------------------------------\n// propertyDefault\n//---------------------------------------------------------\n\nQVariant Fingering::propertyDefault(P_ID id) const\n {\n switch (id) {\n case P_ID::SUB_STYLE:\n return int(SubStyle::FINGERING);\n default:\n return Text::propertyDefault(id);\n }\n }\n\n//---------------------------------------------------------\n// propertyStyle\n//---------------------------------------------------------\n\nPropertyFlags Fingering::propertyFlags(P_ID id) const\n {\n switch (id) {\n default:\n return Text::propertyFlags(id);\n }\n }\n\n//---------------------------------------------------------\n// resetProperty\n//---------------------------------------------------------\n\nvoid Fingering::resetProperty(P_ID id)\n {\n switch (id) {\n default:\n return Text::resetProperty(id);\n }\n }\n\n//---------------------------------------------------------\n// getPropertyStyle\n//---------------------------------------------------------\n\nStyleIdx Fingering::getPropertyStyle(P_ID id) const\n {\n switch (id) {\n default:\n return Text::getPropertyStyle(id);\n }\n return StyleIdx::NOSTYLE;\n }\n\n//---------------------------------------------------------\n// styleChanged\n// reset all styled values to actual style\n//---------------------------------------------------------\n\nvoid Fingering::styleChanged()\n {\n Text::styleChanged();\n }\n\n//---------------------------------------------------------\n// reset\n//---------------------------------------------------------\n\nvoid Fingering::reset()\n {\n Text::reset();\n }\n\n//---------------------------------------------------------\n// subtypeName\n//---------------------------------------------------------\n\nQString Fingering::subtypeName() const\n {\n return subStyleName(subStyle());\n }\n\n}\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":19,"cells":{"file_path":{"kind":"string","value":"libmscore/property.cpp"},"num_changed_lines":{"kind":"number","value":291,"string":"291"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2011 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENCE.GPL\n//=============================================================================\n\n#include \"property.h\"\n#include \"mscore.h\"\n#include \"layoutbreak.h\"\n#include \"groups.h\"\n#include \"xml.h\"\n#include \"note.h\"\n#include \"barline.h\"\n#include \"style.h\"\n#include \"sym.h\"\n\nnamespace Ms {\n\n//---------------------------------------------------------\n// PropertyData\n//---------------------------------------------------------\n\nstruct PropertyData {\n P_ID id;\n const char* qml; // qml name of property\n bool link; // link this property for linked elements\n const char* name; // xml name of property\n P_TYPE type;\n };\n\n//\n// always: propertyList[subtype].id == subtype\n//\n//\nstatic const PropertyData propertyList[] = {\n { P_ID::SUBTYPE, \"subtype\", false, \"subtype\", P_TYPE::INT },\n { P_ID::SELECTED, \"selected\", false, \"selected\", P_TYPE::BOOL },\n { P_ID::GENERATED, \"generated\", false, \"generated\", P_TYPE::BOOL },\n { P_ID::COLOR, \"color\", false, \"color\", P_TYPE::COLOR },\n { P_ID::VISIBLE, \"visible\", false, \"visible\", P_TYPE::BOOL },\n { P_ID::Z, \"z\", false, \"z\", P_TYPE::INT },\n { P_ID::SMALL, \"small\", false, \"small\", P_TYPE::BOOL },\n { P_ID::SHOW_COURTESY, \"show_courtesy\", false, \"showCourtesy\", P_TYPE::INT },\n { P_ID::LINE_TYPE, \"line_type\", false, \"lineType\", P_TYPE::INT },\n { P_ID::PITCH, \"pitch\", true, \"pitch\", P_TYPE::INT },\n\n { P_ID::TPC1, \"tpc1\", true, \"tpc\", P_TYPE::INT },\n { P_ID::TPC2, \"tpc1\", true, \"tpc2\", P_TYPE::INT },\n { P_ID::LINE, \"line\", false, \"line\", P_TYPE::INT },\n { P_ID::FIXED, \"fixed\", false, \"fixed\", P_TYPE::BOOL },\n { P_ID::FIXED_LINE, \"fixed_line\", false, \"fixedLine\", P_TYPE::INT },\n { P_ID::HEAD_TYPE, \"head_type\", false, \"headType\", P_TYPE::HEAD_TYPE },\n { P_ID::HEAD_GROUP, \"head_group\", false, \"head\", P_TYPE::HEAD_GROUP },\n { P_ID::VELO_TYPE, \"velo_type\", false, \"veloType\", P_TYPE::VALUE_TYPE },\n { P_ID::VELO_OFFSET, \"velo_offset\", false, \"velocity\", P_TYPE::INT },\n { P_ID::ARTICULATION_ANCHOR, \"articulation_anchor\", false, \"anchor\", P_TYPE::INT },\n\n { P_ID::DIRECTION, \"direction\", false, \"direction\", P_TYPE::DIRECTION },\n { P_ID::STEM_DIRECTION, \"stem_direction\", true, \"StemDirection\", P_TYPE::DIRECTION },\n { P_ID::NO_STEM, \"no_stem\", false, \"noStem\", P_TYPE::INT },\n { P_ID::SLUR_DIRECTION, \"slur_direction\", false, \"up\", P_TYPE::DIRECTION },\n { P_ID::LEADING_SPACE, \"leading_space\", false, \"leadingSpace\", P_TYPE::SPATIUM },\n { P_ID::DISTRIBUTE, \"distribute\", false, \"distribute\", P_TYPE::BOOL },\n { P_ID::MIRROR_HEAD, \"mirror_head\", false, \"mirror\", P_TYPE::DIRECTION_H },\n { P_ID::DOT_POSITION, \"dot_position\", false, \"dotPosition\", P_TYPE::DIRECTION },\n { P_ID::TUNING, \"tuning\", false, \"tuning\", P_TYPE::REAL },\n { P_ID::PAUSE, \"pause\", true, \"pause\", P_TYPE::REAL },\n\n { P_ID::BARLINE_TYPE, \"barline_type\", false, \"subtype\", P_TYPE::BARLINE_TYPE },\n { P_ID::BARLINE_SPAN, \"barline_span\", false, \"span\", P_TYPE::BOOL },\n { P_ID::BARLINE_SPAN_FROM, \"barline_span_from\", false, \"spanFromOffset\", P_TYPE::INT },\n { P_ID::BARLINE_SPAN_TO, \"barline_span_to\", false, \"spanToOffset\", P_TYPE::INT },\n { P_ID::USER_OFF, \"user_off\", false, \"userOff\", P_TYPE::POINT },\n { P_ID::FRET, \"fret\", true, \"fret\", P_TYPE::INT },\n { P_ID::STRING, \"string\", true, \"string\", P_TYPE::INT },\n { P_ID::GHOST, \"ghost\", true, \"ghost\", P_TYPE::BOOL },\n { P_ID::PLAY, \"play\", false, \"play\", P_TYPE::BOOL },\n { P_ID::TIMESIG_NOMINAL, \"timesig_nominal\", false, 0, P_TYPE::FRACTION },\n\n { P_ID::TIMESIG_ACTUAL, \"timesig_actual\", true, 0, P_TYPE::FRACTION },\n { P_ID::NUMBER_TYPE, \"number_type\", false, \"numberType\", P_TYPE::INT },\n { P_ID::BRACKET_TYPE, \"bracket_type\", false, \"bracketType\", P_TYPE::INT },\n { P_ID::NORMAL_NOTES, \"normal_notes\", false, \"normalNotes\", P_TYPE::INT },\n { P_ID::ACTUAL_NOTES, \"actual_notes\", false, \"actualNotes\", P_TYPE::INT },\n { P_ID::P1, \"p1\", false, \"p1\", P_TYPE::POINT },\n { P_ID::P2, \"p2\", false, \"p2\", P_TYPE::POINT },\n { P_ID::GROW_LEFT, \"grow_left\", false, \"growLeft\", P_TYPE::REAL },\n { P_ID::GROW_RIGHT, \"grow_right\", false, \"growRight\", P_TYPE::REAL },\n { P_ID::BOX_HEIGHT, \"box_height\", false, \"height\", P_TYPE::SPATIUM },\n\n { P_ID::BOX_WIDTH, \"box_width\", false, \"width\", P_TYPE::SPATIUM },\n { P_ID::TOP_GAP, \"top_gap\", false, \"topGap\", P_TYPE::SP_REAL },\n { P_ID::BOTTOM_GAP, \"bottom_gap\", false, \"bottomGap\", P_TYPE::SP_REAL },\n { P_ID::LEFT_MARGIN, \"left_margin\", false, \"leftMargin\", P_TYPE::REAL },\n { P_ID::RIGHT_MARGIN, \"right_margin\", false, \"rightMargin\", P_TYPE::REAL },\n { P_ID::TOP_MARGIN, \"top_margin\", false, \"topMargin\", P_TYPE::REAL },\n { P_ID::BOTTOM_MARGIN, \"bottom_margin\", false, \"bottomMargin\", P_TYPE::REAL },\n { P_ID::LAYOUT_BREAK, \"layout_break\", false, \"subtype\", P_TYPE::LAYOUT_BREAK },\n { P_ID::AUTOSCALE, \"autoscale\", false, \"autoScale\", P_TYPE::BOOL },\n { P_ID::SIZE, \"size\", false, \"size\", P_TYPE::SIZE },\n\n { P_ID::SCALE, \"scale\", false, 0, P_TYPE::SCALE },\n { P_ID::LOCK_ASPECT_RATIO, \"lock_aspect_ratio\", false, \"lockAspectRatio\", P_TYPE::BOOL },\n { P_ID::SIZE_IS_SPATIUM, \"size_is_spatium\", false, \"sizeIsSpatium\", P_TYPE::BOOL },\n { P_ID::TEXT, \"text\", false, 0, P_TYPE::STRING },\n { P_ID::HTML_TEXT, \"html_text\", false, 0, P_TYPE::STRING },\n { P_ID::USER_MODIFIED, \"user_modified\", false, 0, P_TYPE::BOOL },\n { P_ID::BEAM_POS, \"beam_pos\", false, 0, P_TYPE::POINT },\n { P_ID::BEAM_MODE, \"beam_mode\", true, \"BeamMode\", P_TYPE::BEAM_MODE },\n { P_ID::BEAM_NO_SLOPE, \"beam_no_slope\", true, \"noSlope\", P_TYPE::BOOL },\n { P_ID::USER_LEN, \"user_len\", false, \"userLen\", P_TYPE::REAL },\n\n { P_ID::SPACE, \"space\", false, \"space\", P_TYPE::SP_REAL },\n { P_ID::TEMPO, \"tempo\", true, \"tempo\", P_TYPE::TEMPO },\n { P_ID::TEMPO_FOLLOW_TEXT, \"tempo_follow_text\", true, \"followText\", P_TYPE::BOOL },\n { P_ID::ACCIDENTAL_BRACKET, \"accidental_bracket\", false, \"bracket\", P_TYPE::BOOL },\n { P_ID::NUMERATOR_STRING, \"numerator_string\", false, \"textN\", P_TYPE::STRING },\n { P_ID::DENOMINATOR_STRING, \"denominator_string\", false, \"textD\", P_TYPE::STRING },\n { P_ID::FBPREFIX, \"fbprefix\", false, \"prefix\", P_TYPE::INT },\n { P_ID::FBDIGIT, \"fbdigit\", false, \"digit\", P_TYPE::INT },\n { P_ID::FBSUFFIX, \"fbsuffix\", false, \"suffix\", P_TYPE::INT },\n { P_ID::FBCONTINUATIONLINE, \"fbcontinuationline\", false, \"continuationLine\", P_TYPE::INT },\n\n { P_ID::FBPARENTHESIS1, \"fbparenthesis1\", false, \"\", P_TYPE::INT },\n { P_ID::FBPARENTHESIS2, \"fbparenthesis2\", false, \"\", P_TYPE::INT },\n { P_ID::FBPARENTHESIS3, \"fbparenthesis3\", false, \"\", P_TYPE::INT },\n { P_ID::FBPARENTHESIS4, \"fbparenthesis4\", false, \"\", P_TYPE::INT },\n { P_ID::FBPARENTHESIS5, \"fbparenthesis5\", false, \"\", P_TYPE::INT },\n { P_ID::VOLTA_TYPE, \"volta_type\", false, \"\", P_TYPE::INT },\n { P_ID::OTTAVA_TYPE, \"ottava_type\", false, \"\", P_TYPE::INT },\n { P_ID::NUMBERS_ONLY, \"numbers_only\", false, \"numbersOnly\", P_TYPE::BOOL },\n { P_ID::TRILL_TYPE, \"trill_type\", false, \"\", P_TYPE::INT },\n { P_ID::HAIRPIN_CIRCLEDTIP, \"hairpin_circledtip\", false, \"hairpinCircledTip\", P_TYPE::BOOL },\n\n { P_ID::HAIRPIN_TYPE, \"hairpin_type\", true, \"\", P_TYPE::INT },\n { P_ID::HAIRPIN_HEIGHT, \"hairpin_height\", false, \"hairpinHeight\", P_TYPE::SPATIUM },\n { P_ID::HAIRPIN_CONT_HEIGHT, \"hairpin_cont_height\", false, \"hairpinContHeight\", P_TYPE::SPATIUM },\n { P_ID::VELO_CHANGE, \"velo_change\", true, \"veloChange\", P_TYPE::INT },\n { P_ID::DYNAMIC_RANGE, \"dynamic_range\", true, \"dynType\", P_TYPE::INT },\n { P_ID::PLACEMENT, \"placement\", false, \"placement\", P_TYPE::PLACEMENT },\n { P_ID::VELOCITY, \"velocity\", false, \"velocity\", P_TYPE::INT },\n { P_ID::JUMP_TO, \"jump_to\", false, \"jumpTo\", P_TYPE::STRING },\n { P_ID::PLAY_UNTIL, \"play_until\", false, \"playUntil\", P_TYPE::STRING },\n { P_ID::CONTINUE_AT, \"continue_at\", false, \"continueAt\", P_TYPE::STRING },\n\n/*100*/ { P_ID::LABEL, \"label\", false, \"label\", P_TYPE::STRING },\n { P_ID::MARKER_TYPE, \"marker_type\", false, 0, P_TYPE::INT },\n { P_ID::ARP_USER_LEN1, \"arp_user_len1\", false, 0, P_TYPE::REAL },\n { P_ID::ARP_USER_LEN2, \"arp_user_len2\", false, 0, P_TYPE::REAL },\n { P_ID::REPEAT_END, \"repeat_end\", true, 0, P_TYPE::BOOL },\n { P_ID::REPEAT_START, \"repeat_start\", true, 0, P_TYPE::BOOL },\n { P_ID::REPEAT_JUMP, \"repeat_jump\", true, 0, P_TYPE::BOOL },\n { P_ID::MEASURE_NUMBER_MODE, \"measure_number_mode\", false, \"measureNumberMode\", P_TYPE::INT },\n { P_ID::GLISS_TYPE, \"gliss_type\", false, 0, P_TYPE::INT },\n { P_ID::GLISS_TEXT, \"gliss_text\", false, 0, P_TYPE::STRING },\n\n { P_ID::GLISS_SHOW_TEXT, \"gliss_show_text\", false, 0, P_TYPE::BOOL },\n { P_ID::DIAGONAL, \"diagonal\", false, 0, P_TYPE::BOOL },\n { P_ID::GROUPS, \"groups\", false, 0, P_TYPE::GROUPS },\n { P_ID::LINE_STYLE, \"line_style\", false, \"lineStyle\", P_TYPE::INT },\n { P_ID::LINE_COLOR, \"line_color\", false, 0, P_TYPE::COLOR },\n { P_ID::LINE_WIDTH, \"line_width\", false, \"lineWidth\", P_TYPE::SPATIUM },\n { P_ID::LASSO_POS, \"lasso_pos\", false, 0, P_TYPE::POINT_MM },\n { P_ID::LASSO_SIZE, \"lasso_size\", false, 0, P_TYPE::SIZE_MM },\n { P_ID::TIME_STRETCH, \"time_stretch\", false, \"timeStretch\", P_TYPE::REAL },\n { P_ID::ORNAMENT_STYLE, \"ornament_style\", false, \"ornamentStyle\", P_TYPE::ORNAMENT_STYLE },\n\n { P_ID::TIMESIG, \"timesig\", false, 0, P_TYPE::FRACTION },\n { P_ID::TIMESIG_GLOBAL, \"timesig_global\", false, 0, P_TYPE::FRACTION },\n { P_ID::TIMESIG_STRETCH, \"timesig_stretch\", false, 0, P_TYPE::FRACTION },\n { P_ID::TIMESIG_TYPE, \"timesig_type\", true, 0, P_TYPE::INT },\n { P_ID::SPANNER_TICK, \"spanner_tick\", true, \"tick\", P_TYPE::INT },\n { P_ID::SPANNER_TICKS, \"spanner_ticks\", true, \"ticks\", P_TYPE::INT },\n { P_ID::SPANNER_TRACK2, \"spanner_track2\", true, \"track2\", P_TYPE::INT },\n { P_ID::USER_OFF2, \"user_off2\", false, \"userOff2\", P_TYPE::POINT },\n { P_ID::BEGIN_TEXT_PLACE, \"begin_text_place\", false, \"beginTextPlace\", P_TYPE::INT },\n { P_ID::CONTINUE_TEXT_PLACE, \"continue_text_place\", false, \"continueTextPlace\", P_TYPE::INT },\n\n { P_ID::END_TEXT_PLACE, \"end_text_place\", false, \"endTextPlace\", P_TYPE::INT },\n { P_ID::BEGIN_HOOK, \"begin_hook\", false, \"beginHook\", P_TYPE::BOOL },\n { P_ID::END_HOOK, \"end_hook\", false, \"endHook\", P_TYPE::BOOL },\n { P_ID::BEGIN_HOOK_HEIGHT, \"begin_hook_height\", false, \"beginHookHeight\", P_TYPE::SPATIUM },\n { P_ID::END_HOOK_HEIGHT, \"end_hook_height\", false, \"endHookHeight\", P_TYPE::SPATIUM },\n { P_ID::BEGIN_HOOK_TYPE, \"begin_hook_type\", false, \"beginHookType\", P_TYPE::INT },\n { P_ID::END_HOOK_TYPE, \"end_hook_type\", false, \"endHookType\", P_TYPE::INT },\n { P_ID::BEGIN_TEXT, \"begin_text\", true, \"beginText\", P_TYPE::STRING },\n { P_ID::CONTINUE_TEXT, \"continue_text\", true, \"continueText\", P_TYPE::STRING },\n { P_ID::END_TEXT, \"end_text\", true, \"endText\", P_TYPE::STRING },\n\n { P_ID::BEGIN_TEXT_STYLE, \"begin_text_style\", false, \"beginTextStyle\", P_TYPE::TEXT_STYLE },\n { P_ID::CONTINUE_TEXT_STYLE, \"continue_text_style\", false, \"continueTextStyle\", P_TYPE::TEXT_STYLE },\n { P_ID::END_TEXT_STYLE, \"end_text_style\", false, \"endTextStyle\", P_TYPE::TEXT_STYLE },\n { P_ID::BREAK_MMR, \"break_mmr\", false, \"breakMultiMeasureRest\", P_TYPE::BOOL },\n { P_ID::REPEAT_COUNT, \"repeat_count\", true, \"endRepeat\", P_TYPE::INT },\n { P_ID::USER_STRETCH, \"user_stretch\", false, \"stretch\", P_TYPE::REAL },\n { P_ID::NO_OFFSET, \"no_offset\", false, \"noOffset\", P_TYPE::INT },\n { P_ID::IRREGULAR, \"irregular\", true, \"irregular\", P_TYPE::BOOL },\n { P_ID::ANCHOR, \"anchor\", false, \"anchor\", P_TYPE::INT },\n { P_ID::SLUR_UOFF1, \"slur_uoff1\", false, \"o1\", P_TYPE::POINT },\n//150\n { P_ID::SLUR_UOFF2, \"slur_uoff2\", false, \"o2\", P_TYPE::POINT },\n { P_ID::SLUR_UOFF3, \"slur_uoff3\", false, \"o3\", P_TYPE::POINT },\n { P_ID::SLUR_UOFF4, \"slur_uoff4\", false, \"o4\", P_TYPE::POINT },\n { P_ID::STAFF_MOVE, \"staff_move\", true, \"move\", P_TYPE::INT },\n { P_ID::VERSE, \"verse\", true, \"no\", P_TYPE::ZERO_INT },\n { P_ID::SYLLABIC, \"syllabic\", true, \"syllabic\", P_TYPE::INT },\n { P_ID::LYRIC_TICKS, \"lyric_ticks\", true, \"ticks\", P_TYPE::INT },\n { P_ID::VOLTA_ENDING, \"volta_ending\", true, \"endings\", P_TYPE::INT_LIST },\n { P_ID::LINE_VISIBLE, \"line_visible\", true, \"lineVisible\", P_TYPE::BOOL },\n { P_ID::MAG, \"mag\", false, \"mag\", P_TYPE::REAL },\n\n { P_ID::USE_DRUMSET, \"use_drumset\", false, \"useDrumset\", P_TYPE::BOOL },\n { P_ID::PART_VOLUME, \"part_volume\", false, \"volume\", P_TYPE::INT },\n { P_ID::PART_MUTE, \"part_mute\", false, \"mute\", P_TYPE::BOOL },\n { P_ID::PART_PAN, \"part_pan\", false, \"pan\", P_TYPE::INT },\n { P_ID::PART_REVERB, \"part_reverb\", false, \"reverb\", P_TYPE::INT },\n { P_ID::PART_CHORUS, \"part_chorus\", false, \"chorus\", P_TYPE::INT },\n { P_ID::DURATION, \"duration\", false, 0, P_TYPE::FRACTION },\n { P_ID::DURATION_TYPE, \"duration_type\", false, 0, P_TYPE::TDURATION },\n { P_ID::ROLE, \"role\", false, \"role\", P_TYPE::INT },\n { P_ID::TRACK, \"track\", false, 0, P_TYPE::INT },\n\n { P_ID::GLISSANDO_STYLE, \"glissando_style\", false, \"glissandoStyle\", P_TYPE::GLISSANDO_STYLE },\n { P_ID::FRET_STRINGS, \"fret_strings\", false, \"strings\", P_TYPE::INT },\n { P_ID::FRET_FRETS, \"fret_frets\", false, \"frets\", P_TYPE::INT },\n { P_ID::FRET_BARRE, \"fret_barre\", false, \"barre\", P_TYPE::INT },\n { P_ID::FRET_OFFSET, \"fret_offset\", false, \"fretOffset\", P_TYPE::INT },\n { P_ID::SYSTEM_BRACKET, \"system_bracket\", false, \"type\", P_TYPE::INT },\n { P_ID::GAP, \"gap\", false, 0, P_TYPE::BOOL },\n { P_ID::AUTOPLACE, \"autoplace\", false, 0, P_TYPE::BOOL },\n { P_ID::DASH_LINE_LEN, \"dash_line_len\", false, \"dashLineLength\", P_TYPE::REAL },\n { P_ID::DASH_GAP_LEN, \"dash_gap_len\", false, \"dashGapLength\", P_TYPE::REAL },\n\n { P_ID::TICK, \"tick\", false, 0, P_TYPE::INT },\n { P_ID::PLAYBACK_VOICE1, \"playback_voice1\", false, \"playbackVoice1\", P_TYPE::BOOL },\n { P_ID::PLAYBACK_VOICE2, \"playback_voice2\", false, \"playbackVoice2\", P_TYPE::BOOL },\n { P_ID::PLAYBACK_VOICE3, \"playback_voice3\", false, \"playbackVoice3\", P_TYPE::BOOL },\n { P_ID::PLAYBACK_VOICE4, \"playback_voice4\", false, \"playbackVoice4\", P_TYPE::BOOL },\n { P_ID::SYMBOL, \"symbol\", true, \"symbol\", P_TYPE::SYMID },\n { P_ID::PLAY_REPEATS, \"play_repeats\", false, \"playRepeats\", P_TYPE::BOOL },\n { P_ID::CREATE_SYSTEM_HEADER, \"create_system_header\", false, \"createSystemHeader\", P_TYPE::BOOL },\n { P_ID::STAFF_LINES, \"staff_lines\", true, \"lines\", P_TYPE::INT },\n { P_ID::LINE_DISTANCE, \"line_distance\", true, \"lineDistance\", P_TYPE::SPATIUM },\n { P_ID::STEP_OFFSET, \"step_offset\", true, \"stepOffset\", P_TYPE::INT },\n\n { P_ID::STAFF_SHOW_BARLINES, \"staff_show_barlines\", false, \"\", P_TYPE::BOOL },\n { P_ID::STAFF_SHOW_LEDGERLINES, \"staff_show_ledgerlines\", false, \"\", P_TYPE::BOOL },\n { P_ID::STAFF_SLASH_STYLE, \"staff_slash_style\", false, \"\", P_TYPE::BOOL },\n { P_ID::STAFF_NOTEHEAD_SCHEME, \"staff_notehead_scheme\", false, \"\", P_TYPE::INT },\n { P_ID::STAFF_GEN_CLEF, \"staff_gen_clef\", false, \"\", P_TYPE::BOOL },\n { P_ID::STAFF_GEN_TIMESIG, \"staff_gen_timesig\", false, \"\", P_TYPE::BOOL },\n { P_ID::STAFF_GEN_KEYSIG, \"staff_gen_keysig\", false, \"\", P_TYPE::BOOL },\n { P_ID::STAFF_YOFFSET, \"staff_yoffset\", false, \"\", P_TYPE::SPATIUM },\n { P_ID::STAFF_USERDIST, \"staff_userdist\", false, \"distOffset\", P_TYPE::SP_REAL },\n//200\n { P_ID::STAFF_BARLINE_SPAN, \"staff_barline_span\", false, \"barLineSpan\", P_TYPE::BOOL },\n { P_ID::STAFF_BARLINE_SPAN_FROM, \"staff_barline_span_from\", false, \"barLineSpanFrom\", P_TYPE::INT },\n { P_ID::STAFF_BARLINE_SPAN_TO, \"staff_barline_span_to\", false, \"barLineSpanTo\", P_TYPE::INT },\n\n { P_ID::BRACKET_COLUMN, \"bracket_column\", false, \"level\", P_TYPE::INT },\n { P_ID::INAME_LAYOUT_POSITION, \"iname_layout_position\", false, \"layoutPosition\", P_TYPE::INT },\n\n { P_ID::SUB_STYLE, \"sub_style\", false, \"style\", P_TYPE::SUB_STYLE },\n { P_ID::FONT_FACE, \"font_face\", false, \"family\", P_TYPE::FONT },\n { P_ID::FONT_SIZE, \"font_size\", false, \"size\", P_TYPE::REAL },\n { P_ID::FONT_BOLD, \"font_bold\", false, \"bold\", P_TYPE::BOOL },\n { P_ID::FONT_ITALIC, \"font_italic\", false, \"italic\", P_TYPE::BOOL },\n { P_ID::FONT_UNDERLINE, \"font_underline\", false, \"underline\", P_TYPE::BOOL },\n { P_ID::FRAME, \"has_frame\", false, \"hasFrame\", P_TYPE::BOOL },\n { P_ID::FRAME_SQUARE, \"frame_square\", false, \"frameSquare\", P_TYPE::BOOL },\n { P_ID::FRAME_CIRCLE, \"frame_circle\", false, \"frameCircle\", P_TYPE::BOOL },\n { P_ID::FRAME_WIDTH, \"frame_width\", false, \"frameWidth\", P_TYPE::SPATIUM },\n { P_ID::FRAME_PADDING, \"frame_padding\", false, \"framePadding\", P_TYPE::SPATIUM },\n { P_ID::FRAME_ROUND, \"frame_round\", false, \"frameRound\", P_TYPE::INT },\n { P_ID::FRAME_FG_COLOR, \"frame_fg_color\", false, \"frameFgColor\", P_TYPE::COLOR },\n { P_ID::FRAME_BG_COLOR, \"frame_bg_color\", false, \"frameBgColor\", P_TYPE::COLOR },\n { P_ID::FONT_SPATIUM_DEPENDENT, \"font_spatium_dependent\", false, \"sizeIsSpatiumDependent\", P_TYPE::BOOL },\n { P_ID::ALIGN, \"align\", false, \"align\", P_TYPE::ALIGN },\n { P_ID::OFFSET, \"offset\", false, \"offset\", P_TYPE::POINT },\n { P_ID::OFFSET_TYPE, \"offset_type\", false, \"offsetType\", P_TYPE::INT },\n { P_ID::SYSTEM_FLAG, \"system_flag\", false, \"systemFlag\", P_TYPE::BOOL },\n { P_ID::END, \"\", false, \"\", P_TYPE::INT }\n };\n\n//---------------------------------------------------------\n// propertyType\n//---------------------------------------------------------\n\nP_TYPE propertyType(P_ID id)\n {\n Q_ASSERT( propertyList[int(id)].id == id);\n return propertyList[int(id)].type;\n }\n\n//---------------------------------------------------------\n// propertyLink\n//---------------------------------------------------------\n\nbool propertyLink(P_ID id)\n {\n Q_ASSERT( propertyList[int(id)].id == id);\n return propertyList[int(id)].link;\n }\n\n//---------------------------------------------------------\n// propertyName\n//---------------------------------------------------------\n\nconst char* propertyName(P_ID id)\n {\n Q_ASSERT( propertyList[int(id)].id == id);\n return propertyList[int(id)].name;\n }\n\nconst char* propertyQmlName(P_ID id)\n {\n Q_ASSERT( propertyList[int(id)].id == id);\n return propertyList[int(id)].qml;\n }\n\n//---------------------------------------------------------\n// getProperty\n//---------------------------------------------------------\n\nQVariant getProperty(P_ID id, XmlReader& e)\n {\n switch (propertyType(id)) {\n case P_TYPE::BOOL:\n return QVariant(bool(e.readInt()));\n case P_TYPE::SUBTYPE:\n case P_TYPE::ZERO_INT:\n case P_TYPE::INT:\n return QVariant(e.readInt());\n case P_TYPE::REAL:\n case P_TYPE::SPATIUM:\n case P_TYPE::SP_REAL:\n case P_TYPE::TEMPO:\n return QVariant(e.readDouble());\n case P_TYPE::FRACTION:\n return QVariant::fromValue(e.readFraction());\n case P_TYPE::COLOR:\n return QVariant(e.readColor());\n case P_TYPE::POINT:\n return QVariant(e.readPoint());\n case P_TYPE::SCALE:\n case P_TYPE::SIZE:\n return QVariant(e.readSize());\n case P_TYPE::FONT:\n case P_TYPE::STRING:\n return QVariant(e.readElementText());\n case P_TYPE::GLISSANDO_STYLE: {\n QString value(e.readElementText());\n if ( value == \"whitekeys\")\n return QVariant(int(MScore::GlissandoStyle::WHITE_KEYS));\n else if ( value == \"blackkeys\")\n return QVariant(int(MScore::GlissandoStyle::BLACK_KEYS));\n else if ( value == \"diatonic\")\n return QVariant(int(MScore::GlissandoStyle::DIATONIC));\n else // e.g., normally \"Chromatic\"\n return QVariant(int(MScore::GlissandoStyle::CHROMATIC));\n }\n break;\n case P_TYPE::ORNAMENT_STYLE: {\n QString value(e.readElementText());\n if ( value == \"baroque\")\n return QVariant(int(MScore::OrnamentStyle::BAROQUE));\n return QVariant(int(MScore::OrnamentStyle::DEFAULT));\n }\n\n case P_TYPE::DIRECTION:\n return QVariant::fromValue(Direction(e.readElementText()));\n\n case P_TYPE::DIRECTION_H:\n {\n QString value(e.readElementText());\n if (value == \"left\" || value == \"1\")\n return QVariant(int(MScore::DirectionH::LEFT));\n else if (value == \"right\" || value == \"2\")\n return QVariant(int(MScore::DirectionH::RIGHT));\n else if (value == \"auto\")\n return QVariant(int(MScore::DirectionH::AUTO));\n }\n break;\n case P_TYPE::LAYOUT_BREAK: {\n QString value(e.readElementText());\n if (value == \"line\")\n return QVariant(int(LayoutBreak::LINE));\n if (value == \"page\")\n return QVariant(int(LayoutBreak::PAGE));\n if (value == \"section\")\n return QVariant(int(LayoutBreak::SECTION));\n if (value == \"nobreak\")\n return QVariant(int(LayoutBreak::NOBREAK));\n qDebug(\"getProperty: invalid P_TYPE::LAYOUT_BREAK: <%s>\", qPrintable(value));\n }\n break;\n case P_TYPE::VALUE_TYPE: {\n QString value(e.readElementText());\n if (value == \"offset\")\n return QVariant(int(Note::ValueType::OFFSET_VAL));\n else if (value == \"user\")\n return QVariant(int(Note::ValueType::USER_VAL));\n }\n break;\n case P_TYPE::PLACEMENT: {\n QString value(e.readElementText());\n if (value == \"above\")\n return QVariant(int(Element::Placement::ABOVE));\n else if (value == \"below\")\n return QVariant(int(Element::Placement::BELOW));\n }\n break;\n case P_TYPE::BARLINE_TYPE: {\n bool ok;\n const QString& val(e.readElementText());\n int ct = val.toInt(&ok);\n if (ok)\n return QVariant(ct);\n else {\n BarLineType t = BarLine::barLineType(val);\n return QVariant::fromValue(t);\n }\n }\n break;\n case P_TYPE::BEAM_MODE: // TODO\n return QVariant(int(0));\n\n case P_TYPE::GROUPS:\n {\n Groups g;\n g.read(e);\n return QVariant::fromValue(g);\n }\n case P_TYPE::SYMID:\n return QVariant::fromValue(Sym::name2id(e.readElementText()));\n break;\n case P_TYPE::HEAD_GROUP:\n return QVariant::fromValue(NoteHead::name2group(e.readElementText()));;\n case P_TYPE::HEAD_TYPE:\n return QVariant::fromValue(NoteHead::name2type(e.readElementText()));\n case P_TYPE::POINT_MM: // not supported\n case P_TYPE::TDURATION:\n case P_TYPE::SIZE_MM:\n case P_TYPE::TEXT_STYLE:\n case P_TYPE::INT_LIST:\n return QVariant();\n case P_TYPE::SUB_STYLE:\n return int(subStyleFromName(e.readElementText()));\n case P_TYPE::ALIGN: {\n QString s = e.readElementText();\n QStringList sl = s.split(',');\n if (sl.size() != 2) {\n qDebug(\"bad align text <%s>\", qPrintable(s));\n return QVariant();\n }\n Align align = Align::LEFT;\n if (sl[0] == \"center\")\n align = align | Align::HCENTER;\n else if (sl[0] == \"right\")\n align = align | Align::RIGHT;\n else if (sl[0] == \"left\")\n ;\n else {\n qDebug(\"bad align text <%s>\", qPrintable(sl[0]));\n return QVariant();\n }\n if (sl[1] == \"center\")\n align = align | Align::VCENTER;\n else if (sl[1] == \"bottom\")\n align = align | Align::BOTTOM;\n else if (sl[1] == \"baseline\")\n align = align | Align::BASELINE;\n else if (sl[1] == \"top\")\n ;\n else {\n qDebug(\"bad align text <%s>\", qPrintable(sl[1]));\n return QVariant();\n }\n return int(align);\n }\n }\n return QVariant();\n }\n\n#ifndef NDEBUG\n//---------------------------------------------------------\n// checkProperties\n//---------------------------------------------------------\n\nvoid checkProperties()\n {\n int idx = 0;\n for (const PropertyData& d : propertyList) {\n if (int(d.id) != idx)\n qDebug(\"====%s %d != %d\", d.qml, int(d.id), idx);\n Q_ASSERT(int(d.id) == idx);\n ++idx;\n }\n }\n#endif\n\n\n}\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":20,"cells":{"file_path":{"kind":"string","value":"libmscore/scoreElement.cpp"},"num_changed_lines":{"kind":"number","value":232,"string":"232"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2015 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENCE.GPL\n//=============================================================================\n\n#include \"scoreElement.h\"\n#include \"score.h\"\n#include \"undo.h\"\n#include \"xml.h\"\n\nnamespace Ms {\n\n//\n// list has to be synchronized with ElementType enum\n//\nstatic const ElementName elementNames[] = {\n { ElementType::INVALID, \"invalid\", QT_TRANSLATE_NOOP(\"elementName\", \"invalid\") },\n { ElementType::PART, \"Part\", QT_TRANSLATE_NOOP(\"elementName\", \"Part\") },\n { ElementType::STAFF, \"Staff\", QT_TRANSLATE_NOOP(\"elementName\", \"Staff\") },\n { ElementType::SCORE, \"Score\", QT_TRANSLATE_NOOP(\"elementName\", \"Score\") },\n { ElementType::SYMBOL, \"Symbol\", QT_TRANSLATE_NOOP(\"elementName\", \"Symbol\") },\n { ElementType::TEXT, \"Text\", QT_TRANSLATE_NOOP(\"elementName\", \"Text\") },\n { ElementType::INSTRUMENT_NAME, \"InstrumentName\", QT_TRANSLATE_NOOP(\"elementName\", \"Instrument Name\") },\n { ElementType::SLUR_SEGMENT, \"SlurSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Slur Segment\") },\n { ElementType::TIE_SEGMENT, \"TieSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Tie Segment\") },\n { ElementType::STAFF_LINES, \"StaffLines\", QT_TRANSLATE_NOOP(\"elementName\", \"Staff Lines\") },\n { ElementType::BAR_LINE, \"BarLine\", QT_TRANSLATE_NOOP(\"elementName\", \"Barline\") },\n { ElementType::SYSTEM_DIVIDER, \"SystemDivider\", QT_TRANSLATE_NOOP(\"elementName\", \"System Divider\") },\n { ElementType::STEM_SLASH, \"StemSlash\", QT_TRANSLATE_NOOP(\"elementName\", \"Stem Slash\") },\n { ElementType::LINE, \"Line\", QT_TRANSLATE_NOOP(\"elementName\", \"Line\") },\n { ElementType::ARPEGGIO, \"Arpeggio\", QT_TRANSLATE_NOOP(\"elementName\", \"Arpeggio\") },\n { ElementType::ACCIDENTAL, \"Accidental\", QT_TRANSLATE_NOOP(\"elementName\", \"Accidental\") },\n { ElementType::LEDGER_LINE, \"LedgerLine\", QT_TRANSLATE_NOOP(\"elementName\", \"Ledger Line\") },\n { ElementType::STEM, \"Stem\", QT_TRANSLATE_NOOP(\"elementName\", \"Stem\") },\n { ElementType::NOTE, \"Note\", QT_TRANSLATE_NOOP(\"elementName\", \"Note\") },\n { ElementType::CLEF, \"Clef\", QT_TRANSLATE_NOOP(\"elementName\", \"Clef\") },\n { ElementType::KEYSIG, \"KeySig\", QT_TRANSLATE_NOOP(\"elementName\", \"Key Signature\") },\n { ElementType::AMBITUS, \"Ambitus\", QT_TRANSLATE_NOOP(\"elementName\", \"Ambitus\") },\n { ElementType::TIMESIG, \"TimeSig\", QT_TRANSLATE_NOOP(\"elementName\", \"Time Signature\") },\n { ElementType::REST, \"Rest\", QT_TRANSLATE_NOOP(\"elementName\", \"Rest\") },\n { ElementType::BREATH, \"Breath\", QT_TRANSLATE_NOOP(\"elementName\", \"Breath\") },\n { ElementType::REPEAT_MEASURE, \"RepeatMeasure\", QT_TRANSLATE_NOOP(\"elementName\", \"Repeat Measure\") },\n { ElementType::TIE, \"Tie\", QT_TRANSLATE_NOOP(\"elementName\", \"Tie\") },\n { ElementType::ARTICULATION, \"Articulation\", QT_TRANSLATE_NOOP(\"elementName\", \"Articulation\") },\n { ElementType::CHORDLINE, \"ChordLine\", QT_TRANSLATE_NOOP(\"elementName\", \"Chord Line\") },\n { ElementType::DYNAMIC, \"Dynamic\", QT_TRANSLATE_NOOP(\"elementName\", \"Dynamic\") },\n { ElementType::BEAM, \"Beam\", QT_TRANSLATE_NOOP(\"elementName\", \"Beam\") },\n { ElementType::HOOK, \"Hook\", QT_TRANSLATE_NOOP(\"elementName\", \"Hook\") },\n { ElementType::LYRICS, \"Lyrics\", QT_TRANSLATE_NOOP(\"elementName\", \"Lyrics\") },\n { ElementType::FIGURED_BASS, \"FiguredBass\", QT_TRANSLATE_NOOP(\"elementName\", \"Figured Bass\") },\n { ElementType::MARKER, \"Marker\", QT_TRANSLATE_NOOP(\"elementName\", \"Marker\") },\n { ElementType::JUMP, \"Jump\", QT_TRANSLATE_NOOP(\"elementName\", \"Jump\") },\n { ElementType::FINGERING, \"Fingering\", QT_TRANSLATE_NOOP(\"elementName\", \"Fingering\") },\n { ElementType::TUPLET, \"Tuplet\", QT_TRANSLATE_NOOP(\"elementName\", \"Tuplet\") },\n { ElementType::TEMPO_TEXT, \"Tempo\", QT_TRANSLATE_NOOP(\"elementName\", \"Tempo\") },\n { ElementType::STAFF_TEXT, \"StaffText\", QT_TRANSLATE_NOOP(\"elementName\", \"Staff Text\") },\n { ElementType::SYSTEM_TEXT, \"SystemText\", QT_TRANSLATE_NOOP(\"elementName\", \"System Text\") },\n { ElementType::REHEARSAL_MARK, \"RehearsalMark\", QT_TRANSLATE_NOOP(\"elementName\", \"Rehearsal Mark\") },\n { ElementType::INSTRUMENT_CHANGE, \"InstrumentChange\", QT_TRANSLATE_NOOP(\"elementName\", \"Instrument Change\") },\n { ElementType::STAFFTYPE_CHANGE, \"StaffTypeChange\", QT_TRANSLATE_NOOP(\"elementName\", \"Staff Typeype Change\") },\n { ElementType::HARMONY, \"Harmony\", QT_TRANSLATE_NOOP(\"elementName\", \"Chord Symbol\") },\n { ElementType::FRET_DIAGRAM, \"FretDiagram\", QT_TRANSLATE_NOOP(\"elementName\", \"Fretboard Diagram\") },\n { ElementType::BEND, \"Bend\", QT_TRANSLATE_NOOP(\"elementName\", \"Bend\") },\n { ElementType::TREMOLOBAR, \"TremoloBar\", QT_TRANSLATE_NOOP(\"elementName\", \"Tremolo Bar\") },\n { ElementType::VOLTA, \"Volta\", QT_TRANSLATE_NOOP(\"elementName\", \"Volta\") },\n { ElementType::HAIRPIN_SEGMENT, \"HairpinSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Hairpin Segment\") },\n { ElementType::OTTAVA_SEGMENT, \"OttavaSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Ottava Segment\") },\n { ElementType::TRILL_SEGMENT, \"TrillSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Trill Segment\") },\n { ElementType::TEXTLINE_SEGMENT, \"TextLineSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Text Line Segment\") },\n { ElementType::VOLTA_SEGMENT, \"VoltaSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Volta Segment\") },\n { ElementType::PEDAL_SEGMENT, \"PedalSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Pedal Segment\") },\n { ElementType::LYRICSLINE_SEGMENT, \"LyricsLineSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Melisma Line Segment\") },\n { ElementType::GLISSANDO_SEGMENT, \"GlissandoSegment\", QT_TRANSLATE_NOOP(\"elementName\", \"Glissando Segment\") },\n { ElementType::LAYOUT_BREAK, \"LayoutBreak\", QT_TRANSLATE_NOOP(\"elementName\", \"Layout Break\") },\n { ElementType::SPACER, \"Spacer\", QT_TRANSLATE_NOOP(\"elementName\", \"Spacer\") },\n { ElementType::STAFF_STATE, \"StaffState\", QT_TRANSLATE_NOOP(\"elementName\", \"Staff State\") },\n { ElementType::NOTEHEAD, \"NoteHead\", QT_TRANSLATE_NOOP(\"elementName\", \"Notehead\") },\n { ElementType::NOTEDOT, \"NoteDot\", QT_TRANSLATE_NOOP(\"elementName\", \"Note Dot\") },\n { ElementType::TREMOLO, \"Tremolo\", QT_TRANSLATE_NOOP(\"elementName\", \"Tremolo\") },\n { ElementType::IMAGE, \"Image\", QT_TRANSLATE_NOOP(\"elementName\", \"Image\") },\n { ElementType::MEASURE, \"Measure\", QT_TRANSLATE_NOOP(\"elementName\", \"Measure\") },\n { ElementType::SELECTION, \"Selection\", QT_TRANSLATE_NOOP(\"elementName\", \"Selection\") },\n { ElementType::LASSO, \"Lasso\", QT_TRANSLATE_NOOP(\"elementName\", \"Lasso\") },\n { ElementType::SHADOW_NOTE, \"ShadowNote\", QT_TRANSLATE_NOOP(\"elementName\", \"Shadow Note\") },\n { ElementType::TAB_DURATION_SYMBOL, \"TabDurationSymbol\", QT_TRANSLATE_NOOP(\"elementName\", \"Tab Duration Symbol\") },\n { ElementType::FSYMBOL, \"FSymbol\", QT_TRANSLATE_NOOP(\"elementName\", \"Font Symbol\") },\n { ElementType::PAGE, \"Page\", QT_TRANSLATE_NOOP(\"elementName\", \"Page\") },\n { ElementType::HAIRPIN, \"HairPin\", QT_TRANSLATE_NOOP(\"elementName\", \"Hairpin\") },\n { ElementType::OTTAVA, \"Ottava\", QT_TRANSLATE_NOOP(\"elementName\", \"Ottava\") },\n { ElementType::PEDAL, \"Pedal\", QT_TRANSLATE_NOOP(\"elementName\", \"Pedal\") },\n { ElementType::TRILL, \"Trill\", QT_TRANSLATE_NOOP(\"elementName\", \"Trill\") },\n { ElementType::TEXTLINE, \"TextLine\", QT_TRANSLATE_NOOP(\"elementName\", \"Text Line\") },\n { ElementType::TEXTLINE_BASE, \"TextLineBase\", QT_TRANSLATE_NOOP(\"elementName\", \"Text Line Base\") }, // remove\n { ElementType::NOTELINE, \"NoteLine\", QT_TRANSLATE_NOOP(\"elementName\", \"Note Line\") },\n { ElementType::LYRICSLINE, \"LyricsLine\", QT_TRANSLATE_NOOP(\"elementName\", \"Melisma Line\") },\n { ElementType::GLISSANDO, \"Glissando\", QT_TRANSLATE_NOOP(\"elementName\", \"Glissando\") },\n { ElementType::BRACKET, \"Bracket\", QT_TRANSLATE_NOOP(\"elementName\", \"Bracket\") },\n { ElementType::SEGMENT, \"Segment\", QT_TRANSLATE_NOOP(\"elementName\", \"Segment\") },\n { ElementType::SYSTEM, \"System\", QT_TRANSLATE_NOOP(\"elementName\", \"System\") },\n { ElementType::COMPOUND, \"Compound\", QT_TRANSLATE_NOOP(\"elementName\", \"Compound\") },\n { ElementType::CHORD, \"Chord\", QT_TRANSLATE_NOOP(\"elementName\", \"Chord\") },\n { ElementType::SLUR, \"Slur\", QT_TRANSLATE_NOOP(\"elementName\", \"Slur\") },\n { ElementType::ELEMENT, \"Element\", QT_TRANSLATE_NOOP(\"elementName\", \"Element\") },\n { ElementType::ELEMENT_LIST, \"ElementList\", QT_TRANSLATE_NOOP(\"elementName\", \"Element List\") },\n { ElementType::STAFF_LIST, \"StaffList\", QT_TRANSLATE_NOOP(\"elementName\", \"Staff List\") },\n { ElementType::MEASURE_LIST, \"MeasureList\", QT_TRANSLATE_NOOP(\"elementName\", \"Measure List\") },\n { ElementType::HBOX, \"HBox\", QT_TRANSLATE_NOOP(\"elementName\", \"Horizontal Frame\") },\n { ElementType::VBOX, \"VBox\", QT_TRANSLATE_NOOP(\"elementName\", \"Vertical Frame\") },\n { ElementType::TBOX, \"TBox\", QT_TRANSLATE_NOOP(\"elementName\", \"Text Frame\") },\n { ElementType::FBOX, \"FBox\", QT_TRANSLATE_NOOP(\"elementName\", \"Fretboard Diagram Frame\") },\n { ElementType::ICON, \"Icon\", QT_TRANSLATE_NOOP(\"elementName\", \"Icon\") },\n { ElementType::OSSIA, \"Ossia\", QT_TRANSLATE_NOOP(\"elementName\", \"Ossia\") },\n { ElementType::BAGPIPE_EMBELLISHMENT,\"BagpipeEmbellishment\", QT_TRANSLATE_NOOP(\"elementName\", \"Bagpipe Embellishment\") }\n };\n\n//---------------------------------------------------------\n// ScoreElement\n//---------------------------------------------------------\n\nScoreElement::ScoreElement(const ScoreElement& se)\n : QObject(0)\n {\n _score = se._score;\n _links = 0;\n }\n\n//---------------------------------------------------------\n// ~ScoreElement\n//---------------------------------------------------------\n\nScoreElement::~ScoreElement()\n {\n if (_links) {\n _links->removeOne(this);\n if (_links->empty()) {\n delete _links;\n _links = 0;\n }\n }\n }\n\n//---------------------------------------------------------\n// resetProperty\n//---------------------------------------------------------\n\nvoid ScoreElement::resetProperty(P_ID id)\n {\n QVariant v = propertyDefault(id);\n if (v.isValid())\n setProperty(id, v);\n }\n\n//---------------------------------------------------------\n// undoResetProperty\n//---------------------------------------------------------\n\nvoid ScoreElement::undoResetProperty(P_ID id)\n {\n PropertyFlags f = propertyFlags(id);\n if (f == PropertyFlags::UNSTYLED)\n undoChangeProperty(id, propertyDefault(id), PropertyFlags::STYLED);\n else\n undoChangeProperty(id, propertyDefault(id), f);\n }\n\n//---------------------------------------------------------\n// undoChangeProperty\n//---------------------------------------------------------\n\nvoid ScoreElement::undoChangeProperty(P_ID id, const QVariant& v)\n {\n undoChangeProperty(id, v, propertyFlags(id));\n }\n\nvoid ScoreElement::undoChangeProperty(P_ID id, const QVariant& v, PropertyFlags ps)\n {\n if (id == P_ID::AUTOPLACE && v.toBool() && !getProperty(id).toBool()) {\n // special case: if we switch to autoplace, we must save\n // user offset values\n undoResetProperty(P_ID::USER_OFF);\n if (isSlurSegment()) {\n undoResetProperty(P_ID::SLUR_UOFF1);\n undoResetProperty(P_ID::SLUR_UOFF2);\n undoResetProperty(P_ID::SLUR_UOFF3);\n undoResetProperty(P_ID::SLUR_UOFF4);\n }\n }\n else if (id == P_ID::SUB_STYLE) {\n //\n // change a list of properties\n //\n auto l = subStyle(SubStyle(v.toInt()));\n // Change to SubStyle defaults\n for (const StyledProperty& p : l)\n score()->undoChangeProperty(this, p.propertyIdx, score()->styleV(p.styleIdx), PropertyFlags::STYLED);\n }\n score()->undoChangeProperty(this, id, v, ps);\n }\n\n//---------------------------------------------------------\n// undoPushProperty\n//---------------------------------------------------------\n\nvoid ScoreElement::undoPushProperty(P_ID id)\n {\n QVariant val = getProperty(id);\n score()->undoStack()->push1(new ChangeProperty(this, id, val));\n }\n\n//---------------------------------------------------------\n// writeProperty\n//---------------------------------------------------------\n\nvoid ScoreElement::writeProperty(XmlWriter& xml, P_ID id) const\n {\n if (propertyType(id) == P_TYPE::SP_REAL) {\n qreal _spatium = score()->spatium();\n xml.tag(id, QVariant(getProperty(id).toReal()/_spatium),\n QVariant(propertyDefault(id).toReal()/_spatium));\n }\n else\n xml.tag(id, getProperty(id), propertyDefault(id));\n }\n\n//---------------------------------------------------------\n// linkTo\n//---------------------------------------------------------\n\nvoid ScoreElement::linkTo(ScoreElement* element)\n {\n Q_ASSERT(element != this);\n if (!_links) {\n if (element->links()) {\n _links = element->_links;\n Q_ASSERT(_links->contains(element));\n }\n else {\n _links = new LinkedElements(score());\n _links->append(element);\n element->_links = _links;\n }\n Q_ASSERT(!_links->contains(this));\n _links->append(this);\n }\n else {\n _links->append(element);\n element->_links = _links;\n }\n }\n\n//---------------------------------------------------------\n// unlink\n//---------------------------------------------------------\n\nvoid ScoreElement::unlink()\n {\n if (_links) {\n Q_ASSERT(_links->contains(this));\n _links->removeOne(this);\n\n // if link list is empty, remove list\n if (_links->size() <= 1) {\n if (!_links->empty()) // abnormal case: only \"this\" is in list\n _links->front()->_links = 0;\n delete _links;\n }\n _links = 0;\n }\n }\n\n//---------------------------------------------------------\n// undoUnlink\n//---------------------------------------------------------\n\nvoid ScoreElement::undoUnlink()\n {\n if (_links)\n _score->undo(new Unlink(this));\n }\n\n//---------------------------------------------------------\n// linkList\n//---------------------------------------------------------\n\nQList ScoreElement::linkList() const\n {\n QList el;\n if (links())\n el.append(*links());\n else\n el.append((Element*)this);\n return el;\n }\n\n//---------------------------------------------------------\n// LinkedElements\n//---------------------------------------------------------\n\nLinkedElements::LinkedElements(Score* score)\n {\n _lid = score->linkId(); // create new unique id\n }\n\nLinkedElements::LinkedElements(Score* score, int id)\n {\n _lid = id;\n score->linkId(id); // remember used id\n }\n\n//---------------------------------------------------------\n// setLid\n//---------------------------------------------------------\n\nvoid LinkedElements::setLid(Score* score, int id)\n {\n _lid = id;\n score->linkId(id);\n }\n\n//---------------------------------------------------------\n// masterScore\n//---------------------------------------------------------\n\nMasterScore* ScoreElement::masterScore() const\n {\n return _score->masterScore();\n }\n\n//---------------------------------------------------------\n// propertyStyle\n//---------------------------------------------------------\n\nPropertyFlags ScoreElement::propertyFlags(P_ID) const\n {\n return PropertyFlags::NOSTYLE;\n }\n\n//---------------------------------------------------------\n// getPropertyStyle\n//---------------------------------------------------------\n\nStyleIdx ScoreElement::getPropertyStyle(P_ID) const\n {\n return StyleIdx::NOSTYLE;\n }\n\n//---------------------------------------------------------\n// name\n//---------------------------------------------------------\n\nconst char* ScoreElement::name() const\n {\n return name(type());\n }\n\n//---------------------------------------------------------\n// name\n//---------------------------------------------------------\n\nconst char* ScoreElement::name(ElementType type)\n {\n return elementNames[int(type)].name;\n }\n\n//---------------------------------------------------------\n// userName\n//---------------------------------------------------------\n\nQString ScoreElement::userName() const\n {\n return qApp->translate(\"elementName\", elementNames[int(type())].userName);\n }\n\n//---------------------------------------------------------\n// name2type\n//---------------------------------------------------------\n\nElementType ScoreElement::name2type(const QStringRef& s)\n {\n for (int i = 0; i < int(ElementType::MAXTYPE); ++i) {\n if (s == elementNames[i].name)\n return ElementType(i);\n }\n qDebug(\"unknown type\");\n return ElementType::INVALID;\n }\n\n//---------------------------------------------------------\n// isSLine\n//---------------------------------------------------------\n\nbool ScoreElement::isSLine() const\n {\n return isHairpin() || isOttava() || isPedal()\n || isTrill() || isVolta() || isTextLine() || isNoteLine() || isGlissando();\n }\n\n//---------------------------------------------------------\n// isSLineSegment\n//---------------------------------------------------------\n\nbool ScoreElement::isSLineSegment() const\n {\n return isHairpinSegment() || isOttavaSegment() || isPedalSegment()\n || isTrillSegment() || isVoltaSegment() || isTextLineSegment()\n || isGlissandoSegment();\n }\n\n//---------------------------------------------------------\n// isText\n//---------------------------------------------------------\n\nbool ScoreElement::isText() const\n {\n return type() == ElementType::TEXT\n || type() == ElementType::LYRICS\n || type() == ElementType::DYNAMIC\n || type() == ElementType::FINGERING\n || type() == ElementType::HARMONY\n || type() == ElementType::MARKER\n || type() == ElementType::JUMP\n || type() == ElementType::STAFF_TEXT\n || type() == ElementType::REHEARSAL_MARK\n || type() == ElementType::INSTRUMENT_CHANGE\n || type() == ElementType::FIGURED_BASS\n || type() == ElementType::TEMPO_TEXT\n || type() == ElementType::INSTRUMENT_NAME\n ;\n }\n}\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":21,"cells":{"file_path":{"kind":"string","value":"libmscore/systemtext.cpp"},"num_changed_lines":{"kind":"number","value":61,"string":"61"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2011 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENCE.GPL\n//=============================================================================\n\n#include \"systemtext.h\"\n\nnamespace Ms {\n\n//---------------------------------------------------------\n// SystemText\n//---------------------------------------------------------\n\nSystemText::SystemText(Score* s)\n : StaffText(SubStyle::SYSTEM, s)\n {\n setSystemFlag(true);\n }\n\nSystemText::SystemText(SubStyle ss, Score* s)\n : StaffText(ss, s)\n {\n setSystemFlag(true);\n }\n\n//---------------------------------------------------------\n// propertyDefault\n//---------------------------------------------------------\n\nQVariant SystemText::propertyDefault(P_ID id) const\n {\n switch (id) {\n case P_ID::SUB_STYLE:\n return int(SubStyle::SYSTEM);\n default:\n return StaffText::propertyDefault(id);\n }\n }\n\n//---------------------------------------------------------\n// write\n//---------------------------------------------------------\n\nvoid SystemText::write(XmlWriter& xml) const\n {\n if (!xml.canWrite(this))\n return;\n xml.stag(\"SystemText\");\n StaffText::writeProperties(xml);\n xml.etag();\n }\n\n} // namespace Ms\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":22,"cells":{"file_path":{"kind":"string","value":"mscore/inspector/inspectorFingering.cpp"},"num_changed_lines":{"kind":"number","value":61,"string":"61"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2013-2017 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENSE.GPL\n//=============================================================================\n\n#include \"inspectorFingering.h\"\n#include \"musescore.h\"\n#include \"libmscore/fingering.h\"\n#include \"libmscore/score.h\"\n\nnamespace Ms {\n\n//---------------------------------------------------------\n// InspectorFingering\n//---------------------------------------------------------\n\nInspectorFingering::InspectorFingering(QWidget* parent)\n : InspectorElementBase(parent)\n {\n t.setupUi(addWidget());\n f.setupUi(addWidget());\n\n const std::vector iiList = {\n { P_ID::FONT_FACE, 0, 0, t.fontFace, t.resetFontFace },\n { P_ID::FONT_SIZE, 0, 0, t.fontSize, t.resetFontSize },\n { P_ID::FONT_BOLD, 0, 0, t.bold, t.resetBold },\n { P_ID::FONT_ITALIC, 0, 0, t.italic, t.resetItalic },\n { P_ID::FONT_UNDERLINE, 0, 0, t.underline, t.resetUnderline },\n { P_ID::FRAME, 0, 0, t.hasFrame, t.resetHasFrame },\n { P_ID::FRAME_FG_COLOR, 0, 0, t.frameColor, t.resetFrameColor },\n { P_ID::FRAME_BG_COLOR, 0, 0, t.bgColor, t.resetBgColor },\n { P_ID::FRAME_CIRCLE, 0, 0, t.circle, t.resetCircle },\n { P_ID::FRAME_SQUARE, 0, 0, t.square, t.resetSquare },\n { P_ID::FRAME_WIDTH, 0, 0, t.frameWidth, t.resetFrameWidth },\n { P_ID::FRAME_PADDING, 0, 0, t.paddingWidth, t.resetPaddingWidth },\n { P_ID::FRAME_ROUND, 0, 0, t.frameRound, t.resetFrameRound },\n { P_ID::ALIGN, 0, 0, t.align, t.resetAlign },\n { P_ID::SUB_STYLE, 0, 0, f.subStyle, f.resetSubStyle },\n };\n const std::vector ppList = {\n { t.title, t.panel },\n { f.title, f.panel }\n };\n\n f.subStyle->clear();\n for (auto ss : { SubStyle::FINGERING, SubStyle::LH_GUITAR_FINGERING, SubStyle::RH_GUITAR_FINGERING, SubStyle::STRING_NUMBER } )\n {\n f.subStyle->addItem(subStyleUserName(ss), int(ss));\n }\n\n mapSignals(iiList, ppList);\n }\n}\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":23,"cells":{"file_path":{"kind":"string","value":"mscore/inspector/alignSelect.cpp"},"num_changed_lines":{"kind":"number","value":115,"string":"115"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2017 Werner Schweer and others\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENSE.GPL\n//=============================================================================\n\n#include \"alignSelect.h\"\n#include \"libmscore/elementlayout.h\"\n#include \"icons.h\"\n\nnamespace Ms {\n\n//---------------------------------------------------------\n// AlignSelect\n//---------------------------------------------------------\n\nAlignSelect::AlignSelect(QWidget* parent)\n : QWidget(parent)\n {\n setupUi(this);\n\n g1 = new QButtonGroup(this);\n g1->addButton(alignLeft);\n g1->addButton(alignHCenter);\n g1->addButton(alignRight);\n\n g2 = new QButtonGroup(this);\n g2->addButton(alignTop);\n g2->addButton(alignVCenter);\n g2->addButton(alignBaseline);\n g2->addButton(alignBottom);\n\n alignLeft->setIcon(*icons[int(Icons::textLeft_ICON)]);\n alignRight->setIcon(*icons[int(Icons::textRight_ICON)]);\n alignHCenter->setIcon(*icons[int(Icons::textCenter_ICON)]);\n alignVCenter->setIcon(*icons[int(Icons::textVCenter_ICON)]);\n alignTop->setIcon(*icons[int(Icons::textTop_ICON)]);\n alignBaseline->setIcon(*icons[int(Icons::textBaseline_ICON)]);\n alignBottom->setIcon(*icons[int(Icons::textBaseline_ICON)]);\n\n connect(g1, SIGNAL(buttonToggled(int,bool)), SLOT(_alignChanged()));\n connect(g2, SIGNAL(buttonToggled(int,bool)), SLOT(_alignChanged()));\n }\n\n//---------------------------------------------------------\n// _alignChanged\n//---------------------------------------------------------\n\nvoid AlignSelect::_alignChanged()\n {\n emit alignChanged(align());\n }\n\n//---------------------------------------------------------\n// align\n//---------------------------------------------------------\n\nAlign AlignSelect::align() const\n {\n Align a = Align::LEFT;\n if (alignHCenter->isChecked())\n a = a | Align::HCENTER;\n else if (alignRight->isChecked())\n a = a | Align::RIGHT;\n if (alignVCenter->isChecked())\n a = a | Align::VCENTER;\n else if (alignBottom->isChecked())\n a = a | Align::BOTTOM;\n else if (alignBaseline->isChecked())\n a = a | Align::BASELINE;\n return a;\n }\n\n//---------------------------------------------------------\n// blockAlign\n//---------------------------------------------------------\n\nvoid AlignSelect::blockAlign(bool val)\n {\n g1->blockSignals(val);\n g2->blockSignals(val);\n }\n\n//---------------------------------------------------------\n// setElement\n//---------------------------------------------------------\n\nvoid AlignSelect::setAlign(Align a)\n {\n blockAlign(true);\n if (a & Align::HCENTER)\n alignHCenter->setChecked(true);\n else if (a & Align::RIGHT)\n alignRight->setChecked(true);\n else\n alignLeft->setChecked(true);\n if (a & Align::VCENTER)\n alignVCenter->setChecked(true);\n else if (a & Align::BOTTOM)\n alignBottom->setChecked(true);\n else if (a & Align::BASELINE)\n alignBaseline->setChecked(true);\n else\n alignTop->setChecked(true);\n blockAlign(false);\n }\n\n}\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":24,"cells":{"file_path":{"kind":"string","value":"mtest/libmscore/element/tst_element.cpp"},"num_changed_lines":{"kind":"number","value":59,"string":"59"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n// $Id:$\n//\n// Copyright (C) 2012 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENCE.GPL\n//=============================================================================\n\n#include \n\n#include \"libmscore/score.h\"\n#include \"libmscore/element.h\"\n#include \"mtest/testutils.h\"\n\nusing namespace Ms;\n\n//---------------------------------------------------------\n// TestElement\n//---------------------------------------------------------\n\nclass TestElement : public QObject, public MTest\n {\n Q_OBJECT\n\n private slots:\n void initTestCase() { initMTest(); }\n void testIds();\n };\n\n//---------------------------------------------------------\n// testIds\n//---------------------------------------------------------\n\nvoid TestElement::testIds()\n {\n ElementType ids[] = {\n ElementType::VOLTA,\n ElementType::OTTAVA,\n ElementType::TEXTLINE,\n ElementType::TRILL,\n ElementType::PEDAL,\n ElementType::HAIRPIN,\n ElementType::CLEF,\n ElementType::KEYSIG,\n ElementType::TIMESIG,\n ElementType::BAR_LINE,\n ElementType::ARPEGGIO,\n ElementType::BREATH,\n ElementType::GLISSANDO,\n ElementType::BRACKET,\n ElementType::ARTICULATION,\n ElementType::CHORDLINE,\n ElementType::ACCIDENTAL,\n ElementType::DYNAMIC,\n ElementType::TEXT,\n ElementType::INSTRUMENT_NAME,\n ElementType::STAFF_TEXT,\n ElementType::REHEARSAL_MARK,\n ElementType::INSTRUMENT_CHANGE,\n ElementType::NOTEHEAD,\n ElementType::NOTEDOT,\n ElementType::TREMOLO,\n ElementType::LAYOUT_BREAK,\n ElementType::MARKER,\n ElementType::JUMP,\n ElementType::REPEAT_MEASURE,\n ElementType::ICON,\n ElementType::NOTE,\n ElementType::SYMBOL,\n ElementType::FSYMBOL,\n ElementType::CHORD,\n ElementType::REST,\n ElementType::SPACER,\n ElementType::STAFF_STATE,\n ElementType::TEMPO_TEXT,\n ElementType::HARMONY,\n ElementType::FRET_DIAGRAM,\n ElementType::BEND,\n ElementType::TREMOLOBAR,\n ElementType::LYRICS,\n ElementType::FIGURED_BASS,\n ElementType::STEM,\n ElementType::SLUR,\n ElementType::FINGERING,\n ElementType::HBOX,\n ElementType::VBOX,\n ElementType::TBOX,\n ElementType::FBOX,\n ElementType::MEASURE,\n ElementType::TAB_DURATION_SYMBOL,\n ElementType::OSSIA,\n ElementType::INVALID\n };\n\n for (int i = 0; ids[i] != ElementType::INVALID; ++i) {\n ElementType t = ids[i];\n Element* e = Element::create(t, score);\n Element* ee = writeReadElement(e);\n QCOMPARE(e->type(), ee->type());\n delete e;\n delete ee;\n }\n }\n\nQTEST_MAIN(TestElement)\n\n#include \"tst_element.moc\"\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":25,"cells":{"file_path":{"kind":"string","value":"mscore/inspector/inspectorText.cpp"},"num_changed_lines":{"kind":"number","value":33,"string":"33"},"code":{"kind":"string","value":"//=============================================================================\n// MuseScore\n// Music Composition & Notation\n//\n// Copyright (C) 2011 Werner Schweer\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License version 2\n// as published by the Free Software Foundation and appearing in\n// the file LICENSE.GPL\n//=============================================================================\n\n#include \"inspectorText.h\"\n#include \"libmscore/score.h\"\n#include \"icons.h\"\n\nnamespace Ms {\n\n//---------------------------------------------------------\n// InspectorText\n//---------------------------------------------------------\n\nInspectorText::InspectorText(QWidget* parent)\n : InspectorElementBase(parent)\n {\n t.setupUi(addWidget());\n f.setupUi(addWidget());\n\n const std::vector iiList = {\n { P_ID::FONT_FACE, 0, 0, t.fontFace, t.resetFontFace },\n { P_ID::FONT_SIZE, 0, 0, t.fontSize, t.resetFontSize },\n { P_ID::FONT_BOLD, 0, 0, t.bold, t.resetBold },\n { P_ID::FONT_ITALIC, 0, 0, t.italic, t.resetItalic },\n { P_ID::FONT_UNDERLINE, 0, 0, t.underline, t.resetUnderline },\n { P_ID::FRAME, 0, 0, t.hasFrame, t.resetHasFrame },\n { P_ID::FRAME_FG_COLOR, 0, 0, t.frameColor, t.resetFrameColor },\n { P_ID::FRAME_BG_COLOR, 0, 0, t.bgColor, t.resetBgColor },\n { P_ID::FRAME_CIRCLE, 0, 0, t.circle, t.resetCircle },\n { P_ID::FRAME_SQUARE, 0, 0, t.square, t.resetSquare },\n { P_ID::FRAME_WIDTH, 0, 0, t.frameWidth, t.resetFrameWidth },\n { P_ID::FRAME_PADDING, 0, 0, t.paddingWidth, t.resetPaddingWidth },\n { P_ID::FRAME_ROUND, 0, 0, t.frameRound, t.resetFrameRound },\n { P_ID::ALIGN, 0, 0, t.align, t.resetAlign },\n { P_ID::SUB_STYLE, 0, 0, f.subStyle, f.resetSubStyle },\n };\n\n const std::vector ppList = {\n { t.title, t.panel },\n { f.title, f.panel }\n };\n\n f.subStyle->clear();\n for (auto ss : { SubStyle::FRAME, SubStyle::TITLE, SubStyle::SUBTITLE,SubStyle::COMPOSER, SubStyle::POET, SubStyle::INSTRUMENT_EXCERPT,\n SubStyle::TRANSLATOR, SubStyle::HEADER, SubStyle::FOOTER, SubStyle::USER1, SubStyle::USER2 } )\n {\n f.subStyle->addItem(subStyleUserName(ss), int(ss));\n }\n\n connect(t.resetToStyle, SIGNAL(clicked()), SLOT(resetToStyle()));\n mapSignals(iiList, ppList);\n }\n\n}\n\n"},"repo_name":{"kind":"string","value":"musescore_MuseScore"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"ac9de15554925578bc13dd4b3894e6fb880e6f1e"}}},{"rowIdx":26,"cells":{"file_path":{"kind":"string","value":"samples/cpp/tutorial_code/core/how_to_use_OpenCV_parallel_for_/how_to_use_OpenCV_parallel_for_.cpp"},"num_changed_lines":{"kind":"number","value":122,"string":"122"},"code":{"kind":"string","value":"#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\n\nnamespace\n{\n//! [mandelbrot-escape-time-algorithm]\nint mandelbrot(const complex &z0, const int max)\n{\n complex z = z0;\n for (int t = 0; t < max; t++)\n {\n if (z.real()*z.real() + z.imag()*z.imag() > 4.0f) return t;\n z = z*z + z0;\n }\n\n return max;\n}\n//! [mandelbrot-escape-time-algorithm]\n\n//! [mandelbrot-grayscale-value]\nint mandelbrotFormula(const complex &z0, const int maxIter=500) {\n int value = mandelbrot(z0, maxIter);\n if(maxIter - value == 0)\n {\n return 0;\n }\n\n return cvRound(sqrt(value / (float) maxIter) * 255);\n}\n//! [mandelbrot-grayscale-value]\n\n//! [mandelbrot-parallel]\nclass ParallelMandelbrot : public ParallelLoopBody\n{\npublic:\n ParallelMandelbrot (Mat &img, const float x1, const float y1, const float scaleX, const float scaleY)\n : m_img(img), m_x1(x1), m_y1(y1), m_scaleX(scaleX), m_scaleY(scaleY)\n {\n }\n\n virtual void operator ()(const Range& range) const\n {\n for (int r = range.start; r < range.end; r++)\n {\n int i = r / m_img.cols;\n int j = r % m_img.cols;\n\n float x0 = j / m_scaleX + m_x1;\n float y0 = i / m_scaleY + m_y1;\n\n complex z0(x0, y0);\n uchar value = (uchar) mandelbrotFormula(z0);\n m_img.ptr(i)[j] = value;\n }\n }\n\n ParallelMandelbrot& operator=(const ParallelMandelbrot &) {\n return *this;\n };\n\nprivate:\n Mat &m_img;\n float m_x1;\n float m_y1;\n float m_scaleX;\n float m_scaleY;\n};\n//! [mandelbrot-parallel]\n\n//! [mandelbrot-sequential]\nvoid sequentialMandelbrot(Mat &img, const float x1, const float y1, const float scaleX, const float scaleY)\n{\n for (int i = 0; i < img.rows; i++)\n {\n for (int j = 0; j < img.cols; j++)\n {\n float x0 = j / scaleX + x1;\n float y0 = i / scaleY + y1;\n\n complex z0(x0, y0);\n uchar value = (uchar) mandelbrotFormula(z0);\n img.ptr(i)[j] = value;\n }\n }\n}\n//! [mandelbrot-sequential]\n}\n\nint main()\n{\n //! [mandelbrot-transformation]\n Mat mandelbrotImg(4800, 5400, CV_8U);\n float x1 = -2.1f, x2 = 0.6f;\n float y1 = -1.2f, y2 = 1.2f;\n float scaleX = mandelbrotImg.cols / (x2 - x1);\n float scaleY = mandelbrotImg.rows / (y2 - y1);\n //! [mandelbrot-transformation]\n\n double t1 = (double) getTickCount();\n //! [mandelbrot-parallel-call]\n ParallelMandelbrot parallelMandelbrot(mandelbrotImg, x1, y1, scaleX, scaleY);\n parallel_for_(Range(0, mandelbrotImg.rows*mandelbrotImg.cols), parallelMandelbrot);\n //! [mandelbrot-parallel-call]\n t1 = ((double) getTickCount() - t1) / getTickFrequency();\n cout << \"Parallel Mandelbrot: \" << t1 << \" s\" << endl;\n\n Mat mandelbrotImgSequential(4800, 5400, CV_8U);\n double t2 = (double) getTickCount();\n sequentialMandelbrot(mandelbrotImgSequential, x1, y1, scaleX, scaleY);\n t2 = ((double) getTickCount() - t2) / getTickFrequency();\n cout << \"Sequential Mandelbrot: \" << t2 << \" s\" << endl;\n cout << \"Speed-up: \" << t2/t1 << \" X\" << endl;\n\n imwrite(\"Mandelbrot_parallel.png\", mandelbrotImg);\n imwrite(\"Mandelbrot_sequential.png\", mandelbrotImgSequential);\n\n return EXIT_SUCCESS;\n}\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":27,"cells":{"file_path":{"kind":"string","value":"samples/cpp/tutorial_code/ImgProc/changing_contrast_brightness_image/changing_contrast_brightness_image.cpp"},"num_changed_lines":{"kind":"number","value":91,"string":"91"},"code":{"kind":"string","value":"#include \n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/highgui.hpp\"\n\nusing namespace std;\nusing namespace cv;\n\nnamespace\n{\n/** Global Variables */\nint alpha = 100;\nint beta = 100;\nint gamma_cor = 100;\nMat img_original, img_corrected, img_gamma_corrected;\n\nvoid basicLinearTransform(const Mat &img, const double alpha_, const int beta_)\n{\n Mat res;\n img.convertTo(res, -1, alpha_, beta_);\n\n hconcat(img, res, img_corrected);\n}\n\nvoid gammaCorrection(const Mat &img, const double gamma_)\n{\n CV_Assert(gamma_ >= 0);\n //![changing-contrast-brightness-gamma-correction]\n Mat lookUpTable(1, 256, CV_8U);\n uchar* p = lookUpTable.ptr();\n for( int i = 0; i < 256; ++i)\n p[i] = saturate_cast(pow(i / 255.0, gamma_) * 255.0);\n\n Mat res = img.clone();\n LUT(img, lookUpTable, res);\n //![changing-contrast-brightness-gamma-correction]\n\n hconcat(img, res, img_gamma_corrected);\n}\n\nvoid on_linear_transform_alpha_trackbar(int, void *)\n{\n double alpha_value = alpha / 100.0;\n int beta_value = beta - 100;\n basicLinearTransform(img_original, alpha_value, beta_value);\n}\n\nvoid on_linear_transform_beta_trackbar(int, void *)\n{\n double alpha_value = alpha / 100.0;\n int beta_value = beta - 100;\n basicLinearTransform(img_original, alpha_value, beta_value);\n}\n\nvoid on_gamma_correction_trackbar(int, void *)\n{\n double gamma_value = gamma_cor / 100.0;\n gammaCorrection(img_original, gamma_value);\n}\n}\n\nint main( int, char** argv )\n{\n img_original = imread( argv[1] );\n img_corrected = Mat(img_original.rows, img_original.cols*2, img_original.type());\n img_gamma_corrected = Mat(img_original.rows, img_original.cols*2, img_original.type());\n\n hconcat(img_original, img_original, img_corrected);\n hconcat(img_original, img_original, img_gamma_corrected);\n\n namedWindow(\"Brightness and contrast adjustments\", WINDOW_AUTOSIZE);\n namedWindow(\"Gamma correction\", WINDOW_AUTOSIZE);\n\n createTrackbar(\"Alpha gain (contrast)\", \"Brightness and contrast adjustments\", &alpha, 500, on_linear_transform_alpha_trackbar);\n createTrackbar(\"Beta bias (brightness)\", \"Brightness and contrast adjustments\", &beta, 200, on_linear_transform_beta_trackbar);\n createTrackbar(\"Gamma correction\", \"Gamma correction\", &gamma_cor, 200, on_gamma_correction_trackbar);\n\n while (true)\n {\n imshow(\"Brightness and contrast adjustments\", img_corrected);\n imshow(\"Gamma correction\", img_gamma_corrected);\n\n int c = waitKey(30);\n if (c == 27)\n break;\n }\n\n imwrite(\"linear_transform_correction.png\", img_corrected);\n imwrite(\"gamma_correction.png\", img_gamma_corrected);\n\n return 0;\n}\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":28,"cells":{"file_path":{"kind":"string","value":"platforms/ios/build_framework.py"},"num_changed_lines":{"kind":"number","value":118,"string":"118"},"code":{"kind":"string","value":"#!/usr/bin/env python\n\"\"\"\nThe script builds OpenCV.framework for iOS.\nThe built framework is universal, it can be used to build app and run it on either iOS simulator or real device.\n\nUsage:\n ./build_framework.py \n\nBy cmake conventions (and especially if you work with OpenCV repository),\nthe output dir should not be a subdirectory of OpenCV source tree.\n\nScript will create , if it's missing, and a few its subdirectories:\n\n \n build/\n iPhoneOS-*/\n [cmake-generated build tree for an iOS device target]\n iPhoneSimulator-*/\n [cmake-generated build tree for iOS simulator]\n opencv2.framework/\n [the framework content]\n\nThe script should handle minor OpenCV updates efficiently\n- it does not recompile the library from scratch each time.\nHowever, opencv2.framework directory is erased and recreated on each run.\n\nAdding --dynamic parameter will build opencv2.framework as App Store dynamic framework. Only iOS 8+ versions are supported.\n\"\"\"\n\nfrom __future__ import print_function\nimport glob, re, os, os.path, shutil, string, sys, argparse, traceback\nfrom subprocess import check_call, check_output, CalledProcessError\n\ndef execute(cmd, cwd = None):\n print(\"Executing: %s in %s\" % (cmd, cwd), file=sys.stderr)\n retcode = check_call(cmd, cwd = cwd)\n if retcode != 0:\n raise Exception(\"Child returned:\", retcode)\n\ndef getXCodeMajor():\n ret = check_output([\"xcodebuild\", \"-version\"])\n m = re.match(r'XCode\\s+(\\d)\\..*', ret, flags=re.IGNORECASE)\n if m:\n return int(m.group(1))\n return 0\n\nclass Builder:\n def __init__(self, opencv, contrib, dynamic, bitcodedisabled, exclude, targets):\n self.opencv = os.path.abspath(opencv)\n self.contrib = None\n if contrib:\n modpath = os.path.join(contrib, \"modules\")\n if os.path.isdir(modpath):\n self.contrib = os.path.abspath(modpath)\n else:\n print(\"Note: contrib repository is bad - modules subfolder not found\", file=sys.stderr)\n self.dynamic = dynamic\n self.bitcodedisabled = bitcodedisabled\n self.exclude = exclude\n self.targets = targets\n\n def getBD(self, parent, t):\n\n if len(t[0]) == 1:\n res = os.path.join(parent, 'build-%s-%s' % (t[0][0].lower(), t[1].lower()))\n else:\n res = os.path.join(parent, 'build-%s' % t[1].lower())\n\n if not os.path.isdir(res):\n os.makedirs(res)\n return os.path.abspath(res)\n\n def _build(self, outdir):\n outdir = os.path.abspath(outdir)\n if not os.path.isdir(outdir):\n os.makedirs(outdir)\n mainWD = os.path.join(outdir, \"build\")\n dirs = []\n\n xcode_ver = getXCodeMajor()\n\n if self.dynamic:\n alltargets = self.targets\n else:\n # if we are building a static library, we must build each architecture separately\n alltargets = []\n\n for t in self.targets:\n for at in t[0]:\n current = ( [at], t[1] )\n\n alltargets.append(current)\n\n for t in alltargets:\n mainBD = self.getBD(mainWD, t)\n dirs.append(mainBD)\n\n cmake_flags = []\n if self.contrib:\n cmake_flags.append(\"-DOPENCV_EXTRA_MODULES_PATH=%s\" % self.contrib)\n if xcode_ver >= 7 and t[1] == 'iPhoneOS' and self.bitcodedisabled == False:\n cmake_flags.append(\"-DCMAKE_C_FLAGS=-fembed-bitcode\")\n cmake_flags.append(\"-DCMAKE_CXX_FLAGS=-fembed-bitcode\")\n self.buildOne(t[0], t[1], mainBD, cmake_flags)\n\n if self.dynamic == False:\n self.mergeLibs(mainBD)\n self.makeFramework(outdir, dirs)\n\n def build(self, outdir):\n try:\n self._build(outdir)\n except Exception as e:\n print(\"=\"*60, file=sys.stderr)\n print(\"ERROR: %s\" % e, file=sys.stderr)\n print(\"=\"*60, file=sys.stderr)\n traceback.print_exc(file=sys.stderr)\n sys.exit(1)\n\n def getToolchain(self, arch, target):\n return None\n\n def getCMakeArgs(self, arch, target):\n\n if self.dynamic:\n args = [\n \"cmake\",\n \"-GXcode\",\n \"-DAPPLE_FRAMEWORK=ON\",\n \"-DCMAKE_INSTALL_PREFIX=install\",\n \"-DCMAKE_BUILD_TYPE=Release\",\n \"-DBUILD_SHARED_LIBS=ON\",\n \"-DCMAKE_MACOSX_BUNDLE=ON\",\n \"-DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=NO\",\n ]\n else:\n args = [\n \"cmake\",\n \"-GXcode\",\n \"-DAPPLE_FRAMEWORK=ON\",\n \"-DCMAKE_INSTALL_PREFIX=install\",\n \"-DCMAKE_BUILD_TYPE=Release\",\n ]\n\n if len(self.exclude) > 0:\n args += [\"-DBUILD_opencv_world=OFF\"]\n args += (\"-DBUILD_opencv_%s=OFF\" % m for m in self.exclude)\n\n return args\n\n def getBuildCommand(self, archs, target):\n\n if self.dynamic:\n buildcmd = [\n \"xcodebuild\",\n \"IPHONEOS_DEPLOYMENT_TARGET=8.0\",\n \"ONLY_ACTIVE_ARCH=NO\",\n ]\n\n for arch in archs:\n buildcmd.append(\"-arch\")\n buildcmd.append(arch.lower())\n\n buildcmd += [\n \"-sdk\", target.lower(),\n \"-configuration\", \"Release\",\n \"-parallelizeTargets\",\n \"-jobs\", \"4\",\n \"-target\",\"ALL_BUILD\",\n ]\n else:\n arch = \";\".join(archs)\n buildcmd = [\n \"xcodebuild\",\n \"IPHONEOS_DEPLOYMENT_TARGET=6.0\",\n \"ARCHS=%s\" % arch,\n \"-sdk\", target.lower(),\n \"-configuration\", \"Release\",\n \"-parallelizeTargets\",\n \"-jobs\", \"4\"\n ]\n\n return buildcmd\n\n def getInfoPlist(self, builddirs):\n return os.path.join(builddirs[0], \"ios\", \"Info.plist\")\n\n def buildOne(self, arch, target, builddir, cmakeargs = []):\n # Run cmake\n toolchain = self.getToolchain(arch, target)\n cmakecmd = self.getCMakeArgs(arch, target) + \\\n ([\"-DCMAKE_TOOLCHAIN_FILE=%s\" % toolchain] if toolchain is not None else [])\n if target.lower().startswith(\"iphoneos\"):\n cmakecmd.append(\"-DENABLE_NEON=ON\")\n cmakecmd.append(self.opencv)\n cmakecmd.extend(cmakeargs)\n execute(cmakecmd, cwd = builddir)\n\n # Clean and build\n clean_dir = os.path.join(builddir, \"install\")\n if os.path.isdir(clean_dir):\n shutil.rmtree(clean_dir)\n buildcmd = self.getBuildCommand(arch, target)\n execute(buildcmd + [\"-target\", \"ALL_BUILD\", \"build\"], cwd = builddir)\n execute([\"cmake\", \"-P\", \"cmake_install.cmake\"], cwd = builddir)\n\n def mergeLibs(self, builddir):\n res = os.path.join(builddir, \"lib\", \"Release\", \"libopencv_merged.a\")\n libs = glob.glob(os.path.join(builddir, \"install\", \"lib\", \"*.a\"))\n libs3 = glob.glob(os.path.join(builddir, \"install\", \"share\", \"OpenCV\", \"3rdparty\", \"lib\", \"*.a\"))\n print(\"Merging libraries:\\n\\t%s\" % \"\\n\\t\".join(libs + libs3), file=sys.stderr)\n execute([\"libtool\", \"-static\", \"-o\", res] + libs + libs3)\n\n def makeFramework(self, outdir, builddirs):\n name = \"opencv2\"\n\n # set the current dir to the dst root\n framework_dir = os.path.join(outdir, \"%s.framework\" % name)\n if os.path.isdir(framework_dir):\n shutil.rmtree(framework_dir)\n os.makedirs(framework_dir)\n\n if self.dynamic:\n dstdir = framework_dir\n libname = \"opencv2.framework/opencv2\"\n else:\n dstdir = os.path.join(framework_dir, \"Versions\", \"A\")\n libname = \"libopencv_merged.a\"\n\n # copy headers from one of build folders\n shutil.copytree(os.path.join(builddirs[0], \"install\", \"include\", \"opencv2\"), os.path.join(dstdir, \"Headers\"))\n\n # make universal static lib\n libs = [os.path.join(d, \"lib\", \"Release\", libname) for d in builddirs]\n lipocmd = [\"lipo\", \"-create\"]\n lipocmd.extend(libs)\n lipocmd.extend([\"-o\", os.path.join(dstdir, name)])\n print(\"Creating universal library from:\\n\\t%s\" % \"\\n\\t\".join(libs), file=sys.stderr)\n execute(lipocmd)\n\n # dynamic framework has different structure, just copy the Plist directly\n if self.dynamic:\n resdir = dstdir\n shutil.copyfile(self.getInfoPlist(builddirs), os.path.join(resdir, \"Info.plist\"))\n else:\n # copy Info.plist\n resdir = os.path.join(dstdir, \"Resources\")\n os.makedirs(resdir)\n shutil.copyfile(self.getInfoPlist(builddirs), os.path.join(resdir, \"Info.plist\"))\n\n # make symbolic links\n links = [\n ([\"A\"], [\"Versions\", \"Current\"]),\n ([\"Versions\", \"Current\", \"Headers\"], [\"Headers\"]),\n ([\"Versions\", \"Current\", \"Resources\"], [\"Resources\"]),\n ([\"Versions\", \"Current\", name], [name])\n ]\n for l in links:\n s = os.path.join(*l[0])\n d = os.path.join(framework_dir, *l[1])\n os.symlink(s, d)\n\nclass iOSBuilder(Builder):\n\n def getToolchain(self, arch, target):\n toolchain = os.path.join(self.opencv, \"platforms\", \"ios\", \"cmake\", \"Toolchains\", \"Toolchain-%s_Xcode.cmake\" % target)\n return toolchain\n\n def getCMakeArgs(self, arch, target):\n arch = \";\".join(arch)\n\n args = Builder.getCMakeArgs(self, arch, target)\n args = args + [\n '-DIOS_ARCH=%s' % arch\n ]\n return args\n\n\nif __name__ == \"__main__\":\n folder = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), \"../..\"))\n parser = argparse.ArgumentParser(description='The script builds OpenCV.framework for iOS.')\n parser.add_argument('out', metavar='OUTDIR', help='folder to put built framework')\n parser.add_argument('--opencv', metavar='DIR', default=folder, help='folder with opencv repository (default is \"../..\" relative to script location)')\n parser.add_argument('--contrib', metavar='DIR', default=None, help='folder with opencv_contrib repository (default is \"None\" - build only main framework)')\n parser.add_argument('--without', metavar='MODULE', default=[], action='append', help='OpenCV modules to exclude from the framework')\n parser.add_argument('--dynamic', default=False, action='store_true', help='build dynamic framework (default is \"False\" - builds static framework)')\n parser.add_argument('--disable-bitcode', default=False, dest='bitcodedisabled', action='store_true', help='disable bitcode (enabled by default)')\n args = parser.parse_args()\n\n b = iOSBuilder(args.opencv, args.contrib, args.dynamic, args.bitcodedisabled, args.without,\n [\n ([\"armv7\", \"arm64\"], \"iPhoneOS\"),\n ] if os.environ.get('BUILD_PRECOMMIT', None) else\n [\n ([\"armv7\", \"armv7s\", \"arm64\"], \"iPhoneOS\"),\n ([\"i386\", \"x86_64\"], \"iPhoneSimulator\"),\n ])\n b.build(args.out)\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":29,"cells":{"file_path":{"kind":"string","value":"modules/core/misc/java/src/java/core+Rect2d.java"},"num_changed_lines":{"kind":"number","value":100,"string":"100"},"code":{"kind":"string","value":"package org.opencv.core;\n\n//javadoc:Rect2d_\npublic class Rect2d {\n\n public double x, y, width, height;\n\n public Rect2d(double x, double y, double width, double height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n\n public Rect2d() {\n this(0, 0, 0, 0);\n }\n\n public Rect2d(Point p1, Point p2) {\n x = (double) (p1.x < p2.x ? p1.x : p2.x);\n y = (double) (p1.y < p2.y ? p1.y : p2.y);\n width = (double) (p1.x > p2.x ? p1.x : p2.x) - x;\n height = (double) (p1.y > p2.y ? p1.y : p2.y) - y;\n }\n\n public Rect2d(Point p, Size s) {\n this((double) p.x, (double) p.y, (double) s.width, (double) s.height);\n }\n\n public Rect2d(double[] vals) {\n set(vals);\n }\n\n public void set(double[] vals) {\n if (vals != null) {\n x = vals.length > 0 ? (double) vals[0] : 0;\n y = vals.length > 1 ? (double) vals[1] : 0;\n width = vals.length > 2 ? (double) vals[2] : 0;\n height = vals.length > 3 ? (double) vals[3] : 0;\n } else {\n x = 0;\n y = 0;\n width = 0;\n height = 0;\n }\n }\n\n public Rect2d clone() {\n return new Rect2d(x, y, width, height);\n }\n\n public Point tl() {\n return new Point(x, y);\n }\n\n public Point br() {\n return new Point(x + width, y + height);\n }\n\n public Size size() {\n return new Size(width, height);\n }\n\n public double area() {\n return width * height;\n }\n\n public boolean contains(Point p) {\n return x <= p.x && p.x < x + width && y <= p.y && p.y < y + height;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n long temp;\n temp = Double.doubleToLongBits(height);\n result = prime * result + (int) (temp ^ (temp >>> 32));\n temp = Double.doubleToLongBits(width);\n result = prime * result + (int) (temp ^ (temp >>> 32));\n temp = Double.doubleToLongBits(x);\n result = prime * result + (int) (temp ^ (temp >>> 32));\n temp = Double.doubleToLongBits(y);\n result = prime * result + (int) (temp ^ (temp >>> 32));\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (!(obj instanceof Rect2d)) return false;\n Rect2d it = (Rect2d) obj;\n return x == it.x && y == it.y && width == it.width && height == it.height;\n }\n\n @Override\n public String toString() {\n return \"{\" + x + \", \" + y + \", \" + width + \"x\" + height + \"}\";\n }\n}\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":30,"cells":{"file_path":{"kind":"string","value":"samples/cpp/tutorial_code/ImgProc/BasicLinearTransforms.cpp"},"num_changed_lines":{"kind":"number","value":42,"string":"42"},"code":{"kind":"string","value":"/**\n * @file BasicLinearTransforms.cpp\n * @brief Simple program to change contrast and brightness\n * @author OpenCV team\n */\n\n#include \"opencv2/imgcodecs.hpp\"\n#include \"opencv2/highgui.hpp\"\n#include \n\nusing namespace std;\nusing namespace cv;\n\n/**\n * @function main\n * @brief Main function\n */\nint main( int, char** argv )\n{\n //! [basic-linear-transform-parameters]\n double alpha = 1.0; /*< Simple contrast control */\n int beta = 0; /*< Simple brightness control */\n //! [basic-linear-transform-parameters]\n\n /// Read image given by user\n //! [basic-linear-transform-load]\n Mat image = imread( argv[1] );\n //! [basic-linear-transform-load]\n //! [basic-linear-transform-output]\n Mat new_image = Mat::zeros( image.size(), image.type() );\n //! [basic-linear-transform-output]\n\n /// Initialize values\n cout << \" Basic Linear Transforms \" << endl;\n cout << \"-------------------------\" << endl;\n cout << \"* Enter the alpha value [1.0-3.0]: \"; cin >> alpha;\n cout << \"* Enter the beta value [0-100]: \"; cin >> beta;\n\n /// Do the operation new_image(i,j) = alpha*image(i,j) + beta\n /// Instead of these 'for' loops we could have used simply:\n /// image.convertTo(new_image, -1, alpha, beta);\n /// but we wanted to show you how to access the pixels :)\n //! [basic-linear-transform-operation]\n for( int y = 0; y < image.rows; y++ ) {\n for( int x = 0; x < image.cols; x++ ) {\n for( int c = 0; c < 3; c++ ) {\n new_image.at(y,x)[c] =\n saturate_cast( alpha*( image.at(y,x)[c] ) + beta );\n }\n }\n }\n //! [basic-linear-transform-operation]\n\n //! [basic-linear-transform-display]\n /// Create Windows\n namedWindow(\"Original Image\", WINDOW_AUTOSIZE);\n namedWindow(\"New Image\", WINDOW_AUTOSIZE);\n\n /// Show stuff\n imshow(\"Original Image\", image);\n imshow(\"New Image\", new_image);\n\n /// Wait until user press some key\n waitKey();\n //! [basic-linear-transform-display]\n return 0;\n}\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":31,"cells":{"file_path":{"kind":"string","value":"samples/cpp/tutorial_code/ImgProc/HitMiss.cpp"},"num_changed_lines":{"kind":"number","value":37,"string":"37"},"code":{"kind":"string","value":"#include \n#include \n#include \n\nusing namespace cv;\n\nint main(){\n Mat input_image = (Mat_(8, 8) <<\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 255, 255, 255, 0, 0, 0, 255,\n 0, 255, 255, 255, 0, 0, 0, 0,\n 0, 255, 255, 255, 0, 255, 0, 0,\n 0, 0, 255, 0, 0, 0, 0, 0,\n 0, 0, 255, 0, 0, 255, 255, 0,\n 0, 255, 0, 255, 0, 0, 255, 0,\n 0, 255, 255, 255, 0, 0, 0, 0);\n\n Mat kernel = (Mat_(3, 3) <<\n 0, 1, 0,\n 1, -1, 1,\n 0, 1, 0);\n\n Mat output_image;\n morphologyEx(input_image, output_image, MORPH_HITMISS, kernel);\n\n const int rate = 10;\n kernel = (kernel + 1) * 127;\n kernel.convertTo(kernel, CV_8U);\n cv::resize(kernel, kernel, cv::Size(), rate, rate, INTER_NEAREST);\n imshow(\"kernel\", kernel);\n cv::resize(input_image, input_image, cv::Size(), rate, rate, INTER_NEAREST);\n imshow(\"Original\", input_image);\n cv::resize(output_image, output_image, cv::Size(), rate, rate, INTER_NEAREST);\n imshow(\"Hit or Miss\", output_image);\n waitKey(0);\n return 0;\n}\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":32,"cells":{"file_path":{"kind":"string","value":"modules/core/misc/java/src/java/core+MatOfRect2d.java"},"num_changed_lines":{"kind":"number","value":81,"string":"81"},"code":{"kind":"string","value":"package org.opencv.core;\n\nimport java.util.Arrays;\nimport java.util.List;\n\n\npublic class MatOfRect2d extends Mat {\n // 64FC4\n private static final int _depth = CvType.CV_64F;\n private static final int _channels = 4;\n\n public MatOfRect2d() {\n super();\n }\n\n protected MatOfRect2d(long addr) {\n super(addr);\n if( !empty() && checkVector(_channels, _depth) < 0 )\n throw new IllegalArgumentException(\"Incompatible Mat\");\n //FIXME: do we need release() here?\n }\n\n public static MatOfRect2d fromNativeAddr(long addr) {\n return new MatOfRect2d(addr);\n }\n\n public MatOfRect2d(Mat m) {\n super(m, Range.all());\n if( !empty() && checkVector(_channels, _depth) < 0 )\n throw new IllegalArgumentException(\"Incompatible Mat\");\n //FIXME: do we need release() here?\n }\n\n public MatOfRect2d(Rect2d...a) {\n super();\n fromArray(a);\n }\n\n public void alloc(int elemNumber) {\n if(elemNumber>0)\n super.create(elemNumber, 1, CvType.makeType(_depth, _channels));\n }\n\n public void fromArray(Rect2d...a) {\n if(a==null || a.length==0)\n return;\n int num = a.length;\n alloc(num);\n double buff[] = new double[num * _channels];\n for(int i=0; i lr) {\n Rect2d ap[] = lr.toArray(new Rect2d[0]);\n fromArray(ap);\n }\n\n public List toList() {\n Rect2d[] ar = toArray();\n return Arrays.asList(ar);\n }\n}\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":33,"cells":{"file_path":{"kind":"string","value":"modules/python/test/test_shape.py"},"num_changed_lines":{"kind":"number","value":23,"string":"23"},"code":{"kind":"string","value":"#!/usr/bin/env python\nimport cv2\n\nfrom tests_common import NewOpenCVTests\n\nclass shape_test(NewOpenCVTests):\n\n def test_computeDistance(self):\n\n a = self.get_sample('samples/data/shape_sample/1.png', cv2.IMREAD_GRAYSCALE);\n b = self.get_sample('samples/data/shape_sample/2.png', cv2.IMREAD_GRAYSCALE);\n\n _, ca, _ = cv2.findContours(a, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS)\n _, cb, _ = cv2.findContours(b, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS)\n\n hd = cv2.createHausdorffDistanceExtractor()\n sd = cv2.createShapeContextDistanceExtractor()\n\n d1 = hd.computeDistance(ca[0], cb[0])\n d2 = sd.computeDistance(ca[0], cb[0])\n\n self.assertAlmostEqual(d1, 26.4196891785, 3, \"HausdorffDistanceExtractor\")\n self.assertAlmostEqual(d2, 0.25804194808, 3, \"ShapeContextDistanceExtractor\")\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":34,"cells":{"file_path":{"kind":"string","value":"samples/python/tutorial_code/imgProc/hough_line_transform/probabilistic_hough_line_transform.py"},"num_changed_lines":{"kind":"number","value":12,"string":"12"},"code":{"kind":"string","value":"import cv2\nimport numpy as np\n\nimg = cv2.imread('../data/sudoku.png')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray,50,150,apertureSize = 3)\nlines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength=100,maxLineGap=10)\nfor line in lines:\n x1,y1,x2,y2 = line[0]\n cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n\ncv2.imwrite('houghlines5.jpg',img)\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":35,"cells":{"file_path":{"kind":"string","value":"cmake/checks/lapack_check.cpp"},"num_changed_lines":{"kind":"number","value":14,"string":"14"},"code":{"kind":"string","value":"#include \"opencv_lapack.h\"\n\nstatic char* check_fn1 = (char*)sgesv_;\nstatic char* check_fn2 = (char*)sposv_;\nstatic char* check_fn3 = (char*)spotrf_;\nstatic char* check_fn4 = (char*)sgesdd_;\n\nint main(int argc, char* argv[])\n{\n (void)argv;\n if(argc > 1000)\n return check_fn1[0] + check_fn2[0] + check_fn3[0] + check_fn4[0];\n return 0;\n}\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":36,"cells":{"file_path":{"kind":"string","value":"samples/python/tutorial_code/imgProc/hough_line_transform/hough_line_transform.py"},"num_changed_lines":{"kind":"number","value":22,"string":"22"},"code":{"kind":"string","value":"import cv2\nimport numpy as np\n\nimg = cv2.imread('../data/sudoku.png')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray,50,150,apertureSize = 3)\n\nlines = cv2.HoughLines(edges,1,np.pi/180,200)\nfor line in lines:\n rho,theta = line[0]\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\n\ncv2.imwrite('houghlines3.jpg',img)\n"},"repo_name":{"kind":"string","value":"opencv_opencv"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"a8aff6f64330a0ab2c9d71033412af892dd9b710"}}},{"rowIdx":37,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/test_blocktrans.py"},"num_changed_lines":{"kind":"number","value":433,"string":"433"},"code":{"kind":"string","value":"import os\nfrom threading import local\n\nfrom django.template import Context, Template, TemplateSyntaxError\nfrom django.test import SimpleTestCase, override_settings\nfrom django.utils import translation\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import trans_real\n\nfrom ...utils import setup\nfrom .base import MultipleLocaleActivationTestCase, extended_locale_paths, here\n\n\nclass I18nBlockTransTagTests(SimpleTestCase):\n libraries = {'i18n': 'django.templatetags.i18n'}\n\n @setup({'i18n03': '{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}'})\n def test_i18n03(self):\n \"\"\"simple translation of a variable\"\"\"\n output = self.engine.render_to_string('i18n03', {'anton': b'\\xc3\\x85'})\n self.assertEqual(output, 'Å')\n\n @setup({'i18n04': '{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}'})\n def test_i18n04(self):\n \"\"\"simple translation of a variable and filter\"\"\"\n output = self.engine.render_to_string('i18n04', {'anton': b'\\xc3\\x85'})\n self.assertEqual(output, 'å')\n\n @setup({'legacyi18n04': '{% load i18n %}'\n '{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}'})\n def test_legacyi18n04(self):\n \"\"\"simple translation of a variable and filter\"\"\"\n output = self.engine.render_to_string('legacyi18n04', {'anton': b'\\xc3\\x85'})\n self.assertEqual(output, 'å')\n\n @setup({'i18n05': '{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}'})\n def test_i18n05(self):\n \"\"\"simple translation of a string with interpolation\"\"\"\n output = self.engine.render_to_string('i18n05', {'anton': 'yyy'})\n self.assertEqual(output, 'xxxyyyxxx')\n\n @setup({'i18n07': '{% load i18n %}'\n '{% blocktrans count counter=number %}singular{% plural %}'\n '{{ counter }} plural{% endblocktrans %}'})\n def test_i18n07(self):\n \"\"\"translation of singular form\"\"\"\n output = self.engine.render_to_string('i18n07', {'number': 1})\n self.assertEqual(output, 'singular')\n\n @setup({'legacyi18n07': '{% load i18n %}'\n '{% blocktrans count number as counter %}singular{% plural %}'\n '{{ counter }} plural{% endblocktrans %}'})\n def test_legacyi18n07(self):\n \"\"\"translation of singular form\"\"\"\n output = self.engine.render_to_string('legacyi18n07', {'number': 1})\n self.assertEqual(output, 'singular')\n\n @setup({'i18n08': '{% load i18n %}'\n '{% blocktrans count number as counter %}singular{% plural %}'\n '{{ counter }} plural{% endblocktrans %}'})\n def test_i18n08(self):\n \"\"\"translation of plural form\"\"\"\n output = self.engine.render_to_string('i18n08', {'number': 2})\n self.assertEqual(output, '2 plural')\n\n @setup({'legacyi18n08': '{% load i18n %}'\n '{% blocktrans count counter=number %}singular{% plural %}'\n '{{ counter }} plural{% endblocktrans %}'})\n def test_legacyi18n08(self):\n \"\"\"translation of plural form\"\"\"\n output = self.engine.render_to_string('legacyi18n08', {'number': 2})\n self.assertEqual(output, '2 plural')\n\n @setup({'i18n17': '{% load i18n %}'\n '{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}'})\n def test_i18n17(self):\n \"\"\"\n Escaping inside blocktrans and trans works as if it was directly in the\n template.\n \"\"\"\n output = self.engine.render_to_string('i18n17', {'anton': 'α & β'})\n self.assertEqual(output, 'α &amp; β')\n\n @setup({'i18n18': '{% load i18n %}'\n '{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}'})\n def test_i18n18(self):\n output = self.engine.render_to_string('i18n18', {'anton': 'α & β'})\n self.assertEqual(output, 'α &amp; β')\n\n @setup({'i18n19': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'})\n def test_i18n19(self):\n output = self.engine.render_to_string('i18n19', {'andrew': 'a & b'})\n self.assertEqual(output, 'a &amp; b')\n\n @setup({'i18n21': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'})\n def test_i18n21(self):\n output = self.engine.render_to_string('i18n21', {'andrew': mark_safe('a & b')})\n self.assertEqual(output, 'a & b')\n\n @setup({'legacyi18n17': '{% load i18n %}'\n '{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}'})\n def test_legacyi18n17(self):\n output = self.engine.render_to_string('legacyi18n17', {'anton': 'α & β'})\n self.assertEqual(output, 'α &amp; β')\n\n @setup({'legacyi18n18': '{% load i18n %}'\n '{% blocktrans with anton|force_escape as berta %}'\n '{{ berta }}{% endblocktrans %}'})\n def test_legacyi18n18(self):\n output = self.engine.render_to_string('legacyi18n18', {'anton': 'α & β'})\n self.assertEqual(output, 'α &amp; β')\n\n @setup({'i18n26': '{% load i18n %}'\n '{% blocktrans with extra_field=myextra_field count counter=number %}'\n 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'})\n def test_i18n26(self):\n \"\"\"\n translation of plural form with extra field in singular form (#13568)\n \"\"\"\n output = self.engine.render_to_string('i18n26', {'myextra_field': 'test', 'number': 1})\n self.assertEqual(output, 'singular test')\n\n @setup({'legacyi18n26': '{% load i18n %}'\n '{% blocktrans with myextra_field as extra_field count number as counter %}'\n 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'})\n def test_legacyi18n26(self):\n output = self.engine.render_to_string('legacyi18n26', {'myextra_field': 'test', 'number': 1})\n self.assertEqual(output, 'singular test')\n\n @setup({'i18n27': '{% load i18n %}{% blocktrans count counter=number %}'\n '{{ counter }} result{% plural %}{{ counter }} results'\n '{% endblocktrans %}'})\n def test_i18n27(self):\n \"\"\"translation of singular form in Russian (#14126)\"\"\"\n with translation.override('ru'):\n output = self.engine.render_to_string('i18n27', {'number': 1})\n self.assertEqual(output, '1 \\u0440\\u0435\\u0437\\u0443\\u043b\\u044c\\u0442\\u0430\\u0442')\n\n @setup({'legacyi18n27': '{% load i18n %}'\n '{% blocktrans count number as counter %}{{ counter }} result'\n '{% plural %}{{ counter }} results{% endblocktrans %}'})\n def test_legacyi18n27(self):\n with translation.override('ru'):\n output = self.engine.render_to_string('legacyi18n27', {'number': 1})\n self.assertEqual(output, '1 \\u0440\\u0435\\u0437\\u0443\\u043b\\u044c\\u0442\\u0430\\u0442')\n\n @setup({'i18n28': '{% load i18n %}'\n '{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}'})\n def test_i18n28(self):\n \"\"\"simple translation of multiple variables\"\"\"\n output = self.engine.render_to_string('i18n28', {'anton': 'α', 'berta': 'β'})\n self.assertEqual(output, 'α + β')\n\n @setup({'legacyi18n28': '{% load i18n %}'\n '{% blocktrans with anton as a and berta as b %}'\n '{{ a }} + {{ b }}{% endblocktrans %}'})\n def test_legacyi18n28(self):\n output = self.engine.render_to_string('legacyi18n28', {'anton': 'α', 'berta': 'β'})\n self.assertEqual(output, 'α + β')\n\n # blocktrans handling of variables which are not in the context.\n # this should work as if blocktrans was not there (#19915)\n @setup({'i18n34': '{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}'})\n def test_i18n34(self):\n output = self.engine.render_to_string('i18n34')\n if self.engine.string_if_invalid:\n self.assertEqual(output, 'INVALID')\n else:\n self.assertEqual(output, '')\n\n @setup({'i18n34_2': '{% load i18n %}{% blocktrans with a=\\'α\\' %}{{ missing }}{% endblocktrans %}'})\n def test_i18n34_2(self):\n output = self.engine.render_to_string('i18n34_2')\n if self.engine.string_if_invalid:\n self.assertEqual(output, 'INVALID')\n else:\n self.assertEqual(output, '')\n\n @setup({'i18n34_3': '{% load i18n %}{% blocktrans with a=anton %}{{ missing }}{% endblocktrans %}'})\n def test_i18n34_3(self):\n output = self.engine.render_to_string(\n 'i18n34_3', {'anton': '\\xce\\xb1'})\n if self.engine.string_if_invalid:\n self.assertEqual(output, 'INVALID')\n else:\n self.assertEqual(output, '')\n\n @setup({'i18n37': '{% load i18n %}'\n '{% trans \"Page not found\" as page_not_found %}'\n '{% blocktrans %}Error: {{ page_not_found }}{% endblocktrans %}'})\n def test_i18n37(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n37')\n self.assertEqual(output, 'Error: Seite nicht gefunden')\n\n # blocktrans tag with asvar\n @setup({'i18n39': '{% load i18n %}'\n '{% blocktrans asvar page_not_found %}Page not found{% endblocktrans %}'\n '>{{ page_not_found }}<'})\n def test_i18n39(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n39')\n self.assertEqual(output, '>Seite nicht gefunden<')\n\n @setup({'i18n40': '{% load i18n %}'\n '{% trans \"Page not found\" as pg_404 %}'\n '{% blocktrans with page_not_found=pg_404 asvar output %}'\n 'Error: {{ page_not_found }}'\n '{% endblocktrans %}'})\n def test_i18n40(self):\n output = self.engine.render_to_string('i18n40')\n self.assertEqual(output, '')\n\n @setup({'i18n41': '{% load i18n %}'\n '{% trans \"Page not found\" as pg_404 %}'\n '{% blocktrans with page_not_found=pg_404 asvar output %}'\n 'Error: {{ page_not_found }}'\n '{% endblocktrans %}'\n '>{{ output }}<'})\n def test_i18n41(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n41')\n self.assertEqual(output, '>Error: Seite nicht gefunden<')\n\n @setup({'template': '{% load i18n %}{% blocktrans asvar %}Yes{% endblocktrans %}'})\n def test_blocktrans_syntax_error_missing_assignment(self):\n msg = \"No argument provided to the 'blocktrans' tag for the asvar option.\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% blocktrans %}%s{% endblocktrans %}'})\n def test_blocktrans_tag_using_a_string_that_looks_like_str_fmt(self):\n output = self.engine.render_to_string('template')\n self.assertEqual(output, '%s')\n\n\nclass TranslationBlockTransTagTests(SimpleTestCase):\n\n @override_settings(LOCALE_PATHS=extended_locale_paths)\n def test_template_tags_pgettext(self):\n \"\"\"{% blocktrans %} takes message contexts into account (#14806).\"\"\"\n trans_real._active = local()\n trans_real._translations = {}\n with translation.override('de'):\n # Nonexistent context\n t = Template('{% load i18n %}{% blocktrans context \"nonexistent\" %}May{% endblocktrans %}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'May')\n\n # Existing context... using a literal\n t = Template('{% load i18n %}{% blocktrans context \"month name\" %}May{% endblocktrans %}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Mai')\n t = Template('{% load i18n %}{% blocktrans context \"verb\" %}May{% endblocktrans %}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Kann')\n\n # Using a variable\n t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}')\n rendered = t.render(Context({'message_context': 'month name'}))\n self.assertEqual(rendered, 'Mai')\n t = Template('{% load i18n %}{% blocktrans context message_context %}May{% endblocktrans %}')\n rendered = t.render(Context({'message_context': 'verb'}))\n self.assertEqual(rendered, 'Kann')\n\n # Using a filter\n t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}')\n rendered = t.render(Context({'message_context': 'MONTH NAME'}))\n self.assertEqual(rendered, 'Mai')\n t = Template('{% load i18n %}{% blocktrans context message_context|lower %}May{% endblocktrans %}')\n rendered = t.render(Context({'message_context': 'VERB'}))\n self.assertEqual(rendered, 'Kann')\n\n # Using 'count'\n t = Template(\n '{% load i18n %}{% blocktrans count number=1 context \"super search\" %}'\n '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, '1 Super-Ergebnis')\n t = Template(\n '{% load i18n %}{% blocktrans count number=2 context \"super search\" %}{{ number }}'\n ' super result{% plural %}{{ number }} super results{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, '2 Super-Ergebnisse')\n t = Template(\n '{% load i18n %}{% blocktrans context \"other super search\" count number=1 %}'\n '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, '1 anderen Super-Ergebnis')\n t = Template(\n '{% load i18n %}{% blocktrans context \"other super search\" count number=2 %}'\n '{{ number }} super result{% plural %}{{ number }} super results{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, '2 andere Super-Ergebnisse')\n\n # Using 'with'\n t = Template(\n '{% load i18n %}{% blocktrans with num_comments=5 context \"comment count\" %}'\n 'There are {{ num_comments }} comments{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Es gibt 5 Kommentare')\n t = Template(\n '{% load i18n %}{% blocktrans with num_comments=5 context \"other comment count\" %}'\n 'There are {{ num_comments }} comments{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Andere: Es gibt 5 Kommentare')\n\n # Using trimmed\n t = Template(\n '{% load i18n %}{% blocktrans trimmed %}\\n\\nThere\\n\\t are 5 '\n '\\n\\n comments\\n{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, 'There are 5 comments')\n t = Template(\n '{% load i18n %}{% blocktrans with num_comments=5 context \"comment count\" trimmed %}\\n\\n'\n 'There are \\t\\n \\t {{ num_comments }} comments\\n\\n{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Es gibt 5 Kommentare')\n t = Template(\n '{% load i18n %}{% blocktrans context \"other super search\" count number=2 trimmed %}\\n'\n '{{ number }} super \\n result{% plural %}{{ number }} super results{% endblocktrans %}'\n )\n rendered = t.render(Context())\n self.assertEqual(rendered, '2 andere Super-Ergebnisse')\n\n # Misuses\n with self.assertRaises(TemplateSyntaxError):\n Template('{% load i18n %}{% blocktrans context with month=\"May\" %}{{ month }}{% endblocktrans %}')\n with self.assertRaises(TemplateSyntaxError):\n Template('{% load i18n %}{% blocktrans context %}{% endblocktrans %}')\n with self.assertRaises(TemplateSyntaxError):\n Template(\n '{% load i18n %}{% blocktrans count number=2 context %}'\n '{{ number }} super result{% plural %}{{ number }}'\n ' super results{% endblocktrans %}'\n )\n\n @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])\n def test_bad_placeholder_1(self):\n \"\"\"\n Error in translation file should not crash template rendering (#16516).\n (%(person)s is translated as %(personne)s in fr.po).\n \"\"\"\n with translation.override('fr'):\n t = Template('{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}')\n rendered = t.render(Context({'person': 'James'}))\n self.assertEqual(rendered, 'My name is James.')\n\n @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])\n def test_bad_placeholder_2(self):\n \"\"\"\n Error in translation file should not crash template rendering (#18393).\n (%(person) misses a 's' in fr.po, causing the string formatting to fail)\n .\n \"\"\"\n with translation.override('fr'):\n t = Template('{% load i18n %}{% blocktrans %}My other name is {{ person }}.{% endblocktrans %}')\n rendered = t.render(Context({'person': 'James'}))\n self.assertEqual(rendered, 'My other name is James.')\n\n\nclass MultipleLocaleActivationBlockTransTests(MultipleLocaleActivationTestCase):\n\n def test_single_locale_activation(self):\n \"\"\"\n Simple baseline behavior with one locale for all the supported i18n\n constructs.\n \"\"\"\n with translation.override('fr'):\n self.assertEqual(\n Template(\"{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}\").render(Context({})),\n 'Oui'\n )\n\n def test_multiple_locale_btrans(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{% blocktrans %}No{% endblocktrans %}\")\n with translation.override(self._old_language), translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_deactivate_btrans(self):\n with translation.override('de', deactivate=True):\n t = Template(\"{% load i18n %}{% blocktrans %}No{% endblocktrans %}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_direct_switch_btrans(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{% blocktrans %}No{% endblocktrans %}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n\nclass MiscTests(SimpleTestCase):\n\n @override_settings(LOCALE_PATHS=extended_locale_paths)\n def test_percent_in_translatable_block(self):\n t_sing = Template(\"{% load i18n %}{% blocktrans %}The result was {{ percent }}%{% endblocktrans %}\")\n t_plur = Template(\n \"{% load i18n %}{% blocktrans count num as number %}\"\n \"{{ percent }}% represents {{ num }} object{% plural %}\"\n \"{{ percent }}% represents {{ num }} objects{% endblocktrans %}\"\n )\n with translation.override('de'):\n self.assertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%')\n self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar')\n self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar')\n\n @override_settings(LOCALE_PATHS=extended_locale_paths)\n def test_percent_formatting_in_blocktrans(self):\n \"\"\"\n Python's %-formatting is properly escaped in blocktrans, singular, or\n plural.\n \"\"\"\n t_sing = Template(\"{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}\")\n t_plur = Template(\n \"{% load i18n %}{% blocktrans count num as number %}\"\n \"%(percent)s% represents {{ num }} object{% plural %}\"\n \"%(percent)s% represents {{ num }} objects{% endblocktrans %}\"\n )\n with translation.override('de'):\n # Strings won't get translated as they don't match after escaping %\n self.assertEqual(t_sing.render(Context({'num_comments': 42})), 'There are %(num_comments)s comments')\n self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '%(percent)s% represents 1 object')\n self.assertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '%(percent)s% represents 4 objects')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":38,"cells":{"file_path":{"kind":"string","value":"tests/forms_tests/widget_tests/test_input.py"},"num_changed_lines":{"kind":"number","value":15,"string":"15"},"code":{"kind":"string","value":"from django.forms.widgets import Input\n\nfrom .base import WidgetTest\n\n\nclass InputTests(WidgetTest):\n\n def test_attrs_with_type(self):\n attrs = {'type': 'date'}\n widget = Input(attrs)\n self.check_html(widget, 'name', 'value', '')\n # reuse the same attrs for another widget\n self.check_html(Input(attrs), 'name', 'value', '')\n attrs['type'] = 'number' # shouldn't change the widget type\n self.check_html(widget, 'name', 'value', '')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":39,"cells":{"file_path":{"kind":"string","value":"tests/queries/test_qs_combinators.py"},"num_changed_lines":{"kind":"number","value":108,"string":"108"},"code":{"kind":"string","value":"from django.db.models import F, IntegerField, Value\nfrom django.db.utils import DatabaseError\nfrom django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature\n\nfrom .models import Number, ReservedName\n\n\n@skipUnlessDBFeature('supports_select_union')\nclass QuerySetSetOperationTests(TestCase):\n @classmethod\n def setUpTestData(cls):\n Number.objects.bulk_create(Number(num=i) for i in range(10))\n\n def number_transform(self, value):\n return value.num\n\n def assertNumbersEqual(self, queryset, expected_numbers, ordered=True):\n self.assertQuerysetEqual(queryset, expected_numbers, self.number_transform, ordered)\n\n def test_simple_union(self):\n qs1 = Number.objects.filter(num__lte=1)\n qs2 = Number.objects.filter(num__gte=8)\n qs3 = Number.objects.filter(num=5)\n self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False)\n\n @skipUnlessDBFeature('supports_select_intersection')\n def test_simple_intersection(self):\n qs1 = Number.objects.filter(num__lte=5)\n qs2 = Number.objects.filter(num__gte=5)\n qs3 = Number.objects.filter(num__gte=4, num__lte=6)\n self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False)\n\n @skipUnlessDBFeature('supports_select_difference')\n def test_simple_difference(self):\n qs1 = Number.objects.filter(num__lte=5)\n qs2 = Number.objects.filter(num__lte=4)\n self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False)\n\n def test_union_distinct(self):\n qs1 = Number.objects.all()\n qs2 = Number.objects.all()\n self.assertEqual(len(list(qs1.union(qs2, all=True))), 20)\n self.assertEqual(len(list(qs1.union(qs2))), 10)\n\n def test_union_bad_kwarg(self):\n qs1 = Number.objects.all()\n msg = \"union() received an unexpected keyword argument 'bad'\"\n with self.assertRaisesMessage(TypeError, msg):\n self.assertEqual(len(list(qs1.union(qs1, bad=True))), 20)\n\n def test_limits(self):\n qs1 = Number.objects.all()\n qs2 = Number.objects.all()\n self.assertEqual(len(list(qs1.union(qs2)[:2])), 2)\n\n def test_ordering(self):\n qs1 = Number.objects.filter(num__lte=1)\n qs2 = Number.objects.filter(num__gte=2, num__lte=3)\n self.assertNumbersEqual(qs1.union(qs2).order_by('-num'), [3, 2, 1, 0])\n\n @skipUnlessDBFeature('supports_slicing_ordering_in_compound')\n def test_ordering_subqueries(self):\n qs1 = Number.objects.order_by('num')[:2]\n qs2 = Number.objects.order_by('-num')[:2]\n self.assertNumbersEqual(qs1.union(qs2).order_by('-num')[:4], [9, 8, 1, 0])\n\n @skipIfDBFeature('supports_slicing_ordering_in_compound')\n def test_unsupported_ordering_slicing_raises_db_error(self):\n qs1 = Number.objects.all()\n qs2 = Number.objects.all()\n msg = 'LIMIT/OFFSET not allowed in subqueries of compound statements'\n with self.assertRaisesMessage(DatabaseError, msg):\n list(qs1.union(qs2[:10]))\n msg = 'ORDER BY not allowed in subqueries of compound statements'\n with self.assertRaisesMessage(DatabaseError, msg):\n list(qs1.order_by('id').union(qs2))\n\n @skipIfDBFeature('supports_select_intersection')\n def test_unsupported_intersection_raises_db_error(self):\n qs1 = Number.objects.all()\n qs2 = Number.objects.all()\n msg = 'intersection not supported on this database backend'\n with self.assertRaisesMessage(DatabaseError, msg):\n list(qs1.intersection(qs2))\n\n def test_combining_multiple_models(self):\n ReservedName.objects.create(name='99 little bugs', order=99)\n qs1 = Number.objects.filter(num=1).values_list('num', flat=True)\n qs2 = ReservedName.objects.values_list('order')\n self.assertEqual(list(qs1.union(qs2).order_by('num')), [1, 99])\n\n def test_order_raises_on_non_selected_column(self):\n qs1 = Number.objects.filter().annotate(\n annotation=Value(1, IntegerField()),\n ).values('annotation', num2=F('num'))\n qs2 = Number.objects.filter().values('id', 'num')\n # Should not raise\n list(qs1.union(qs2).order_by('annotation'))\n list(qs1.union(qs2).order_by('num2'))\n msg = 'ORDER BY term does not match any column in the result set'\n # 'id' is not part of the select\n with self.assertRaisesMessage(DatabaseError, msg):\n list(qs1.union(qs2).order_by('id'))\n # 'num' got realiased to num2\n with self.assertRaisesMessage(DatabaseError, msg):\n list(qs1.union(qs2).order_by('num'))\n # switched order, now 'exists' again:\n list(qs2.union(qs1).order_by('num'))\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":40,"cells":{"file_path":{"kind":"string","value":"tests/staticfiles_tests/project/loop/foo.css"},"num_changed_lines":{"kind":"number","value":1,"string":"1"},"code":{"kind":"string","value":"@import url(\"bar.css\")\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":41,"cells":{"file_path":{"kind":"string","value":"django/contrib/gis/static/gis/js/OLMapWidget.js"},"num_changed_lines":{"kind":"number","value":208,"string":"208"},"code":{"kind":"string","value":"/* global ol */\n\nvar GeometryTypeControl = function(opt_options) {\n 'use strict';\n // Map control to switch type when geometry type is unknown\n var options = opt_options || {};\n\n var element = document.createElement('div');\n element.className = 'switch-type type-' + options.type + ' ol-control ol-unselectable';\n if (options.active) {\n element.className += \" type-active\";\n }\n\n var self = this;\n var switchType = function(e) {\n e.preventDefault();\n if (options.widget.currentGeometryType !== self) {\n options.widget.map.removeInteraction(options.widget.interactions.draw);\n options.widget.interactions.draw = new ol.interaction.Draw({\n features: options.widget.featureCollection,\n type: options.type\n });\n options.widget.map.addInteraction(options.widget.interactions.draw);\n var className = options.widget.currentGeometryType.element.className.replace(/ type-active/g, '');\n options.widget.currentGeometryType.element.className = className;\n options.widget.currentGeometryType = self;\n element.className += \" type-active\";\n }\n };\n\n element.addEventListener('click', switchType, false);\n element.addEventListener('touchstart', switchType, false);\n\n ol.control.Control.call(this, {\n element: element\n });\n};\nol.inherits(GeometryTypeControl, ol.control.Control);\n\n// TODO: allow deleting individual features (#8972)\n(function() {\n 'use strict';\n var jsonFormat = new ol.format.GeoJSON();\n\n function MapWidget(options) {\n this.map = null;\n this.interactions = {draw: null, modify: null};\n this.typeChoices = false;\n this.ready = false;\n\n // Default options\n this.options = {\n default_lat: 0,\n default_lon: 0,\n default_zoom: 12,\n is_collection: options.geom_name.indexOf('Multi') > -1 || options.geom_name.indexOf('Collection') > -1\n };\n\n // Altering using user-provided options\n for (var property in options) {\n if (options.hasOwnProperty(property)) {\n this.options[property] = options[property];\n }\n }\n if (!options.base_layer) {\n this.options.base_layer = new ol.layer.Tile({source: new ol.source.OSM()});\n }\n\n this.map = this.createMap();\n this.featureCollection = new ol.Collection();\n this.featureOverlay = new ol.layer.Vector({\n map: this.map,\n source: new ol.source.Vector({\n features: this.featureCollection,\n useSpatialIndex: false // improve performance\n }),\n updateWhileAnimating: true, // optional, for instant visual feedback\n updateWhileInteracting: true // optional, for instant visual feedback\n });\n\n // Populate and set handlers for the feature container\n var self = this;\n this.featureCollection.on('add', function(event) {\n var feature = event.element;\n feature.on('change', function() {\n self.serializeFeatures();\n });\n if (self.ready) {\n self.serializeFeatures();\n if (!self.options.is_collection) {\n self.disableDrawing(); // Only allow one feature at a time\n }\n }\n });\n\n var initial_value = document.getElementById(this.options.id).value;\n if (initial_value) {\n var features = jsonFormat.readFeatures('{\"type\": \"Feature\", \"geometry\": ' + initial_value + '}');\n var extent = ol.extent.createEmpty();\n features.forEach(function(feature) {\n this.featureOverlay.getSource().addFeature(feature);\n ol.extent.extend(extent, feature.getGeometry().getExtent());\n }, this);\n // Center/zoom the map\n this.map.getView().fit(extent, this.map.getSize(), {maxZoom: this.options.default_zoom});\n } else {\n this.map.getView().setCenter(this.defaultCenter());\n }\n this.createInteractions();\n if (initial_value && !this.options.is_collection) {\n this.disableDrawing();\n }\n this.ready = true;\n }\n\n MapWidget.prototype.createMap = function() {\n var map = new ol.Map({\n target: this.options.map_id,\n layers: [this.options.base_layer],\n view: new ol.View({\n zoom: this.options.default_zoom\n })\n });\n return map;\n };\n\n MapWidget.prototype.createInteractions = function() {\n // Initialize the modify interaction\n this.interactions.modify = new ol.interaction.Modify({\n features: this.featureCollection,\n deleteCondition: function(event) {\n return ol.events.condition.shiftKeyOnly(event) &&\n ol.events.condition.singleClick(event);\n }\n });\n\n // Initialize the draw interaction\n var geomType = this.options.geom_name;\n if (geomType === \"Unknown\" || geomType === \"GeometryCollection\") {\n // Default to Point, but create icons to switch type\n geomType = \"Point\";\n this.currentGeometryType = new GeometryTypeControl({widget: this, type: \"Point\", active: true});\n this.map.addControl(this.currentGeometryType);\n this.map.addControl(new GeometryTypeControl({widget: this, type: \"LineString\", active: false}));\n this.map.addControl(new GeometryTypeControl({widget: this, type: \"Polygon\", active: false}));\n this.typeChoices = true;\n }\n this.interactions.draw = new ol.interaction.Draw({\n features: this.featureCollection,\n type: geomType\n });\n\n this.map.addInteraction(this.interactions.draw);\n this.map.addInteraction(this.interactions.modify);\n };\n\n MapWidget.prototype.defaultCenter = function() {\n var center = [this.options.default_lon, this.options.default_lat];\n if (this.options.map_srid) {\n return ol.proj.transform(center, 'EPSG:4326', this.map.getView().getProjection());\n }\n return center;\n };\n\n MapWidget.prototype.enableDrawing = function() {\n this.interactions.draw.setActive(true);\n if (this.typeChoices) {\n // Show geometry type icons\n var divs = document.getElementsByClassName(\"switch-type\");\n for (var i = 0; i !== divs.length; i++) {\n divs[i].style.visibility = \"visible\";\n }\n }\n };\n\n MapWidget.prototype.disableDrawing = function() {\n if (this.interactions.draw) {\n this.interactions.draw.setActive(false);\n if (this.typeChoices) {\n // Hide geometry type icons\n var divs = document.getElementsByClassName(\"switch-type\");\n for (var i = 0; i !== divs.length; i++) {\n divs[i].style.visibility = \"hidden\";\n }\n }\n }\n };\n\n MapWidget.prototype.clearFeatures = function() {\n this.featureCollection.clear();\n // Empty textarea widget\n document.getElementById(this.options.id).value = '';\n this.enableDrawing();\n };\n\n MapWidget.prototype.serializeFeatures = function() {\n // Three use cases: GeometryCollection, multigeometries, and single geometry\n var geometry = null;\n var features = this.featureOverlay.getSource().getFeatures();\n if (this.options.is_collection) {\n if (this.options.geom_name === \"GeometryCollection\") {\n var geometries = [];\n for (var i = 0; i < features.length; i++) {\n geometries.push(features[i].getGeometry());\n }\n geometry = new ol.geom.GeometryCollection(geometries);\n } else {\n geometry = features[0].getGeometry().clone();\n for (var j = 1; j < features.length; j++) {\n switch(geometry.getType()) {\n case \"MultiPoint\":\n geometry.appendPoint(features[j].getGeometry().getPoint(0));\n break;\n case \"MultiLineString\":\n geometry.appendLineString(features[j].getGeometry().getLineString(0));\n break;\n case \"MultiPolygon\":\n geometry.appendPolygon(features[j].getGeometry().getPolygon(0));\n }\n }\n }\n } else {\n if (features[0]) {\n geometry = features[0].getGeometry();\n }\n }\n document.getElementById(this.options.id).value = jsonFormat.writeGeometry(geometry);\n };\n\n window.MapWidget = MapWidget;\n})();\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":42,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/test_trans.py"},"num_changed_lines":{"kind":"number","value":205,"string":"205"},"code":{"kind":"string","value":"from threading import local\n\nfrom django.template import Context, Template, TemplateSyntaxError\nfrom django.test import SimpleTestCase, override_settings\nfrom django.utils import translation\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import trans_real\n\nfrom ...utils import setup\nfrom .base import MultipleLocaleActivationTestCase, extended_locale_paths\n\n\nclass I18nTransTagTests(SimpleTestCase):\n libraries = {'i18n': 'django.templatetags.i18n'}\n\n @setup({'i18n01': '{% load i18n %}{% trans \\'xxxyyyxxx\\' %}'})\n def test_i18n01(self):\n \"\"\"simple translation of a string delimited by '.\"\"\"\n output = self.engine.render_to_string('i18n01')\n self.assertEqual(output, 'xxxyyyxxx')\n\n @setup({'i18n02': '{% load i18n %}{% trans \"xxxyyyxxx\" %}'})\n def test_i18n02(self):\n \"\"\"simple translation of a string delimited by \".\"\"\"\n output = self.engine.render_to_string('i18n02')\n self.assertEqual(output, 'xxxyyyxxx')\n\n @setup({'i18n06': '{% load i18n %}{% trans \"Page not found\" %}'})\n def test_i18n06(self):\n \"\"\"simple translation of a string to German\"\"\"\n with translation.override('de'):\n output = self.engine.render_to_string('i18n06')\n self.assertEqual(output, 'Seite nicht gefunden')\n\n @setup({'i18n09': '{% load i18n %}{% trans \"Page not found\" noop %}'})\n def test_i18n09(self):\n \"\"\"simple non-translation (only marking) of a string to German\"\"\"\n with translation.override('de'):\n output = self.engine.render_to_string('i18n09')\n self.assertEqual(output, 'Page not found')\n\n @setup({'i18n20': '{% load i18n %}{% trans andrew %}'})\n def test_i18n20(self):\n output = self.engine.render_to_string('i18n20', {'andrew': 'a & b'})\n self.assertEqual(output, 'a &amp; b')\n\n @setup({'i18n22': '{% load i18n %}{% trans andrew %}'})\n def test_i18n22(self):\n output = self.engine.render_to_string('i18n22', {'andrew': mark_safe('a & b')})\n self.assertEqual(output, 'a & b')\n\n @setup({'i18n23': '{% load i18n %}{% trans \"Page not found\"|capfirst|slice:\"6:\" %}'})\n def test_i18n23(self):\n \"\"\"Using filters with the {% trans %} tag (#5972).\"\"\"\n with translation.override('de'):\n output = self.engine.render_to_string('i18n23')\n self.assertEqual(output, 'nicht gefunden')\n\n @setup({'i18n24': '{% load i18n %}{% trans \\'Page not found\\'|upper %}'})\n def test_i18n24(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n24')\n self.assertEqual(output, 'SEITE NICHT GEFUNDEN')\n\n @setup({'i18n25': '{% load i18n %}{% trans somevar|upper %}'})\n def test_i18n25(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n25', {'somevar': 'Page not found'})\n self.assertEqual(output, 'SEITE NICHT GEFUNDEN')\n\n # trans tag with as var\n @setup({'i18n35': '{% load i18n %}{% trans \"Page not found\" as page_not_found %}{{ page_not_found }}'})\n def test_i18n35(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n35')\n self.assertEqual(output, 'Seite nicht gefunden')\n\n @setup({'i18n36': '{% load i18n %}'\n '{% trans \"Page not found\" noop as page_not_found %}{{ page_not_found }}'})\n def test_i18n36(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n36')\n self.assertEqual(output, 'Page not found')\n\n @setup({'template': '{% load i18n %}{% trans %}A}'})\n def test_syntax_error_no_arguments(self):\n msg = \"'trans' takes at least one argument\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% trans \"Yes\" badoption %}'})\n def test_syntax_error_bad_option(self):\n msg = \"Unknown argument for 'trans' tag: 'badoption'\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% trans \"Yes\" as %}'})\n def test_syntax_error_missing_assignment(self):\n msg = \"No argument provided to the 'trans' tag for the as option.\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% trans \"Yes\" as var context %}'})\n def test_syntax_error_missing_context(self):\n msg = \"No argument provided to the 'trans' tag for the context option.\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% trans \"Yes\" context as var %}'})\n def test_syntax_error_context_as(self):\n msg = \"Invalid argument 'as' provided to the 'trans' tag for the context option\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% trans \"Yes\" context noop %}'})\n def test_syntax_error_context_noop(self):\n msg = \"Invalid argument 'noop' provided to the 'trans' tag for the context option\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% trans \"Yes\" noop noop %}'})\n def test_syntax_error_duplicate_option(self):\n msg = \"The 'noop' option was specified more than once.\"\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n self.engine.render_to_string('template')\n\n @setup({'template': '{% load i18n %}{% trans \"%s\" %}'})\n def test_trans_tag_using_a_string_that_looks_like_str_fmt(self):\n output = self.engine.render_to_string('template')\n self.assertEqual(output, '%s')\n\n\nclass TranslationTransTagTests(SimpleTestCase):\n\n @override_settings(LOCALE_PATHS=extended_locale_paths)\n def test_template_tags_pgettext(self):\n \"\"\"{% trans %} takes message contexts into account (#14806).\"\"\"\n trans_real._active = local()\n trans_real._translations = {}\n with translation.override('de'):\n # Nonexistent context...\n t = Template('{% load i18n %}{% trans \"May\" context \"nonexistent\" %}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'May')\n\n # Existing context... using a literal\n t = Template('{% load i18n %}{% trans \"May\" context \"month name\" %}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Mai')\n t = Template('{% load i18n %}{% trans \"May\" context \"verb\" %}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Kann')\n\n # Using a variable\n t = Template('{% load i18n %}{% trans \"May\" context message_context %}')\n rendered = t.render(Context({'message_context': 'month name'}))\n self.assertEqual(rendered, 'Mai')\n t = Template('{% load i18n %}{% trans \"May\" context message_context %}')\n rendered = t.render(Context({'message_context': 'verb'}))\n self.assertEqual(rendered, 'Kann')\n\n # Using a filter\n t = Template('{% load i18n %}{% trans \"May\" context message_context|lower %}')\n rendered = t.render(Context({'message_context': 'MONTH NAME'}))\n self.assertEqual(rendered, 'Mai')\n t = Template('{% load i18n %}{% trans \"May\" context message_context|lower %}')\n rendered = t.render(Context({'message_context': 'VERB'}))\n self.assertEqual(rendered, 'Kann')\n\n # Using 'as'\n t = Template('{% load i18n %}{% trans \"May\" context \"month name\" as var %}Value: {{ var }}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Value: Mai')\n t = Template('{% load i18n %}{% trans \"May\" as var context \"verb\" %}Value: {{ var }}')\n rendered = t.render(Context())\n self.assertEqual(rendered, 'Value: Kann')\n\n\nclass MultipleLocaleActivationTransTagTests(MultipleLocaleActivationTestCase):\n\n def test_single_locale_activation(self):\n \"\"\"\n Simple baseline behavior with one locale for all the supported i18n\n constructs.\n \"\"\"\n with translation.override('fr'):\n self.assertEqual(Template(\"{% load i18n %}{% trans 'Yes' %}\").render(Context({})), 'Oui')\n\n def test_multiple_locale_trans(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{% trans 'No' %}\")\n with translation.override(self._old_language), translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_deactivate_trans(self):\n with translation.override('de', deactivate=True):\n t = Template(\"{% load i18n %}{% trans 'No' %}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_direct_switch_trans(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{% trans 'No' %}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":43,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/base.py"},"num_changed_lines":{"kind":"number","value":24,"string":"24"},"code":{"kind":"string","value":"import os\n\nfrom django.conf import settings\nfrom django.test import SimpleTestCase\nfrom django.utils.translation import activate, get_language\n\nhere = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\npdir = os.path.split(os.path.split(os.path.abspath(here))[0])[0]\nextended_locale_paths = settings.LOCALE_PATHS + [\n os.path.join(pdir, 'i18n', 'other', 'locale'),\n]\n\n\nclass MultipleLocaleActivationTestCase(SimpleTestCase):\n \"\"\"\n Tests for template rendering when multiple locales are activated during the\n lifetime of the same process.\n \"\"\"\n\n def setUp(self):\n self._old_language = get_language()\n\n def tearDown(self):\n activate(self._old_language)\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":44,"cells":{"file_path":{"kind":"string","value":"django/contrib/admindocs/utils.py"},"num_changed_lines":{"kind":"number","value":91,"string":"91"},"code":{"kind":"string","value":"\"Misc. utility functions/classes for admin documentation generator.\"\n\nimport re\nfrom email.errors import HeaderParseError\nfrom email.parser import HeaderParser\n\nfrom django.urls import reverse\nfrom django.utils.encoding import force_bytes\nfrom django.utils.safestring import mark_safe\n\ntry:\n import docutils.core\n import docutils.nodes\n import docutils.parsers.rst.roles\nexcept ImportError:\n docutils_is_available = False\nelse:\n docutils_is_available = True\n\n\ndef trim_docstring(docstring):\n \"\"\"\n Uniformly trim leading/trailing whitespace from docstrings.\n\n Based on https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation\n \"\"\"\n if not docstring or not docstring.strip():\n return ''\n # Convert tabs to spaces and split into lines\n lines = docstring.expandtabs().splitlines()\n indent = min(len(line) - len(line.lstrip()) for line in lines if line.lstrip())\n trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]]\n return \"\\n\".join(trimmed).strip()\n\n\ndef parse_docstring(docstring):\n \"\"\"\n Parse out the parts of a docstring. Return (title, body, metadata).\n \"\"\"\n docstring = trim_docstring(docstring)\n parts = re.split(r'\\n{2,}', docstring)\n title = parts[0]\n if len(parts) == 1:\n body = ''\n metadata = {}\n else:\n parser = HeaderParser()\n try:\n metadata = parser.parsestr(parts[-1])\n except HeaderParseError:\n metadata = {}\n body = \"\\n\\n\".join(parts[1:])\n else:\n metadata = dict(metadata.items())\n if metadata:\n body = \"\\n\\n\".join(parts[1:-1])\n else:\n body = \"\\n\\n\".join(parts[1:])\n return title, body, metadata\n\n\ndef parse_rst(text, default_reference_context, thing_being_parsed=None):\n \"\"\"\n Convert the string from reST to an XHTML fragment.\n \"\"\"\n overrides = {\n 'doctitle_xform': True,\n 'initial_header_level': 3,\n \"default_reference_context\": default_reference_context,\n \"link_base\": reverse('django-admindocs-docroot').rstrip('/'),\n 'raw_enabled': False,\n 'file_insertion_enabled': False,\n }\n if thing_being_parsed:\n thing_being_parsed = force_bytes(\"<%s>\" % thing_being_parsed)\n # Wrap ``text`` in some reST that sets the default role to ``cmsreference``,\n # then restores it.\n source = \"\"\"\n.. default-role:: cmsreference\n\n%s\n\n.. default-role::\n\"\"\"\n parts = docutils.core.publish_parts(\n source % text,\n source_path=thing_being_parsed, destination_path=None,\n writer_name='html', settings_overrides=overrides,\n )\n return mark_safe(parts['fragment'])\n\n\n#\n# reST roles\n#\nROLES = {\n 'model': '%s/models/%s/',\n 'view': '%s/views/%s/',\n 'template': '%s/templates/%s/',\n 'filter': '%s/filters/#%s',\n 'tag': '%s/tags/#%s',\n}\n\n\ndef create_reference_role(rolename, urlbase):\n def _role(name, rawtext, text, lineno, inliner, options=None, content=None):\n if options is None:\n options = {}\n if content is None:\n content = []\n node = docutils.nodes.reference(\n rawtext,\n text,\n refuri=(urlbase % (\n inliner.document.settings.link_base,\n text.lower(),\n )),\n **options\n )\n return [node], []\n docutils.parsers.rst.roles.register_canonical_role(rolename, _role)\n\n\ndef default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n if options is None:\n options = {}\n if content is None:\n content = []\n context = inliner.document.settings.default_reference_context\n node = docutils.nodes.reference(\n rawtext,\n text,\n refuri=(ROLES[context] % (\n inliner.document.settings.link_base,\n text.lower(),\n )),\n **options\n )\n return [node], []\n\n\nif docutils_is_available:\n docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role)\n\n for name, urlbase in ROLES.items():\n create_reference_role(name, urlbase)\n\n# Match the beginning of a named or unnamed group.\nnamed_group_matcher = re.compile(r'\\(\\?P(<\\w+>)')\nunnamed_group_matcher = re.compile(r'\\(')\n\n\ndef replace_named_groups(pattern):\n r\"\"\"\n Find named groups in `pattern` and replace them with the group name. E.g.,\n 1. ^(?P\\w+)/b/(\\w+)$ ==> ^/b/(\\w+)$\n 2. ^(?P\\w+)/b/(?P\\w+)/$ ==> ^/b//$\n \"\"\"\n named_group_indices = [\n (m.start(0), m.end(0), m.group(1))\n for m in named_group_matcher.finditer(pattern)\n ]\n # Tuples of (named capture group pattern, group name).\n group_pattern_and_name = []\n # Loop over the groups and their start and end indices.\n for start, end, group_name in named_group_indices:\n # Handle nested parentheses, e.g. '^(?P(x|y))/b'.\n unmatched_open_brackets, prev_char = 1, None\n for idx, val in enumerate(list(pattern[end:])):\n # If brackets are balanced, the end of the string for the current\n # named capture group pattern has been reached.\n if unmatched_open_brackets == 0:\n group_pattern_and_name.append((pattern[start:end + idx], group_name))\n break\n\n # Check for unescaped `(` and `)`. They mark the start and end of a\n # nested group.\n if val == '(' and prev_char != '\\\\':\n unmatched_open_brackets += 1\n elif val == ')' and prev_char != '\\\\':\n unmatched_open_brackets -= 1\n prev_char = val\n\n # Replace the string for named capture groups with their group names.\n for group_pattern, group_name in group_pattern_and_name:\n pattern = pattern.replace(group_pattern, group_name)\n return pattern\n\n\ndef replace_unnamed_groups(pattern):\n r\"\"\"\n Find unnamed groups in `pattern` and replace them with ''. E.g.,\n 1. ^(?P\\w+)/b/(\\w+)$ ==> ^(?P\\w+)/b/$\n 2. ^(?P\\w+)/b/((x|y)\\w+)$ ==> ^(?P\\w+)/b/$\n \"\"\"\n unnamed_group_indices = [m.start(0) for m in unnamed_group_matcher.finditer(pattern)]\n # Indices of the start of unnamed capture groups.\n group_indices = []\n # Loop over the start indices of the groups.\n for start in unnamed_group_indices:\n # Handle nested parentheses, e.g. '^b/((x|y)\\w+)$'.\n unmatched_open_brackets, prev_char = 1, None\n for idx, val in enumerate(list(pattern[start + 1:])):\n if unmatched_open_brackets == 0:\n group_indices.append((start, start + 1 + idx))\n break\n\n # Check for unescaped `(` and `)`. They mark the start and end of\n # a nested group.\n if val == '(' and prev_char != '\\\\':\n unmatched_open_brackets += 1\n elif val == ')' and prev_char != '\\\\':\n unmatched_open_brackets -= 1\n prev_char = val\n\n # Remove unnamed group matches inside other unnamed capture groups.\n group_start_end_indices = []\n prev_end = None\n for start, end in group_indices:\n if prev_end and start > prev_end or not prev_end:\n group_start_end_indices.append((start, end))\n prev_end = end\n\n if group_start_end_indices:\n # Replace unnamed groups with . Handle the fact that replacing the\n # string between indices will change string length and thus indices\n # will point to the wrong substring if not corrected.\n final_pattern, prev_end = [], None\n for start, end in group_start_end_indices:\n if prev_end:\n final_pattern.append(pattern[prev_end:start])\n final_pattern.append(pattern[:start] + '')\n prev_end = end\n final_pattern.append(pattern[prev_end:])\n return ''.join(final_pattern)\n else:\n return pattern\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":45,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/test_get_available_languages.py"},"num_changed_lines":{"kind":"number","value":14,"string":"14"},"code":{"kind":"string","value":"from django.test import SimpleTestCase\n\nfrom ...utils import setup\n\n\nclass GetAvailableLanguagesTagTests(SimpleTestCase):\n libraries = {'i18n': 'django.templatetags.i18n'}\n\n @setup({'i18n12': '{% load i18n %}'\n '{% get_available_languages as langs %}{% for lang in langs %}'\n '{% if lang.0 == \"de\" %}{{ lang.0 }}{% endif %}{% endfor %}'})\n def test_i18n12(self):\n output = self.engine.render_to_string('i18n12')\n self.assertEqual(output, 'de')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":46,"cells":{"file_path":{"kind":"string","value":"tests/staticfiles_tests/project/loop/bar.css"},"num_changed_lines":{"kind":"number","value":1,"string":"1"},"code":{"kind":"string","value":"@import url(\"foo.css\")\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":47,"cells":{"file_path":{"kind":"string","value":"tests/backends/test_postgresql.py"},"num_changed_lines":{"kind":"number","value":54,"string":"54"},"code":{"kind":"string","value":"import unittest\nfrom collections import namedtuple\n\nfrom django.db import connection\nfrom django.test import TestCase\n\nfrom .models import Person\n\n\n@unittest.skipUnless(connection.vendor == 'postgresql', \"Test only for PostgreSQL\")\nclass ServerSideCursorsPostgres(TestCase):\n cursor_fields = 'name, statement, is_holdable, is_binary, is_scrollable, creation_time'\n PostgresCursor = namedtuple('PostgresCursor', cursor_fields)\n\n @classmethod\n def setUpTestData(cls):\n Person.objects.create(first_name='a', last_name='a')\n Person.objects.create(first_name='b', last_name='b')\n\n def inspect_cursors(self):\n with connection.cursor() as cursor:\n cursor.execute('SELECT {fields} FROM pg_cursors;'.format(fields=self.cursor_fields))\n cursors = cursor.fetchall()\n return [self.PostgresCursor._make(cursor) for cursor in cursors]\n\n def test_server_side_cursor(self):\n persons = Person.objects.iterator()\n next(persons) # Open a server-side cursor\n cursors = self.inspect_cursors()\n self.assertEqual(len(cursors), 1)\n self.assertIn('_django_curs_', cursors[0].name)\n self.assertFalse(cursors[0].is_scrollable)\n self.assertFalse(cursors[0].is_holdable)\n self.assertFalse(cursors[0].is_binary)\n\n def test_server_side_cursor_many_cursors(self):\n persons = Person.objects.iterator()\n persons2 = Person.objects.iterator()\n next(persons) # Open a server-side cursor\n next(persons2) # Open a second server-side cursor\n cursors = self.inspect_cursors()\n self.assertEqual(len(cursors), 2)\n for cursor in cursors:\n self.assertIn('_django_curs_', cursor.name)\n self.assertFalse(cursor.is_scrollable)\n self.assertFalse(cursor.is_holdable)\n self.assertFalse(cursor.is_binary)\n\n def test_closed_server_side_cursor(self):\n persons = Person.objects.iterator()\n next(persons) # Open a server-side cursor\n del persons\n cursors = self.inspect_cursors()\n self.assertEqual(len(cursors), 0)\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":48,"cells":{"file_path":{"kind":"string","value":"tests/forms_tests/widget_tests/test_widget.py"},"num_changed_lines":{"kind":"number","value":11,"string":"11"},"code":{"kind":"string","value":"from django.forms import Widget\nfrom django.forms.widgets import Input\n\nfrom .base import WidgetTest\n\n\nclass WidgetTests(WidgetTest):\n\n def test_value_omitted_from_data(self):\n widget = Widget()\n self.assertIs(widget.value_omitted_from_data({}, {}, 'field'), True)\n self.assertIs(widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False)\n\n def test_no_trailing_newline_in_attrs(self):\n self.check_html(Input(), 'name', 'value', strict=True, html='')\n\n def test_attr_false_not_rendered(self):\n html = ''\n self.check_html(Input(), 'name', 'value', html=html, attrs={'readonly': False})\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":49,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py"},"num_changed_lines":{"kind":"number","value":107,"string":"107"},"code":{"kind":"string","value":"from django.template import Context, Template\nfrom django.test import SimpleTestCase\nfrom django.utils import translation\n\nfrom ...utils import setup\nfrom .base import MultipleLocaleActivationTestCase\n\n\nclass MultipleLocaleActivationTests(MultipleLocaleActivationTestCase):\n\n def test_single_locale_activation(self):\n \"\"\"\n Simple baseline behavior with one locale for all the supported i18n\n constructs.\n \"\"\"\n with translation.override('fr'):\n self.assertEqual(Template(\"{{ _('Yes') }}\").render(Context({})), 'Oui')\n\n # Literal marked up with _() in a filter expression\n\n def test_multiple_locale_filter(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}\")\n with translation.override(self._old_language), translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'nee')\n\n def test_multiple_locale_filter_deactivate(self):\n with translation.override('de', deactivate=True):\n t = Template(\"{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'nee')\n\n def test_multiple_locale_filter_direct_switch(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'nee')\n\n # Literal marked up with _()\n\n def test_multiple_locale(self):\n with translation.override('de'):\n t = Template(\"{{ _('No') }}\")\n with translation.override(self._old_language), translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_deactivate(self):\n with translation.override('de', deactivate=True):\n t = Template(\"{{ _('No') }}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_direct_switch(self):\n with translation.override('de'):\n t = Template(\"{{ _('No') }}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n # Literal marked up with _(), loading the i18n template tag library\n\n def test_multiple_locale_loadi18n(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{{ _('No') }}\")\n with translation.override(self._old_language), translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_loadi18n_deactivate(self):\n with translation.override('de', deactivate=True):\n t = Template(\"{% load i18n %}{{ _('No') }}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n def test_multiple_locale_loadi18n_direct_switch(self):\n with translation.override('de'):\n t = Template(\"{% load i18n %}{{ _('No') }}\")\n with translation.override('nl'):\n self.assertEqual(t.render(Context({})), 'Nee')\n\n\nclass I18nStringLiteralTests(SimpleTestCase):\n \"\"\"translation of constant strings\"\"\"\n libraries = {'i18n': 'django.templatetags.i18n'}\n\n @setup({'i18n13': '{{ _(\"Password\") }}'})\n def test_i18n13(self):\n\n with translation.override('de'):\n output = self.engine.render_to_string('i18n13')\n self.assertEqual(output, 'Passwort')\n\n @setup({'i18n14': '{% cycle \"foo\" _(\"Password\") _(\\'Password\\') as c %} {% cycle c %} {% cycle c %}'})\n def test_i18n14(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n14')\n self.assertEqual(output, 'foo Passwort Passwort')\n\n @setup({'i18n15': '{{ absent|default:_(\"Password\") }}'})\n def test_i18n15(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n15', {'absent': ''})\n self.assertEqual(output, 'Passwort')\n\n @setup({'i18n16': '{{ _(\"<\") }}'})\n def test_i18n16(self):\n with translation.override('de'):\n output = self.engine.render_to_string('i18n16')\n self.assertEqual(output, '<')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":50,"cells":{"file_path":{"kind":"string","value":"tests/postgres_tests/test_indexes.py"},"num_changed_lines":{"kind":"number","value":49,"string":"49"},"code":{"kind":"string","value":"from django.contrib.postgres.indexes import BrinIndex, GinIndex\nfrom django.db import connection\nfrom django.test import skipUnlessDBFeature\n\nfrom . import PostgreSQLTestCase\nfrom .models import CharFieldModel, IntegerArrayModel\n\n\n@skipUnlessDBFeature('has_brin_index_support')\nclass BrinIndexTests(PostgreSQLTestCase):\n\n def test_repr(self):\n index = BrinIndex(fields=['title'], pages_per_range=4)\n another_index = BrinIndex(fields=['title'])\n self.assertEqual(repr(index), \"\")\n self.assertEqual(repr(another_index), \"\")\n\n def test_not_eq(self):\n index = BrinIndex(fields=['title'])\n index_with_page_range = BrinIndex(fields=['title'], pages_per_range=16)\n self.assertNotEqual(index, index_with_page_range)\n\n def test_deconstruction(self):\n index = BrinIndex(fields=['title'], name='test_title_brin')\n path, args, kwargs = index.deconstruct()\n self.assertEqual(path, 'django.contrib.postgres.indexes.BrinIndex')\n self.assertEqual(args, ())\n self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_brin', 'pages_per_range': None})\n\n def test_deconstruction_with_pages_per_range(self):\n index = BrinIndex(fields=['title'], name='test_title_brin', pages_per_range=16)\n path, args, kwargs = index.deconstruct()\n self.assertEqual(path, 'django.contrib.postgres.indexes.BrinIndex')\n self.assertEqual(args, ())\n self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_brin', 'pages_per_range': 16})\n\n def test_invalid_pages_per_range(self):\n with self.assertRaisesMessage(ValueError, 'pages_per_range must be None or a positive integer'):\n BrinIndex(fields=['title'], name='test_title_brin', pages_per_range=0)\n\n\nclass GinIndexTests(PostgreSQLTestCase):\n\n def test_repr(self):\n index = GinIndex(fields=['title'])\n self.assertEqual(repr(index), \"\")\n\n def test_eq(self):\n index = GinIndex(fields=['title'])\n same_index = GinIndex(fields=['title'])\n another_index = GinIndex(fields=['author'])\n self.assertEqual(index, same_index)\n self.assertNotEqual(index, another_index)\n\n def test_name_auto_generation(self):\n index = GinIndex(fields=['field'])\n index.set_name_with_model(IntegerArrayModel)\n self.assertEqual(index.name, 'postgres_te_field_def2f8_gin')\n\n def test_deconstruction(self):\n index = GinIndex(fields=['title'], name='test_title_gin')\n path, args, kwargs = index.deconstruct()\n self.assertEqual(path, 'django.contrib.postgres.indexes.GinIndex')\n self.assertEqual(args, ())\n self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_gin'})\n\n\nclass SchemaTests(PostgreSQLTestCase):\n\n def get_constraints(self, table):\n \"\"\"\n Get the indexes on the table using a new cursor.\n \"\"\"\n with connection.cursor() as cursor:\n return connection.introspection.get_constraints(cursor, table)\n\n def test_gin_index(self):\n # Ensure the table is there and doesn't have an index.\n self.assertNotIn('field', self.get_constraints(IntegerArrayModel._meta.db_table))\n # Add the index\n index_name = 'integer_array_model_field_gin'\n index = GinIndex(fields=['field'], name=index_name)\n with connection.schema_editor() as editor:\n editor.add_index(IntegerArrayModel, index)\n constraints = self.get_constraints(IntegerArrayModel._meta.db_table)\n # Check gin index was added\n self.assertEqual(constraints[index_name]['type'], 'gin')\n # Drop the index\n with connection.schema_editor() as editor:\n editor.remove_index(IntegerArrayModel, index)\n self.assertNotIn(index_name, self.get_constraints(IntegerArrayModel._meta.db_table))\n\n @skipUnlessDBFeature('has_brin_index_support')\n def test_brin_index(self):\n index_name = 'char_field_model_field_brin'\n index = BrinIndex(fields=['field'], name=index_name, pages_per_range=4)\n with connection.schema_editor() as editor:\n editor.add_index(CharFieldModel, index)\n constraints = self.get_constraints(CharFieldModel._meta.db_table)\n self.assertEqual(constraints[index_name]['type'], 'brin')\n self.assertEqual(constraints[index_name]['options'], ['pages_per_range=4'])\n with connection.schema_editor() as editor:\n editor.remove_index(CharFieldModel, index)\n self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":51,"cells":{"file_path":{"kind":"string","value":"django/db/backends/postgresql_psycopg2/__init__.py"},"num_changed_lines":{"kind":"number","value":9,"string":"9"},"code":{"kind":"string","value":"import warnings\n\nfrom django.utils.deprecation import RemovedInDjango30Warning\n\nwarnings.warn(\n \"The django.db.backends.postgresql_psycopg2 module is deprecated in \"\n \"favor of django.db.backends.postgresql.\",\n RemovedInDjango30Warning, stacklevel=2\n)\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":52,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py"},"num_changed_lines":{"kind":"number","value":45,"string":"45"},"code":{"kind":"string","value":"from django.test import SimpleTestCase\nfrom django.utils import translation\n\nfrom ...utils import setup\n\n\nclass GetLanguageInfoListTests(SimpleTestCase):\n libraries = {\n 'custom': 'template_tests.templatetags.custom',\n 'i18n': 'django.templatetags.i18n',\n }\n\n @setup({'i18n30': '{% load i18n %}'\n '{% get_language_info_list for langcodes as langs %}'\n '{% for l in langs %}{{ l.code }}: {{ l.name }}/'\n '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'})\n def test_i18n30(self):\n output = self.engine.render_to_string('i18n30', {'langcodes': ['it', 'no']})\n self.assertEqual(output, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; ')\n\n @setup({'i18n31': '{% load i18n %}'\n '{% get_language_info_list for langcodes as langs %}'\n '{% for l in langs %}{{ l.code }}: {{ l.name }}/'\n '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'})\n def test_i18n31(self):\n output = self.engine.render_to_string('i18n31', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))})\n self.assertEqual(\n output,\n 'sl: Slovenian/Sloven\\u0161\\u010dina bidi=False; '\n 'fa: Persian/\\u0641\\u0627\\u0631\\u0633\\u06cc bidi=True; '\n )\n\n @setup({'i18n38_2': '{% load i18n custom %}'\n '{% get_language_info_list for langcodes|noop:\"x y\" as langs %}'\n '{% for l in langs %}{{ l.code }}: {{ l.name }}/'\n '{{ l.name_local }}/{{ l.name_translated }} '\n 'bidi={{ l.bidi }}; {% endfor %}'})\n def test_i18n38_2(self):\n with translation.override('cs'):\n output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'fr']})\n self.assertEqual(\n output,\n 'it: Italian/italiano/italsky bidi=False; '\n 'fr: French/français/francouzsky bidi=False; '\n )\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":53,"cells":{"file_path":{"kind":"string","value":"django/contrib/postgres/indexes.py"},"num_changed_lines":{"kind":"number","value":34,"string":"34"},"code":{"kind":"string","value":"from django.db.models import Index\n\n__all__ = ['BrinIndex', 'GinIndex']\n\n\nclass BrinIndex(Index):\n suffix = 'brin'\n\n def __init__(self, fields=[], name=None, pages_per_range=None):\n if pages_per_range is not None and pages_per_range <= 0:\n raise ValueError('pages_per_range must be None or a positive integer')\n self.pages_per_range = pages_per_range\n super().__init__(fields, name)\n\n def __repr__(self):\n if self.pages_per_range is not None:\n return '<%(name)s: fields=%(fields)s, pages_per_range=%(pages_per_range)s>' % {\n 'name': self.__class__.__name__,\n 'fields': \"'{}'\".format(', '.join(self.fields)),\n 'pages_per_range': self.pages_per_range,\n }\n else:\n return super().__repr__()\n\n def deconstruct(self):\n path, args, kwargs = super().deconstruct()\n kwargs['pages_per_range'] = self.pages_per_range\n return path, args, kwargs\n\n def get_sql_create_template_values(self, model, schema_editor, using):\n parameters = super().get_sql_create_template_values(model, schema_editor, using=' USING brin')\n if self.pages_per_range is not None:\n parameters['extra'] = ' WITH (pages_per_range={})'.format(\n schema_editor.quote_value(self.pages_per_range)) + parameters['extra']\n return parameters\n\n\nclass GinIndex(Index):\n suffix = 'gin'\n\n def create_sql(self, model, schema_editor):\n return super().create_sql(model, schema_editor, using=' USING gin')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":54,"cells":{"file_path":{"kind":"string","value":"tests/backends/test_mysql.py"},"num_changed_lines":{"kind":"number","value":46,"string":"46"},"code":{"kind":"string","value":"import unittest\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import connection\nfrom django.test import TestCase, override_settings\n\n\n@override_settings(DEBUG=True)\n@unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific test.')\nclass MySQLTests(TestCase):\n\n @staticmethod\n def get_isolation_level(connection):\n with connection.cursor() as cursor:\n cursor.execute(\"SELECT @@session.tx_isolation\")\n return cursor.fetchone()[0]\n\n def test_auto_is_null_auto_config(self):\n query = 'set sql_auto_is_null = 0'\n connection.init_connection_state()\n last_query = connection.queries[-1]['sql'].lower()\n if connection.features.is_sql_auto_is_null_enabled:\n self.assertIn(query, last_query)\n else:\n self.assertNotIn(query, last_query)\n\n def test_connect_isolation_level(self):\n read_committed = 'read committed'\n repeatable_read = 'repeatable read'\n isolation_values = {\n level: level.replace(' ', '-').upper()\n for level in (read_committed, repeatable_read)\n }\n configured_level = connection.isolation_level or isolation_values[repeatable_read]\n configured_level = configured_level.upper()\n other_level = read_committed if configured_level != isolation_values[read_committed] else repeatable_read\n\n self.assertEqual(self.get_isolation_level(connection), configured_level)\n\n new_connection = connection.copy()\n new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level\n try:\n self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level])\n finally:\n new_connection.close()\n\n # Upper case values are also accepted in 'isolation_level'.\n new_connection = connection.copy()\n new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level.upper()\n try:\n self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level])\n finally:\n new_connection.close()\n\n def test_isolation_level_validation(self):\n new_connection = connection.copy()\n new_connection.settings_dict['OPTIONS']['isolation_level'] = 'xxx'\n msg = (\n \"Invalid transaction isolation level 'xxx' specified.\\n\"\n \"Use one of 'read committed', 'read uncommitted', \"\n \"'repeatable read', 'serializable', or None.\"\n )\n with self.assertRaisesMessage(ImproperlyConfigured, msg):\n new_connection.cursor()\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":55,"cells":{"file_path":{"kind":"string","value":"tests/auth_tests/client.py"},"num_changed_lines":{"kind":"number","value":41,"string":"41"},"code":{"kind":"string","value":"import re\n\nfrom django.contrib.auth.views import (\n INTERNAL_RESET_SESSION_TOKEN, INTERNAL_RESET_URL_TOKEN,\n)\nfrom django.test import Client\n\n\ndef extract_token_from_url(url):\n token_search = re.search(r'/reset/.*/(.+?)/', url)\n if token_search:\n return token_search.group(1)\n\n\nclass PasswordResetConfirmClient(Client):\n \"\"\"\n This client eases testing the password reset flow by emulating the\n PasswordResetConfirmView's redirect and saving of the reset token in the\n user's session. This request puts 'my-token' in the session and redirects\n to '/reset/bla/set-password/':\n\n >>> client = PasswordResetConfirmClient()\n >>> client.get('/reset/bla/my-token/')\n \"\"\"\n def _get_password_reset_confirm_redirect_url(self, url):\n token = extract_token_from_url(url)\n if not token:\n return url\n # Add the token to the session\n session = self.session\n session[INTERNAL_RESET_SESSION_TOKEN] = token\n session.save()\n return url.replace(token, INTERNAL_RESET_URL_TOKEN)\n\n def get(self, path, *args, **kwargs):\n redirect_url = self._get_password_reset_confirm_redirect_url(path)\n return super().get(redirect_url, *args, **kwargs)\n\n def post(self, path, *args, **kwargs):\n redirect_url = self._get_password_reset_confirm_redirect_url(path)\n return super().post(redirect_url, *args, **kwargs)\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":56,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/test_filters.py"},"num_changed_lines":{"kind":"number","value":47,"string":"47"},"code":{"kind":"string","value":"from django.test import SimpleTestCase\nfrom django.utils import translation\n\nfrom ...utils import setup\n\n\nclass I18nFiltersTests(SimpleTestCase):\n libraries = {\n 'custom': 'template_tests.templatetags.custom',\n 'i18n': 'django.templatetags.i18n',\n }\n\n @setup({'i18n32': '{% load i18n %}{{ \"hu\"|language_name }} '\n '{{ \"hu\"|language_name_local }} {{ \"hu\"|language_bidi }} '\n '{{ \"hu\"|language_name_translated }}'})\n def test_i18n32(self):\n output = self.engine.render_to_string('i18n32')\n self.assertEqual(output, 'Hungarian Magyar False Hungarian')\n\n with translation.override('cs'):\n output = self.engine.render_to_string('i18n32')\n self.assertEqual(output, 'Hungarian Magyar False maďarsky')\n\n @setup({'i18n33': '{% load i18n %}'\n '{{ langcode|language_name }} {{ langcode|language_name_local }} '\n '{{ langcode|language_bidi }} {{ langcode|language_name_translated }}'})\n def test_i18n33(self):\n output = self.engine.render_to_string('i18n33', {'langcode': 'nl'})\n self.assertEqual(output, 'Dutch Nederlands False Dutch')\n\n with translation.override('cs'):\n output = self.engine.render_to_string('i18n33', {'langcode': 'nl'})\n self.assertEqual(output, 'Dutch Nederlands False nizozemsky')\n\n @setup({'i18n38_2': '{% load i18n custom %}'\n '{% get_language_info_list for langcodes|noop:\"x y\" as langs %}'\n '{% for l in langs %}{{ l.code }}: {{ l.name }}/'\n '{{ l.name_local }}/{{ l.name_translated }} '\n 'bidi={{ l.bidi }}; {% endfor %}'})\n def test_i18n38_2(self):\n with translation.override('cs'):\n output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'fr']})\n self.assertEqual(\n output,\n 'it: Italian/italiano/italsky bidi=False; '\n 'fr: French/français/francouzsky bidi=False; '\n )\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":57,"cells":{"file_path":{"kind":"string","value":"tests/template_tests/syntax_tests/i18n/test_get_language_info.py"},"num_changed_lines":{"kind":"number","value":36,"string":"36"},"code":{"kind":"string","value":"from django.test import SimpleTestCase\nfrom django.utils import translation\n\nfrom ...utils import setup\n\n\nclass I18nGetLanguageInfoTagTests(SimpleTestCase):\n libraries = {\n 'custom': 'template_tests.templatetags.custom',\n 'i18n': 'django.templatetags.i18n',\n }\n\n # retrieving language information\n @setup({'i18n28_2': '{% load i18n %}'\n '{% get_language_info for \"de\" as l %}'\n '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'})\n def test_i18n28_2(self):\n output = self.engine.render_to_string('i18n28_2')\n self.assertEqual(output, 'de: German/Deutsch bidi=False')\n\n @setup({'i18n29': '{% load i18n %}'\n '{% get_language_info for LANGUAGE_CODE as l %}'\n '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'})\n def test_i18n29(self):\n output = self.engine.render_to_string('i18n29', {'LANGUAGE_CODE': 'fi'})\n self.assertEqual(output, 'fi: Finnish/suomi bidi=False')\n\n # Test whitespace in filter arguments\n @setup({'i18n38': '{% load i18n custom %}'\n '{% get_language_info for \"de\"|noop:\"x y\" as l %}'\n '{{ l.code }}: {{ l.name }}/{{ l.name_local }}/'\n '{{ l.name_translated }} bidi={{ l.bidi }}'})\n def test_i18n38(self):\n with translation.override('cs'):\n output = self.engine.render_to_string('i18n38')\n self.assertEqual(output, 'de: German/Deutsch/německy bidi=False')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":58,"cells":{"file_path":{"kind":"string","value":"django/contrib/gis/static/gis/css/ol3.css"},"num_changed_lines":{"kind":"number","value":31,"string":"31"},"code":{"kind":"string","value":".switch-type {\n background-repeat: no-repeat;\n cursor: pointer;\n top: 0.5em;\n width: 22px;\n height: 20px;\n}\n\n.type-Point {\n background-image: url(\"../img/draw_point_off.svg\");\n right: 5px;\n}\n.type-Point.type-active {\n background-image: url(\"../img/draw_point_on.svg\");\n}\n\n.type-LineString {\n background-image: url(\"../img/draw_line_off.svg\");\n right: 30px;\n}\n.type-LineString.type-active {\n background-image: url(\"../img/draw_line_on.svg\");\n}\n\n.type-Polygon {\n background-image: url(\"../img/draw_polygon_off.svg\");\n right: 55px;\n}\n.type-Polygon.type-active {\n background-image: url(\"../img/draw_polygon_on.svg\");\n}\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":59,"cells":{"file_path":{"kind":"string","value":"tests/auth_tests/test_templates.py"},"num_changed_lines":{"kind":"number","value":28,"string":"28"},"code":{"kind":"string","value":"from django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.tokens import PasswordResetTokenGenerator\nfrom django.contrib.auth.views import (\n PasswordChangeDoneView, PasswordChangeView, PasswordResetCompleteView,\n PasswordResetDoneView, PasswordResetView,\n)\nfrom django.test import RequestFactory, TestCase, override_settings\nfrom django.urls import reverse\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode\n\nfrom .client import PasswordResetConfirmClient\n\n\n@override_settings(ROOT_URLCONF='auth_tests.urls')\nclass AuthTemplateTests(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n rf = RequestFactory()\n user = User.objects.create_user('jsmith', 'jsmith@example.com', 'pass')\n user = authenticate(username=user.username, password='pass')\n request = rf.get('/somepath/')\n request.user = user\n cls.user, cls.request = user, request\n\n def test_PasswordResetView(self):\n response = PasswordResetView.as_view(success_url='dummy/')(self.request)\n self.assertContains(response, 'Password reset')\n self.assertContains(response, '

Password reset

')\n\n def test_PasswordResetDoneView(self):\n response = PasswordResetDoneView.as_view()(self.request)\n self.assertContains(response, 'Password reset sent')\n self.assertContains(response, '

Password reset sent

')\n\n def test_PasswordResetConfirmView_invalid_token(self):\n # PasswordResetConfirmView invalid token\n client = PasswordResetConfirmClient()\n url = reverse('password_reset_confirm', kwargs={'uidb64': 'Bad', 'token': 'Bad-Token'})\n response = client.get(url)\n self.assertContains(response, 'Password reset unsuccessful')\n self.assertContains(response, '

Password reset unsuccessful

')\n\n def test_PasswordResetConfirmView_valid_token(self):\n # PasswordResetConfirmView valid token\n client = PasswordResetConfirmClient()\n default_token_generator = PasswordResetTokenGenerator()\n token = default_token_generator.make_token(self.user)\n uidb64 = urlsafe_base64_encode(force_bytes(self.user.pk)).decode()\n url = reverse('password_reset_confirm', kwargs={'uidb64': uidb64, 'token': token})\n response = client.get(url)\n self.assertContains(response, 'Enter new password')\n self.assertContains(response, '

Enter new password

')\n\n def test_PasswordResetCompleteView(self):\n response = PasswordResetCompleteView.as_view()(self.request)\n self.assertContains(response, 'Password reset complete')\n self.assertContains(response, '

Password reset complete

')\n\n def test_PasswordResetChangeView(self):\n response = PasswordChangeView.as_view(success_url='dummy/')(self.request)\n self.assertContains(response, 'Password change')\n self.assertContains(response, '

Password change

')\n\n def test_PasswordChangeDoneView(self):\n response = PasswordChangeDoneView.as_view()(self.request)\n self.assertContains(response, 'Password change successful')\n self.assertContains(response, '

Password change successful

')\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":60,"cells":{"file_path":{"kind":"string","value":"tests/messages_tests/test_api.py"},"num_changed_lines":{"kind":"number","value":31,"string":"31"},"code":{"kind":"string","value":"from django.contrib import messages\nfrom django.test import RequestFactory, SimpleTestCase\n\n\nclass DummyStorage:\n \"\"\"\n dummy message-store to test the api methods\n \"\"\"\n\n def __init__(self):\n self.store = []\n\n def add(self, level, message, extra_tags=''):\n self.store.append(message)\n\n\nclass ApiTests(SimpleTestCase):\n def setUp(self):\n self.rf = RequestFactory()\n self.request = self.rf.request()\n self.storage = DummyStorage()\n\n def test_ok(self):\n msg = 'some message'\n self.request._messages = self.storage\n messages.add_message(self.request, messages.DEBUG, msg)\n self.assertIn(msg, self.storage.store)\n\n def test_request_is_none(self):\n msg = \"add_message() argument must be an HttpRequest object, not 'NoneType'.\"\n self.request._messages = self.storage\n with self.assertRaisesMessage(TypeError, msg):\n messages.add_message(None, messages.DEBUG, 'some message')\n self.assertEqual(self.storage.store, [])\n\n def test_middleware_missing(self):\n msg = 'You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware'\n with self.assertRaisesMessage(messages.MessageFailure, msg):\n messages.add_message(self.request, messages.DEBUG, 'some message')\n self.assertEqual(self.storage.store, [])\n\n def test_middleware_missing_silently(self):\n messages.add_message(self.request, messages.DEBUG, 'some message', fail_silently=True)\n self.assertEqual(self.storage.store, [])\n\n\nclass CustomRequest:\n def __init__(self, request):\n self._request = request\n\n def __getattribute__(self, attr):\n try:\n return super().__getattribute__(attr)\n except AttributeError:\n return getattr(self._request, attr)\n\n\nclass CustomRequestApiTests(ApiTests):\n \"\"\"\n add_message() should use ducktyping to allow request wrappers such as the\n one in Django REST framework.\n \"\"\"\n def setUp(self):\n super().setUp()\n self.request = CustomRequest(self.request)\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":61,"cells":{"file_path":{"kind":"string","value":"tests/shell/tests.py"},"num_changed_lines":{"kind":"number","value":24,"string":"24"},"code":{"kind":"string","value":"import sys\nimport unittest\nfrom unittest import mock\n\nfrom django import __version__\nfrom django.core.management import CommandError, call_command\nfrom django.test import SimpleTestCase\nfrom django.test.utils import captured_stdin, captured_stdout, patch_logger\n\n\nclass ShellCommandTestCase(SimpleTestCase):\n\n def test_command_option(self):\n with patch_logger('test', 'info') as logger:\n call_command(\n 'shell',\n command=(\n 'import django; from logging import getLogger; '\n 'getLogger(\"test\").info(django.__version__)'\n ),\n )\n self.assertEqual(len(logger), 1)\n self.assertEqual(logger[0], __version__)\n\n @unittest.skipIf(sys.platform == 'win32', \"Windows select() doesn't support file descriptors.\")\n @mock.patch('django.core.management.commands.shell.select')\n def test_stdin_read(self, select):\n with captured_stdin() as stdin, captured_stdout() as stdout:\n stdin.write('print(100)\\n')\n stdin.seek(0)\n call_command('shell')\n self.assertEqual(stdout.getvalue().strip(), '100')\n\n @mock.patch('django.core.management.commands.shell.select.select') # [1]\n @mock.patch.dict('sys.modules', {'IPython': None})\n def test_shell_with_ipython_not_installed(self, select):\n select.return_value = ([], [], [])\n with self.assertRaisesMessage(CommandError, \"Couldn't import ipython interface.\"):\n call_command('shell', interface='ipython')\n\n @mock.patch('django.core.management.commands.shell.select.select') # [1]\n @mock.patch.dict('sys.modules', {'bpython': None})\n def test_shell_with_bpython_not_installed(self, select):\n select.return_value = ([], [], [])\n with self.assertRaisesMessage(CommandError, \"Couldn't import bpython interface.\"):\n call_command('shell', interface='bpython')\n\n # [1] Patch select to prevent tests failing when when the test suite is run\n # in parallel mode. The tests are run in a subprocess and the subprocess's\n # stdin is closed and replaced by /dev/null. Reading from /dev/null always\n # returns EOF and so select always shows that sys.stdin is ready to read.\n # This causes problems because of the call to select.select() towards the\n # end of shell's handle() method.\n"},"repo_name":{"kind":"string","value":"django_django"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"e34f4e6f8735a6ad102fda096aa99cbb5600761e"}}},{"rowIdx":62,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/main/java/org/apache/spark/network/crypto/AuthEngine.java"},"num_changed_lines":{"kind":"number","value":284,"string":"284"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.security.GeneralSecurityException;\nimport java.util.Arrays;\nimport java.util.Properties;\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.ShortBufferException;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.PBEKeySpec;\nimport javax.crypto.spec.SecretKeySpec;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Preconditions;\nimport com.google.common.primitives.Bytes;\nimport org.apache.commons.crypto.cipher.CryptoCipher;\nimport org.apache.commons.crypto.cipher.CryptoCipherFactory;\nimport org.apache.commons.crypto.random.CryptoRandom;\nimport org.apache.commons.crypto.random.CryptoRandomFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport org.apache.spark.network.util.TransportConf;\n\n/**\n * A helper class for abstracting authentication and key negotiation details. This is used by\n * both client and server sides, since the operations are basically the same.\n */\nclass AuthEngine implements Closeable {\n\n private static final Logger LOG = LoggerFactory.getLogger(AuthEngine.class);\n private static final BigInteger ONE = new BigInteger(new byte[] { 0x1 });\n\n private final byte[] appId;\n private final char[] secret;\n private final TransportConf conf;\n private final Properties cryptoConf;\n private final CryptoRandom random;\n\n private byte[] authNonce;\n\n @VisibleForTesting\n byte[] challenge;\n\n private TransportCipher sessionCipher;\n private CryptoCipher encryptor;\n private CryptoCipher decryptor;\n\n AuthEngine(String appId, String secret, TransportConf conf) throws GeneralSecurityException {\n this.appId = appId.getBytes(UTF_8);\n this.conf = conf;\n this.cryptoConf = conf.cryptoConf();\n this.secret = secret.toCharArray();\n this.random = CryptoRandomFactory.getCryptoRandom(cryptoConf);\n }\n\n /**\n * Create the client challenge.\n *\n * @return A challenge to be sent the remote side.\n */\n ClientChallenge challenge() throws GeneralSecurityException, IOException {\n this.authNonce = randomBytes(conf.encryptionKeyLength() / Byte.SIZE);\n SecretKeySpec authKey = generateKey(conf.keyFactoryAlgorithm(), conf.keyFactoryIterations(),\n authNonce, conf.encryptionKeyLength());\n initializeForAuth(conf.cipherTransformation(), authNonce, authKey);\n\n this.challenge = randomBytes(conf.encryptionKeyLength() / Byte.SIZE);\n return new ClientChallenge(new String(appId, UTF_8),\n conf.keyFactoryAlgorithm(),\n conf.keyFactoryIterations(),\n conf.cipherTransformation(),\n conf.encryptionKeyLength(),\n authNonce,\n challenge(appId, authNonce, challenge));\n }\n\n /**\n * Validates the client challenge, and create the encryption backend for the channel from the\n * parameters sent by the client.\n *\n * @param clientChallenge The challenge from the client.\n * @return A response to be sent to the client.\n */\n ServerResponse respond(ClientChallenge clientChallenge)\n throws GeneralSecurityException, IOException {\n\n SecretKeySpec authKey = generateKey(clientChallenge.kdf, clientChallenge.iterations,\n clientChallenge.nonce, clientChallenge.keyLength);\n initializeForAuth(clientChallenge.cipher, clientChallenge.nonce, authKey);\n\n byte[] challenge = validateChallenge(clientChallenge.nonce, clientChallenge.challenge);\n byte[] response = challenge(appId, clientChallenge.nonce, rawResponse(challenge));\n byte[] sessionNonce = randomBytes(conf.encryptionKeyLength() / Byte.SIZE);\n byte[] inputIv = randomBytes(conf.ivLength());\n byte[] outputIv = randomBytes(conf.ivLength());\n\n SecretKeySpec sessionKey = generateKey(clientChallenge.kdf, clientChallenge.iterations,\n sessionNonce, clientChallenge.keyLength);\n this.sessionCipher = new TransportCipher(cryptoConf, clientChallenge.cipher, sessionKey,\n inputIv, outputIv);\n\n // Note the IVs are swapped in the response.\n return new ServerResponse(response, encrypt(sessionNonce), encrypt(outputIv), encrypt(inputIv));\n }\n\n /**\n * Validates the server response and initializes the cipher to use for the session.\n *\n * @param serverResponse The response from the server.\n */\n void validate(ServerResponse serverResponse) throws GeneralSecurityException {\n byte[] response = validateChallenge(authNonce, serverResponse.response);\n\n byte[] expected = rawResponse(challenge);\n Preconditions.checkArgument(Arrays.equals(expected, response));\n\n byte[] nonce = decrypt(serverResponse.nonce);\n byte[] inputIv = decrypt(serverResponse.inputIv);\n byte[] outputIv = decrypt(serverResponse.outputIv);\n\n SecretKeySpec sessionKey = generateKey(conf.keyFactoryAlgorithm(), conf.keyFactoryIterations(),\n nonce, conf.encryptionKeyLength());\n this.sessionCipher = new TransportCipher(cryptoConf, conf.cipherTransformation(), sessionKey,\n inputIv, outputIv);\n }\n\n TransportCipher sessionCipher() {\n Preconditions.checkState(sessionCipher != null);\n return sessionCipher;\n }\n\n @Override\n public void close() throws IOException {\n // Close ciphers (by calling \"doFinal()\" with dummy data) and the random instance so that\n // internal state is cleaned up. Error handling here is just for paranoia, and not meant to\n // accurately report the errors when they happen.\n RuntimeException error = null;\n byte[] dummy = new byte[8];\n try {\n doCipherOp(encryptor, dummy, true);\n } catch (Exception e) {\n error = new RuntimeException(e);\n }\n try {\n doCipherOp(decryptor, dummy, true);\n } catch (Exception e) {\n error = new RuntimeException(e);\n }\n random.close();\n\n if (error != null) {\n throw error;\n }\n }\n\n @VisibleForTesting\n byte[] challenge(byte[] appId, byte[] nonce, byte[] challenge) throws GeneralSecurityException {\n return encrypt(Bytes.concat(appId, nonce, challenge));\n }\n\n @VisibleForTesting\n byte[] rawResponse(byte[] challenge) {\n BigInteger orig = new BigInteger(challenge);\n BigInteger response = orig.add(ONE);\n return response.toByteArray();\n }\n\n private byte[] decrypt(byte[] in) throws GeneralSecurityException {\n return doCipherOp(decryptor, in, false);\n }\n\n private byte[] encrypt(byte[] in) throws GeneralSecurityException {\n return doCipherOp(encryptor, in, false);\n }\n\n private void initializeForAuth(String cipher, byte[] nonce, SecretKeySpec key)\n throws GeneralSecurityException {\n\n // commons-crypto currently only supports ciphers that require an initial vector; so\n // create a dummy vector so that we can initialize the ciphers. In the future, if\n // different ciphers are supported, this will have to be configurable somehow.\n byte[] iv = new byte[conf.ivLength()];\n System.arraycopy(nonce, 0, iv, 0, Math.min(nonce.length, iv.length));\n\n encryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf);\n encryptor.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));\n\n decryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf);\n decryptor.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));\n }\n\n /**\n * Validates an encrypted challenge as defined in the protocol, and returns the byte array\n * that corresponds to the actual challenge data.\n */\n private byte[] validateChallenge(byte[] nonce, byte[] encryptedChallenge)\n throws GeneralSecurityException {\n\n byte[] challenge = decrypt(encryptedChallenge);\n checkSubArray(appId, challenge, 0);\n checkSubArray(nonce, challenge, appId.length);\n return Arrays.copyOfRange(challenge, appId.length + nonce.length, challenge.length);\n }\n\n private SecretKeySpec generateKey(String kdf, int iterations, byte[] salt, int keyLength)\n throws GeneralSecurityException {\n\n SecretKeyFactory factory = SecretKeyFactory.getInstance(kdf);\n PBEKeySpec spec = new PBEKeySpec(secret, salt, iterations, keyLength);\n\n long start = System.nanoTime();\n SecretKey key = factory.generateSecret(spec);\n long end = System.nanoTime();\n\n LOG.debug(\"Generated key with {} iterations in {} us.\", conf.keyFactoryIterations(),\n (end - start) / 1000);\n\n return new SecretKeySpec(key.getEncoded(), conf.keyAlgorithm());\n }\n\n private byte[] doCipherOp(CryptoCipher cipher, byte[] in, boolean isFinal)\n throws GeneralSecurityException {\n\n Preconditions.checkState(cipher != null);\n\n int scale = 1;\n while (true) {\n int size = in.length * scale;\n byte[] buffer = new byte[size];\n try {\n int outSize = isFinal ? cipher.doFinal(in, 0, in.length, buffer, 0)\n : cipher.update(in, 0, in.length, buffer, 0);\n if (outSize != buffer.length) {\n byte[] output = new byte[outSize];\n System.arraycopy(buffer, 0, output, 0, output.length);\n return output;\n } else {\n return buffer;\n }\n } catch (ShortBufferException e) {\n // Try again with a bigger buffer.\n scale *= 2;\n }\n }\n }\n\n private byte[] randomBytes(int count) {\n byte[] bytes = new byte[count];\n random.nextBytes(bytes);\n return bytes;\n }\n\n /** Checks that the \"test\" array is in the data array starting at the given offset. */\n private void checkSubArray(byte[] test, byte[] data, int offset) {\n Preconditions.checkArgument(data.length >= test.length + offset);\n for (int i = 0; i < test.length; i++) {\n Preconditions.checkArgument(test[i] == data[i + offset]);\n }\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":63,"cells":{"file_path":{"kind":"string","value":"examples/src/main/java/org/apache/spark/examples/sql/JavaUserDefinedTypedAggregation.java"},"num_changed_lines":{"kind":"number","value":160,"string":"160"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.spark.examples.sql;\n\n// $example on:typed_custom_aggregation$\nimport java.io.Serializable;\n\nimport org.apache.spark.sql.Dataset;\nimport org.apache.spark.sql.Encoder;\nimport org.apache.spark.sql.Encoders;\nimport org.apache.spark.sql.SparkSession;\nimport org.apache.spark.sql.TypedColumn;\nimport org.apache.spark.sql.expressions.Aggregator;\n// $example off:typed_custom_aggregation$\n\npublic class JavaUserDefinedTypedAggregation {\n\n // $example on:typed_custom_aggregation$\n public static class Employee implements Serializable {\n private String name;\n private long salary;\n\n // Constructors, getters, setters...\n // $example off:typed_custom_aggregation$\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public long getSalary() {\n return salary;\n }\n\n public void setSalary(long salary) {\n this.salary = salary;\n }\n // $example on:typed_custom_aggregation$\n }\n\n public static class Average implements Serializable {\n private long sum;\n private long count;\n\n // Constructors, getters, setters...\n // $example off:typed_custom_aggregation$\n public Average() {\n }\n\n public Average(long sum, long count) {\n this.sum = sum;\n this.count = count;\n }\n\n public long getSum() {\n return sum;\n }\n\n public void setSum(long sum) {\n this.sum = sum;\n }\n\n public long getCount() {\n return count;\n }\n\n public void setCount(long count) {\n this.count = count;\n }\n // $example on:typed_custom_aggregation$\n }\n\n public static class MyAverage extends Aggregator {\n // A zero value for this aggregation. Should satisfy the property that any b + zero = b\n public Average zero() {\n return new Average(0L, 0L);\n }\n // Combine two values to produce a new value. For performance, the function may modify `buffer`\n // and return it instead of constructing a new object\n public Average reduce(Average buffer, Employee employee) {\n long newSum = buffer.getSum() + employee.getSalary();\n long newCount = buffer.getCount() + 1;\n buffer.setSum(newSum);\n buffer.setCount(newCount);\n return buffer;\n }\n // Merge two intermediate values\n public Average merge(Average b1, Average b2) {\n long mergedSum = b1.getSum() + b2.getSum();\n long mergedCount = b1.getCount() + b2.getCount();\n b1.setSum(mergedSum);\n b1.setCount(mergedCount);\n return b1;\n }\n // Transform the output of the reduction\n public Double finish(Average reduction) {\n return ((double) reduction.getSum()) / reduction.getCount();\n }\n // Specifies the Encoder for the intermediate value type\n public Encoder bufferEncoder() {\n return Encoders.bean(Average.class);\n }\n // Specifies the Encoder for the final output value type\n public Encoder outputEncoder() {\n return Encoders.DOUBLE();\n }\n }\n // $example off:typed_custom_aggregation$\n\n public static void main(String[] args) {\n SparkSession spark = SparkSession\n .builder()\n .appName(\"Java Spark SQL user-defined Datasets aggregation example\")\n .getOrCreate();\n\n // $example on:typed_custom_aggregation$\n Encoder employeeEncoder = Encoders.bean(Employee.class);\n String path = \"examples/src/main/resources/employees.json\";\n Dataset ds = spark.read().json(path).as(employeeEncoder);\n ds.show();\n // +-------+------+\n // | name|salary|\n // +-------+------+\n // |Michael| 3000|\n // | Andy| 4500|\n // | Justin| 3500|\n // | Berta| 4000|\n // +-------+------+\n\n MyAverage myAverage = new MyAverage();\n // Convert the function to a `TypedColumn` and give it a name\n TypedColumn averageSalary = myAverage.toColumn().name(\"average_salary\");\n Dataset result = ds.select(averageSalary);\n result.show();\n // +--------------+\n // |average_salary|\n // +--------------+\n // | 3750.0|\n // +--------------+\n // $example off:typed_custom_aggregation$\n spark.stop();\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":64,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/test/java/org/apache/spark/network/crypto/AuthIntegrationSuite.java"},"num_changed_lines":{"kind":"number","value":213,"string":"213"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.nio.ByteBuffer;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\nimport io.netty.channel.Channel;\nimport org.junit.After;\nimport org.junit.Test;\nimport static org.junit.Assert.*;\nimport static org.mockito.Mockito.*;\n\nimport org.apache.spark.network.TestUtils;\nimport org.apache.spark.network.TransportContext;\nimport org.apache.spark.network.client.RpcResponseCallback;\nimport org.apache.spark.network.client.TransportClient;\nimport org.apache.spark.network.client.TransportClientBootstrap;\nimport org.apache.spark.network.sasl.SaslRpcHandler;\nimport org.apache.spark.network.sasl.SaslServerBootstrap;\nimport org.apache.spark.network.sasl.SecretKeyHolder;\nimport org.apache.spark.network.server.RpcHandler;\nimport org.apache.spark.network.server.StreamManager;\nimport org.apache.spark.network.server.TransportServer;\nimport org.apache.spark.network.server.TransportServerBootstrap;\nimport org.apache.spark.network.util.JavaUtils;\nimport org.apache.spark.network.util.MapConfigProvider;\nimport org.apache.spark.network.util.TransportConf;\n\npublic class AuthIntegrationSuite {\n\n private AuthTestCtx ctx;\n\n @After\n public void cleanUp() throws Exception {\n if (ctx != null) {\n ctx.close();\n }\n ctx = null;\n }\n\n @Test\n public void testNewAuth() throws Exception {\n ctx = new AuthTestCtx();\n ctx.createServer(\"secret\");\n ctx.createClient(\"secret\");\n\n ByteBuffer reply = ctx.client.sendRpcSync(JavaUtils.stringToBytes(\"Ping\"), 5000);\n assertEquals(\"Pong\", JavaUtils.bytesToString(reply));\n assertTrue(ctx.authRpcHandler.doDelegate);\n assertFalse(ctx.authRpcHandler.delegate instanceof SaslRpcHandler);\n }\n\n @Test\n public void testAuthFailure() throws Exception {\n ctx = new AuthTestCtx();\n ctx.createServer(\"server\");\n\n try {\n ctx.createClient(\"client\");\n fail(\"Should have failed to create client.\");\n } catch (Exception e) {\n assertFalse(ctx.authRpcHandler.doDelegate);\n assertFalse(ctx.serverChannel.isActive());\n }\n }\n\n @Test\n public void testSaslServerFallback() throws Exception {\n ctx = new AuthTestCtx();\n ctx.createServer(\"secret\", true);\n ctx.createClient(\"secret\", false);\n\n ByteBuffer reply = ctx.client.sendRpcSync(JavaUtils.stringToBytes(\"Ping\"), 5000);\n assertEquals(\"Pong\", JavaUtils.bytesToString(reply));\n }\n\n @Test\n public void testSaslClientFallback() throws Exception {\n ctx = new AuthTestCtx();\n ctx.createServer(\"secret\", false);\n ctx.createClient(\"secret\", true);\n\n ByteBuffer reply = ctx.client.sendRpcSync(JavaUtils.stringToBytes(\"Ping\"), 5000);\n assertEquals(\"Pong\", JavaUtils.bytesToString(reply));\n }\n\n @Test\n public void testAuthReplay() throws Exception {\n // This test covers the case where an attacker replays a challenge message sniffed from the\n // network, but doesn't know the actual secret. The server should close the connection as\n // soon as a message is sent after authentication is performed. This is emulated by removing\n // the client encryption handler after authentication.\n ctx = new AuthTestCtx();\n ctx.createServer(\"secret\");\n ctx.createClient(\"secret\");\n\n assertNotNull(ctx.client.getChannel().pipeline()\n .remove(TransportCipher.ENCRYPTION_HANDLER_NAME));\n\n try {\n ctx.client.sendRpcSync(JavaUtils.stringToBytes(\"Ping\"), 5000);\n fail(\"Should have failed unencrypted RPC.\");\n } catch (Exception e) {\n assertTrue(ctx.authRpcHandler.doDelegate);\n }\n }\n\n private class AuthTestCtx {\n\n private final String appId = \"testAppId\";\n private final TransportConf conf;\n private final TransportContext ctx;\n\n TransportClient client;\n TransportServer server;\n volatile Channel serverChannel;\n volatile AuthRpcHandler authRpcHandler;\n\n AuthTestCtx() throws Exception {\n Map testConf = ImmutableMap.of(\"spark.network.crypto.enabled\", \"true\");\n this.conf = new TransportConf(\"rpc\", new MapConfigProvider(testConf));\n\n RpcHandler rpcHandler = new RpcHandler() {\n @Override\n public void receive(\n TransportClient client,\n ByteBuffer message,\n RpcResponseCallback callback) {\n assertEquals(\"Ping\", JavaUtils.bytesToString(message));\n callback.onSuccess(JavaUtils.stringToBytes(\"Pong\"));\n }\n\n @Override\n public StreamManager getStreamManager() {\n return null;\n }\n };\n\n this.ctx = new TransportContext(conf, rpcHandler);\n }\n\n void createServer(String secret) throws Exception {\n createServer(secret, true);\n }\n\n void createServer(String secret, boolean enableAes) throws Exception {\n TransportServerBootstrap introspector = new TransportServerBootstrap() {\n @Override\n public RpcHandler doBootstrap(Channel channel, RpcHandler rpcHandler) {\n AuthTestCtx.this.serverChannel = channel;\n if (rpcHandler instanceof AuthRpcHandler) {\n AuthTestCtx.this.authRpcHandler = (AuthRpcHandler) rpcHandler;\n }\n return rpcHandler;\n }\n };\n SecretKeyHolder keyHolder = createKeyHolder(secret);\n TransportServerBootstrap auth = enableAes ? new AuthServerBootstrap(conf, keyHolder)\n : new SaslServerBootstrap(conf, keyHolder);\n this.server = ctx.createServer(Lists.newArrayList(auth, introspector));\n }\n\n void createClient(String secret) throws Exception {\n createClient(secret, true);\n }\n\n void createClient(String secret, boolean enableAes) throws Exception {\n TransportConf clientConf = enableAes ? conf\n : new TransportConf(\"rpc\", MapConfigProvider.EMPTY);\n List bootstraps = Lists.newArrayList(\n new AuthClientBootstrap(clientConf, appId, createKeyHolder(secret)));\n this.client = ctx.createClientFactory(bootstraps)\n .createClient(TestUtils.getLocalHost(), server.getPort());\n }\n\n void close() {\n if (client != null) {\n client.close();\n }\n if (server != null) {\n server.close();\n }\n }\n\n private SecretKeyHolder createKeyHolder(String secret) {\n SecretKeyHolder keyHolder = mock(SecretKeyHolder.class);\n when(keyHolder.getSaslUser(anyString())).thenReturn(appId);\n when(keyHolder.getSecretKey(anyString())).thenReturn(secret);\n return keyHolder;\n }\n\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":65,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/main/java/org/apache/spark/network/crypto/AuthRpcHandler.java"},"num_changed_lines":{"kind":"number","value":170,"string":"170"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport javax.security.sasl.Sasl;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Throwables;\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\nimport io.netty.channel.Channel;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport org.apache.spark.network.client.RpcResponseCallback;\nimport org.apache.spark.network.client.TransportClient;\nimport org.apache.spark.network.sasl.SecretKeyHolder;\nimport org.apache.spark.network.sasl.SaslRpcHandler;\nimport org.apache.spark.network.server.RpcHandler;\nimport org.apache.spark.network.server.StreamManager;\nimport org.apache.spark.network.util.JavaUtils;\nimport org.apache.spark.network.util.TransportConf;\n\n/**\n * RPC Handler which performs authentication using Spark's auth protocol before delegating to a\n * child RPC handler. If the configuration allows, this handler will delegate messages to a SASL\n * RPC handler for further authentication, to support for clients that do not support Spark's\n * protocol.\n *\n * The delegate will only receive messages if the given connection has been successfully\n * authenticated. A connection may be authenticated at most once.\n */\nclass AuthRpcHandler extends RpcHandler {\n private static final Logger LOG = LoggerFactory.getLogger(AuthRpcHandler.class);\n\n /** Transport configuration. */\n private final TransportConf conf;\n\n /** The client channel. */\n private final Channel channel;\n\n /**\n * RpcHandler we will delegate to for authenticated connections. When falling back to SASL\n * this will be replaced with the SASL RPC handler.\n */\n @VisibleForTesting\n RpcHandler delegate;\n\n /** Class which provides secret keys which are shared by server and client on a per-app basis. */\n private final SecretKeyHolder secretKeyHolder;\n\n /** Whether auth is done and future calls should be delegated. */\n @VisibleForTesting\n boolean doDelegate;\n\n AuthRpcHandler(\n TransportConf conf,\n Channel channel,\n RpcHandler delegate,\n SecretKeyHolder secretKeyHolder) {\n this.conf = conf;\n this.channel = channel;\n this.delegate = delegate;\n this.secretKeyHolder = secretKeyHolder;\n }\n\n @Override\n public void receive(TransportClient client, ByteBuffer message, RpcResponseCallback callback) {\n if (doDelegate) {\n delegate.receive(client, message, callback);\n return;\n }\n\n int position = message.position();\n int limit = message.limit();\n\n ClientChallenge challenge;\n try {\n challenge = ClientChallenge.decodeMessage(message);\n LOG.debug(\"Received new auth challenge for client {}.\", channel.remoteAddress());\n } catch (RuntimeException e) {\n if (conf.saslFallback()) {\n LOG.warn(\"Failed to parse new auth challenge, reverting to SASL for client {}.\",\n channel.remoteAddress());\n delegate = new SaslRpcHandler(conf, channel, delegate, secretKeyHolder);\n message.position(position);\n message.limit(limit);\n delegate.receive(client, message, callback);\n doDelegate = true;\n } else {\n LOG.debug(\"Unexpected challenge message from client {}, closing channel.\",\n channel.remoteAddress());\n callback.onFailure(new IllegalArgumentException(\"Unknown challenge message.\"));\n channel.close();\n }\n return;\n }\n\n // Here we have the client challenge, so perform the new auth protocol and set up the channel.\n AuthEngine engine = null;\n try {\n engine = new AuthEngine(challenge.appId, secretKeyHolder.getSecretKey(challenge.appId), conf);\n ServerResponse response = engine.respond(challenge);\n ByteBuf responseData = Unpooled.buffer(response.encodedLength());\n response.encode(responseData);\n callback.onSuccess(responseData.nioBuffer());\n engine.sessionCipher().addToChannel(channel);\n } catch (Exception e) {\n // This is a fatal error: authentication has failed. Close the channel explicitly.\n LOG.debug(\"Authentication failed for client {}, closing channel.\", channel.remoteAddress());\n callback.onFailure(new IllegalArgumentException(\"Authentication failed.\"));\n channel.close();\n return;\n } finally {\n if (engine != null) {\n try {\n engine.close();\n } catch (Exception e) {\n throw Throwables.propagate(e);\n }\n }\n }\n\n LOG.debug(\"Authorization successful for client {}.\", channel.remoteAddress());\n doDelegate = true;\n }\n\n @Override\n public void receive(TransportClient client, ByteBuffer message) {\n delegate.receive(client, message);\n }\n\n @Override\n public StreamManager getStreamManager() {\n return delegate.getStreamManager();\n }\n\n @Override\n public void channelActive(TransportClient client) {\n delegate.channelActive(client);\n }\n\n @Override\n public void channelInactive(TransportClient client) {\n delegate.channelInactive(client);\n }\n\n @Override\n public void exceptionCaught(Throwable cause, TransportClient client) {\n delegate.exceptionCaught(cause, client);\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":66,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/main/java/org/apache/spark/network/crypto/AuthClientBootstrap.java"},"num_changed_lines":{"kind":"number","value":128,"string":"128"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.security.GeneralSecurityException;\nimport java.security.Key;\nimport javax.crypto.KeyGenerator;\nimport javax.crypto.Mac;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Throwables;\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\nimport io.netty.channel.Channel;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport org.apache.spark.network.client.TransportClient;\nimport org.apache.spark.network.client.TransportClientBootstrap;\nimport org.apache.spark.network.sasl.SaslClientBootstrap;\nimport org.apache.spark.network.sasl.SecretKeyHolder;\nimport org.apache.spark.network.util.JavaUtils;\nimport org.apache.spark.network.util.TransportConf;\n\n/**\n * Bootstraps a {@link TransportClient} by performing authentication using Spark's auth protocol.\n *\n * This bootstrap falls back to using the SASL bootstrap if the server throws an error during\n * authentication, and the configuration allows it. This is used for backwards compatibility\n * with external shuffle services that do not support the new protocol.\n *\n * It also automatically falls back to SASL if the new encryption backend is disabled, so that\n * callers only need to install this bootstrap when authentication is enabled.\n */\npublic class AuthClientBootstrap implements TransportClientBootstrap {\n\n private static final Logger LOG = LoggerFactory.getLogger(AuthClientBootstrap.class);\n\n private final TransportConf conf;\n private final String appId;\n private final String authUser;\n private final SecretKeyHolder secretKeyHolder;\n\n public AuthClientBootstrap(\n TransportConf conf,\n String appId,\n SecretKeyHolder secretKeyHolder) {\n this.conf = conf;\n // TODO: right now this behaves like the SASL backend, because when executors start up\n // they don't necessarily know the app ID. So they send a hardcoded \"user\" that is defined\n // in the SecurityManager, which will also always return the same secret (regardless of the\n // user name). All that's needed here is for this \"user\" to match on both sides, since that's\n // required by the protocol. At some point, though, it would be better for the actual app ID\n // to be provided here.\n this.appId = appId;\n this.authUser = secretKeyHolder.getSaslUser(appId);\n this.secretKeyHolder = secretKeyHolder;\n }\n\n @Override\n public void doBootstrap(TransportClient client, Channel channel) {\n if (!conf.encryptionEnabled()) {\n LOG.debug(\"AES encryption disabled, using old auth protocol.\");\n doSaslAuth(client, channel);\n return;\n }\n\n try {\n doSparkAuth(client, channel);\n } catch (GeneralSecurityException | IOException e) {\n throw Throwables.propagate(e);\n } catch (RuntimeException e) {\n // There isn't a good exception that can be caught here to know whether it's really\n // OK to switch back to SASL (because the server doesn't speak the new protocol). So\n // try it anyway, and in the worst case things will fail again.\n if (conf.saslFallback()) {\n LOG.warn(\"New auth protocol failed, trying SASL.\", e);\n doSaslAuth(client, channel);\n } else {\n throw e;\n }\n }\n }\n\n private void doSparkAuth(TransportClient client, Channel channel)\n throws GeneralSecurityException, IOException {\n\n AuthEngine engine = new AuthEngine(authUser, secretKeyHolder.getSecretKey(authUser), conf);\n try {\n ClientChallenge challenge = engine.challenge();\n ByteBuf challengeData = Unpooled.buffer(challenge.encodedLength());\n challenge.encode(challengeData);\n\n ByteBuffer responseData = client.sendRpcSync(challengeData.nioBuffer(),\n conf.authRTTimeoutMs());\n ServerResponse response = ServerResponse.decodeMessage(responseData);\n\n engine.validate(response);\n engine.sessionCipher().addToChannel(channel);\n } finally {\n engine.close();\n }\n }\n\n private void doSaslAuth(TransportClient client, Channel channel) {\n SaslClientBootstrap sasl = new SaslClientBootstrap(conf, appId, secretKeyHolder);\n sasl.doBootstrap(client, channel);\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":67,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/test/java/org/apache/spark/network/crypto/AuthEngineSuite.java"},"num_changed_lines":{"kind":"number","value":109,"string":"109"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport static org.junit.Assert.*;\n\nimport org.apache.spark.network.util.MapConfigProvider;\nimport org.apache.spark.network.util.TransportConf;\n\npublic class AuthEngineSuite {\n\n private static TransportConf conf;\n\n @BeforeClass\n public static void setUp() {\n conf = new TransportConf(\"rpc\", MapConfigProvider.EMPTY);\n }\n\n @Test\n public void testAuthEngine() throws Exception {\n AuthEngine client = new AuthEngine(\"appId\", \"secret\", conf);\n AuthEngine server = new AuthEngine(\"appId\", \"secret\", conf);\n\n try {\n ClientChallenge clientChallenge = client.challenge();\n ServerResponse serverResponse = server.respond(clientChallenge);\n client.validate(serverResponse);\n\n TransportCipher serverCipher = server.sessionCipher();\n TransportCipher clientCipher = client.sessionCipher();\n\n assertTrue(Arrays.equals(serverCipher.getInputIv(), clientCipher.getOutputIv()));\n assertTrue(Arrays.equals(serverCipher.getOutputIv(), clientCipher.getInputIv()));\n assertEquals(serverCipher.getKey(), clientCipher.getKey());\n } finally {\n client.close();\n server.close();\n }\n }\n\n @Test\n public void testMismatchedSecret() throws Exception {\n AuthEngine client = new AuthEngine(\"appId\", \"secret\", conf);\n AuthEngine server = new AuthEngine(\"appId\", \"different_secret\", conf);\n\n ClientChallenge clientChallenge = client.challenge();\n try {\n server.respond(clientChallenge);\n fail(\"Should have failed to validate response.\");\n } catch (IllegalArgumentException e) {\n // Expected.\n }\n }\n\n @Test(expected = IllegalArgumentException.class)\n public void testWrongAppId() throws Exception {\n AuthEngine engine = new AuthEngine(\"appId\", \"secret\", conf);\n ClientChallenge challenge = engine.challenge();\n\n byte[] badChallenge = engine.challenge(new byte[] { 0x00 }, challenge.nonce,\n engine.rawResponse(engine.challenge));\n engine.respond(new ClientChallenge(challenge.appId, challenge.kdf, challenge.iterations,\n challenge.cipher, challenge.keyLength, challenge.nonce, badChallenge));\n }\n\n @Test(expected = IllegalArgumentException.class)\n public void testWrongNonce() throws Exception {\n AuthEngine engine = new AuthEngine(\"appId\", \"secret\", conf);\n ClientChallenge challenge = engine.challenge();\n\n byte[] badChallenge = engine.challenge(challenge.appId.getBytes(UTF_8), new byte[] { 0x00 },\n engine.rawResponse(engine.challenge));\n engine.respond(new ClientChallenge(challenge.appId, challenge.kdf, challenge.iterations,\n challenge.cipher, challenge.keyLength, challenge.nonce, badChallenge));\n }\n\n @Test(expected = IllegalArgumentException.class)\n public void testBadChallenge() throws Exception {\n AuthEngine engine = new AuthEngine(\"appId\", \"secret\", conf);\n ClientChallenge challenge = engine.challenge();\n\n byte[] badChallenge = new byte[challenge.challenge.length];\n engine.respond(new ClientChallenge(challenge.appId, challenge.kdf, challenge.iterations,\n challenge.cipher, challenge.keyLength, challenge.nonce, badChallenge));\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":68,"cells":{"file_path":{"kind":"string","value":"examples/src/main/java/org/apache/spark/examples/sql/JavaUserDefinedUntypedAggregation.java"},"num_changed_lines":{"kind":"number","value":132,"string":"132"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.spark.examples.sql;\n\n// $example on:untyped_custom_aggregation$\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.spark.sql.Dataset;\nimport org.apache.spark.sql.Row;\nimport org.apache.spark.sql.SparkSession;\nimport org.apache.spark.sql.expressions.MutableAggregationBuffer;\nimport org.apache.spark.sql.expressions.UserDefinedAggregateFunction;\nimport org.apache.spark.sql.types.DataType;\nimport org.apache.spark.sql.types.DataTypes;\nimport org.apache.spark.sql.types.StructField;\nimport org.apache.spark.sql.types.StructType;\n// $example off:untyped_custom_aggregation$\n\npublic class JavaUserDefinedUntypedAggregation {\n\n // $example on:untyped_custom_aggregation$\n public static class MyAverage extends UserDefinedAggregateFunction {\n\n private StructType inputSchema;\n private StructType bufferSchema;\n\n public MyAverage() {\n List inputFields = new ArrayList<>();\n inputFields.add(DataTypes.createStructField(\"inputColumn\", DataTypes.LongType, true));\n inputSchema = DataTypes.createStructType(inputFields);\n\n List bufferFields = new ArrayList<>();\n bufferFields.add(DataTypes.createStructField(\"sum\", DataTypes.LongType, true));\n bufferFields.add(DataTypes.createStructField(\"count\", DataTypes.LongType, true));\n bufferSchema = DataTypes.createStructType(bufferFields);\n }\n // Data types of input arguments of this aggregate function\n public StructType inputSchema() {\n return inputSchema;\n }\n // Data types of values in the aggregation buffer\n public StructType bufferSchema() {\n return bufferSchema;\n }\n // The data type of the returned value\n public DataType dataType() {\n return DataTypes.DoubleType;\n }\n // Whether this function always returns the same output on the identical input\n public boolean deterministic() {\n return true;\n }\n // Initializes the given aggregation buffer. The buffer itself is a `Row` that in addition to\n // standard methods like retrieving a value at an index (e.g., get(), getBoolean()), provides\n // the opportunity to update its values. Note that arrays and maps inside the buffer are still\n // immutable.\n public void initialize(MutableAggregationBuffer buffer) {\n buffer.update(0, 0L);\n buffer.update(1, 0L);\n }\n // Updates the given aggregation buffer `buffer` with new input data from `input`\n public void update(MutableAggregationBuffer buffer, Row input) {\n if (!input.isNullAt(0)) {\n long updatedSum = buffer.getLong(0) + input.getLong(0);\n long updatedCount = buffer.getLong(1) + 1;\n buffer.update(0, updatedSum);\n buffer.update(1, updatedCount);\n }\n }\n // Merges two aggregation buffers and stores the updated buffer values back to `buffer1`\n public void merge(MutableAggregationBuffer buffer1, Row buffer2) {\n long mergedSum = buffer1.getLong(0) + buffer2.getLong(0);\n long mergedCount = buffer1.getLong(1) + buffer2.getLong(1);\n buffer1.update(0, mergedSum);\n buffer1.update(1, mergedCount);\n }\n // Calculates the final result\n public Double evaluate(Row buffer) {\n return ((double) buffer.getLong(0)) / buffer.getLong(1);\n }\n }\n // $example off:untyped_custom_aggregation$\n\n public static void main(String[] args) {\n SparkSession spark = SparkSession\n .builder()\n .appName(\"Java Spark SQL user-defined DataFrames aggregation example\")\n .getOrCreate();\n\n // $example on:untyped_custom_aggregation$\n // Register the function to access it\n spark.udf().register(\"myAverage\", new MyAverage());\n\n Dataset df = spark.read().json(\"examples/src/main/resources/employees.json\");\n df.createOrReplaceTempView(\"employees\");\n df.show();\n // +-------+------+\n // | name|salary|\n // +-------+------+\n // |Michael| 3000|\n // | Andy| 4500|\n // | Justin| 3500|\n // | Berta| 4000|\n // +-------+------+\n\n Dataset result = spark.sql(\"SELECT myAverage(salary) as average_salary FROM employees\");\n result.show();\n // +--------------+\n // |average_salary|\n // +--------------+\n // | 3750.0|\n // +--------------+\n // $example off:untyped_custom_aggregation$\n\n spark.stop();\n }\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":69,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/main/java/org/apache/spark/network/crypto/ClientChallenge.java"},"num_changed_lines":{"kind":"number","value":101,"string":"101"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.nio.ByteBuffer;\n\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\n\nimport org.apache.spark.network.protocol.Encodable;\nimport org.apache.spark.network.protocol.Encoders;\n\n/**\n * The client challenge message, used to initiate authentication.\n *\n * @see README.md\n */\npublic class ClientChallenge implements Encodable {\n /** Serialization tag used to catch incorrect payloads. */\n private static final byte TAG_BYTE = (byte) 0xFA;\n\n public final String appId;\n public final String kdf;\n public final int iterations;\n public final String cipher;\n public final int keyLength;\n public final byte[] nonce;\n public final byte[] challenge;\n\n public ClientChallenge(\n String appId,\n String kdf,\n int iterations,\n String cipher,\n int keyLength,\n byte[] nonce,\n byte[] challenge) {\n this.appId = appId;\n this.kdf = kdf;\n this.iterations = iterations;\n this.cipher = cipher;\n this.keyLength = keyLength;\n this.nonce = nonce;\n this.challenge = challenge;\n }\n\n @Override\n public int encodedLength() {\n return 1 + 4 + 4 +\n Encoders.Strings.encodedLength(appId) +\n Encoders.Strings.encodedLength(kdf) +\n Encoders.Strings.encodedLength(cipher) +\n Encoders.ByteArrays.encodedLength(nonce) +\n Encoders.ByteArrays.encodedLength(challenge);\n }\n\n @Override\n public void encode(ByteBuf buf) {\n buf.writeByte(TAG_BYTE);\n Encoders.Strings.encode(buf, appId);\n Encoders.Strings.encode(buf, kdf);\n buf.writeInt(iterations);\n Encoders.Strings.encode(buf, cipher);\n buf.writeInt(keyLength);\n Encoders.ByteArrays.encode(buf, nonce);\n Encoders.ByteArrays.encode(buf, challenge);\n }\n\n public static ClientChallenge decodeMessage(ByteBuffer buffer) {\n ByteBuf buf = Unpooled.wrappedBuffer(buffer);\n\n if (buf.readByte() != TAG_BYTE) {\n throw new IllegalArgumentException(\"Expected ClientChallenge, received something else.\");\n }\n\n return new ClientChallenge(\n Encoders.Strings.decode(buf),\n Encoders.Strings.decode(buf),\n buf.readInt(),\n Encoders.Strings.decode(buf),\n buf.readInt(),\n Encoders.ByteArrays.decode(buf),\n Encoders.ByteArrays.decode(buf));\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":70,"cells":{"file_path":{"kind":"string","value":"R/install-source-package.sh"},"num_changed_lines":{"kind":"number","value":57,"string":"57"},"code":{"kind":"string","value":"#!/bin/bash\n\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# This scripts packages the SparkR source files (R and C files) and\n# creates a package that can be loaded in R. The package is by default installed to\n# $FWDIR/lib and the package can be loaded by using the following command in R:\n#\n# library(SparkR, lib.loc=\"$FWDIR/lib\")\n#\n# NOTE(shivaram): Right now we use $SPARK_HOME/R/lib to be the installation directory\n# to load the SparkR package on the worker nodes.\n\nset -o pipefail\nset -e\n\nFWDIR=\"$(cd `dirname \"${BASH_SOURCE[0]}\"`; pwd)\"\npushd $FWDIR > /dev/null\n. $FWDIR/find-r.sh\n\nif [ -z \"$VERSION\" ]; then\n VERSION=`grep Version $FWDIR/pkg/DESCRIPTION | awk '{print $NF}'`\nfi\n\nif [ ! -f \"$FWDIR\"/SparkR_\"$VERSION\".tar.gz ]; then\n echo -e \"R source package file $FWDIR/SparkR_$VERSION.tar.gz is not found.\"\n echo -e \"Please build R source package with check-cran.sh\"\n exit -1;\nfi\n\necho \"Removing lib path and installing from source package\"\nLIB_DIR=\"$FWDIR/lib\"\nrm -rf $LIB_DIR\nmkdir -p $LIB_DIR\n\"$R_SCRIPT_PATH/\"R CMD INSTALL SparkR_\"$VERSION\".tar.gz --library=$LIB_DIR\n\n# Zip the SparkR package so that it can be distributed to worker nodes on YARN\npushd $LIB_DIR > /dev/null\njar cfM \"$LIB_DIR/sparkr.zip\" SparkR\npopd > /dev/null\n\npopd\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":71,"cells":{"file_path":{"kind":"string","value":"R/find-r.sh"},"num_changed_lines":{"kind":"number","value":34,"string":"34"},"code":{"kind":"string","value":"#!/bin/bash\n\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nif [ -z \"$R_SCRIPT_PATH\" ]\nthen\n if [ ! -z \"$R_HOME\" ]\n then\n R_SCRIPT_PATH=\"$R_HOME/bin\"\n else\n # if system wide R_HOME is not found, then exit\n if [ ! `command -v R` ]; then\n echo \"Cannot find 'R_HOME'. Please specify 'R_HOME' or make sure R is properly installed.\"\n exit 1\n fi\n R_SCRIPT_PATH=\"$(dirname $(which R))\"\n fi\n echo \"Using R_SCRIPT_PATH = ${R_SCRIPT_PATH}\"\nfi\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":72,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/test/java/org/apache/spark/network/crypto/AuthMessagesSuite.java"},"num_changed_lines":{"kind":"number","value":80,"string":"80"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.nio.ByteBuffer;\nimport java.util.Arrays;\n\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\nimport org.junit.Test;\nimport static org.junit.Assert.*;\n\nimport org.apache.spark.network.protocol.Encodable;\n\npublic class AuthMessagesSuite {\n\n private static int COUNTER = 0;\n\n private static String string() {\n return String.valueOf(COUNTER++);\n }\n\n private static byte[] byteArray() {\n byte[] bytes = new byte[COUNTER++];\n for (int i = 0; i < bytes.length; i++) {\n bytes[i] = (byte) COUNTER;\n } return bytes;\n }\n\n private static int integer() {\n return COUNTER++;\n }\n\n @Test\n public void testClientChallenge() {\n ClientChallenge msg = new ClientChallenge(string(), string(), integer(), string(), integer(),\n byteArray(), byteArray());\n ClientChallenge decoded = ClientChallenge.decodeMessage(encode(msg));\n\n assertEquals(msg.appId, decoded.appId);\n assertEquals(msg.kdf, decoded.kdf);\n assertEquals(msg.iterations, decoded.iterations);\n assertEquals(msg.cipher, decoded.cipher);\n assertEquals(msg.keyLength, decoded.keyLength);\n assertTrue(Arrays.equals(msg.nonce, decoded.nonce));\n assertTrue(Arrays.equals(msg.challenge, decoded.challenge));\n }\n\n @Test\n public void testServerResponse() {\n ServerResponse msg = new ServerResponse(byteArray(), byteArray(), byteArray(), byteArray());\n ServerResponse decoded = ServerResponse.decodeMessage(encode(msg));\n assertTrue(Arrays.equals(msg.response, decoded.response));\n assertTrue(Arrays.equals(msg.nonce, decoded.nonce));\n assertTrue(Arrays.equals(msg.inputIv, decoded.inputIv));\n assertTrue(Arrays.equals(msg.outputIv, decoded.outputIv));\n }\n\n private ByteBuffer encode(Encodable msg) {\n ByteBuf buf = Unpooled.buffer();\n msg.encode(buf);\n return buf.nioBuffer();\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":73,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/main/java/org/apache/spark/network/crypto/AuthServerBootstrap.java"},"num_changed_lines":{"kind":"number","value":55,"string":"55"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport io.netty.channel.Channel;\n\nimport org.apache.spark.network.sasl.SaslServerBootstrap;\nimport org.apache.spark.network.sasl.SecretKeyHolder;\nimport org.apache.spark.network.server.RpcHandler;\nimport org.apache.spark.network.server.TransportServerBootstrap;\nimport org.apache.spark.network.util.TransportConf;\n\n/**\n * A bootstrap which is executed on a TransportServer's client channel once a client connects\n * to the server, enabling authentication using Spark's auth protocol (and optionally SASL for\n * clients that don't support the new protocol).\n *\n * It also automatically falls back to SASL if the new encryption backend is disabled, so that\n * callers only need to install this bootstrap when authentication is enabled.\n */\npublic class AuthServerBootstrap implements TransportServerBootstrap {\n\n private final TransportConf conf;\n private final SecretKeyHolder secretKeyHolder;\n\n public AuthServerBootstrap(TransportConf conf, SecretKeyHolder secretKeyHolder) {\n this.conf = conf;\n this.secretKeyHolder = secretKeyHolder;\n }\n\n public RpcHandler doBootstrap(Channel channel, RpcHandler rpcHandler) {\n if (!conf.encryptionEnabled()) {\n TransportServerBootstrap sasl = new SaslServerBootstrap(conf, secretKeyHolder);\n return sasl.doBootstrap(channel, rpcHandler);\n }\n\n return new AuthRpcHandler(conf, channel, rpcHandler, secretKeyHolder);\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":74,"cells":{"file_path":{"kind":"string","value":"common/network-common/src/main/java/org/apache/spark/network/crypto/ServerResponse.java"},"num_changed_lines":{"kind":"number","value":85,"string":"85"},"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.spark.network.crypto;\n\nimport java.nio.ByteBuffer;\n\nimport io.netty.buffer.ByteBuf;\nimport io.netty.buffer.Unpooled;\n\nimport org.apache.spark.network.protocol.Encodable;\nimport org.apache.spark.network.protocol.Encoders;\n\n/**\n * Server's response to client's challenge.\n *\n * @see README.md\n */\npublic class ServerResponse implements Encodable {\n /** Serialization tag used to catch incorrect payloads. */\n private static final byte TAG_BYTE = (byte) 0xFB;\n\n public final byte[] response;\n public final byte[] nonce;\n public final byte[] inputIv;\n public final byte[] outputIv;\n\n public ServerResponse(\n byte[] response,\n byte[] nonce,\n byte[] inputIv,\n byte[] outputIv) {\n this.response = response;\n this.nonce = nonce;\n this.inputIv = inputIv;\n this.outputIv = outputIv;\n }\n\n @Override\n public int encodedLength() {\n return 1 +\n Encoders.ByteArrays.encodedLength(response) +\n Encoders.ByteArrays.encodedLength(nonce) +\n Encoders.ByteArrays.encodedLength(inputIv) +\n Encoders.ByteArrays.encodedLength(outputIv);\n }\n\n @Override\n public void encode(ByteBuf buf) {\n buf.writeByte(TAG_BYTE);\n Encoders.ByteArrays.encode(buf, response);\n Encoders.ByteArrays.encode(buf, nonce);\n Encoders.ByteArrays.encode(buf, inputIv);\n Encoders.ByteArrays.encode(buf, outputIv);\n }\n\n public static ServerResponse decodeMessage(ByteBuffer buffer) {\n ByteBuf buf = Unpooled.wrappedBuffer(buffer);\n\n if (buf.readByte() != TAG_BYTE) {\n throw new IllegalArgumentException(\"Expected ServerResponse, received something else.\");\n }\n\n return new ServerResponse(\n Encoders.ByteArrays.decode(buf),\n Encoders.ByteArrays.decode(buf),\n Encoders.ByteArrays.decode(buf),\n Encoders.ByteArrays.decode(buf));\n }\n\n}\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":75,"cells":{"file_path":{"kind":"string","value":"R/create-rd.sh"},"num_changed_lines":{"kind":"number","value":37,"string":"37"},"code":{"kind":"string","value":"#!/bin/bash\n\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# This scripts packages the SparkR source files (R and C files) and\n# creates a package that can be loaded in R. The package is by default installed to\n# $FWDIR/lib and the package can be loaded by using the following command in R:\n#\n# library(SparkR, lib.loc=\"$FWDIR/lib\")\n#\n# NOTE(shivaram): Right now we use $SPARK_HOME/R/lib to be the installation directory\n# to load the SparkR package on the worker nodes.\n\nset -o pipefail\nset -e\n\nFWDIR=\"$(cd `dirname \"${BASH_SOURCE[0]}\"`; pwd)\"\npushd $FWDIR > /dev/null\n. $FWDIR/find-r.sh\n\n# Generate Rd files if devtools is installed\n\"$R_SCRIPT_PATH/\"Rscript -e ' if(\"devtools\" %in% rownames(installed.packages())) { library(devtools); devtools::document(pkg=\"./pkg\", roclets=c(\"rd\")) }'\n"},"repo_name":{"kind":"string","value":"apache_spark"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"42ad93b2c9047a68c14cbf681508157101f43c0e"}}},{"rowIdx":76,"cells":{"file_path":{"kind":"string","value":"Wox.Infrastructure/Logger/Log.cs"},"num_changed_lines":{"kind":"number","value":112,"string":"112"},"code":{"kind":"string","value":"using System.Diagnostics;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing NLog;\nusing NLog.Config;\nusing NLog.Targets;\n\nnamespace Wox.Infrastructure.Logger\n{\n public static class Log\n {\n public const string DirectoryName = \"Logs\";\n\n static Log()\n {\n var path = Path.Combine(Constant.DataDirectory, DirectoryName, Constant.Version);\n if (!Directory.Exists(path))\n {\n Directory.CreateDirectory(path);\n }\n\n var configuration = new LoggingConfiguration();\n var target = new FileTarget();\n configuration.AddTarget(\"file\", target);\n target.FileName = \"${specialfolder:folder=ApplicationData}/\" + Constant.Wox + \"/\" + DirectoryName + \"/\" +\n Constant.Version + \"/${shortdate}.txt\";\n#if DEBUG\n var rule = new LoggingRule(\"*\", LogLevel.Debug, target);\n#else\n var rule = new LoggingRule(\"*\", LogLevel.Info, target);\n#endif\n configuration.LoggingRules.Add(rule);\n LogManager.Configuration = configuration;\n }\n\n private static void LogFaultyFormat(string message)\n {\n var logger = LogManager.GetLogger(\"FaultyLogger\");\n message = $\"Wrong logger message format <{message}>\";\n System.Diagnostics.Debug.WriteLine($\"FATAL|{message}\");\n logger.Fatal(message);\n }\n\n private static bool FormatValid(string message)\n {\n var parts = message.Split('|');\n var valid = parts.Length == 3 && !string.IsNullOrWhiteSpace(parts[1]) && !string.IsNullOrWhiteSpace(parts[2]);\n return valid;\n }\n\n /// example: \"|prefix|unprefixed\" \n public static void Error(string message)\n {\n if (FormatValid(message))\n {\n var parts = message.Split('|');\n var prefix = parts[1];\n var unprefixed = parts[2];\n var logger = LogManager.GetLogger(prefix);\n\n System.Diagnostics.Debug.WriteLine($\"ERROR|{message}\");\n logger.Error(unprefixed);\n }\n else\n {\n LogFaultyFormat(message);\n }\n }\n\n /// example: \"|prefix|unprefixed\" \n [MethodImpl(MethodImplOptions.Synchronized)]\n public static void Exception(string message, System.Exception e)\n {\n#if DEBUG\n throw e;\n#else\n if (FormatValid(message))\n {\n var parts = message.Split('|');\n var prefix = parts[1];\n var unprefixed = parts[2];\n var logger = LogManager.GetLogger(prefix);\n\n System.Diagnostics.Debug.WriteLine($\"ERROR|{message}\");\n\n logger.Error(\"-------------------------- Begin exception --------------------------\");\n logger.Error(unprefixed);\n\n do\n {\n logger.Error($\"Exception message:\\n <{e.Message}>\");\n logger.Error($\"Exception stack trace:\\n <{e.StackTrace}>\");\n e = e.InnerException;\n } while (e != null);\n\n logger.Error(\"-------------------------- End exception --------------------------\");\n }\n else\n {\n LogFaultyFormat(message);\n }\n#endif\n }\n \n /// example: \"|prefix|unprefixed\" \n public static void Debug(string message)\n {\n if (FormatValid(message))\n {\n var parts = message.Split('|');\n var prefix = parts[1];\n var unprefixed = parts[2];\n var logger = LogManager.GetLogger(prefix);\n\n System.Diagnostics.Debug.WriteLine($\"DEBUG|{message}\");\n logger.Debug(unprefixed);\n }\n else\n {\n LogFaultyFormat(message);\n }\n }\n\n /// example: \"|prefix|unprefixed\" \n public static void Info(string message)\n {\n if (FormatValid(message))\n {\n var parts = message.Split('|');\n var prefix = parts[1];\n var unprefixed = parts[2];\n var logger = LogManager.GetLogger(prefix);\n\n System.Diagnostics.Debug.WriteLine($\"INFO|{message}\");\n logger.Info(unprefixed);\n }\n else\n {\n LogFaultyFormat(message);\n }\n }\n\n /// example: \"|prefix|unprefixed\" \n public static void Warn(string message)\n {\n if (FormatValid(message))\n {\n var parts = message.Split('|');\n var prefix = parts[1];\n var unprefixed = parts[2];\n var logger = LogManager.GetLogger(prefix);\n\n System.Diagnostics.Debug.WriteLine($\"WARN|{message}\");\n logger.Warn(unprefixed);\n }\n else\n {\n LogFaultyFormat(message);\n }\n }\n }\n}"},"repo_name":{"kind":"string","value":"microsoft_PowerToys"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"dc46277d0c088c48e1a13ea5f72209ea462de929"}}},{"rowIdx":77,"cells":{"file_path":{"kind":"string","value":"Wox.Infrastructure/Alphabet.cs"},"num_changed_lines":{"kind":"number","value":51,"string":"51"},"code":{"kind":"string","value":"using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing hyjiacan.util.p4n;\nusing hyjiacan.util.p4n.format;\n\nnamespace Wox.Infrastructure\n{\n public static class Alphabet\n {\n private static readonly HanyuPinyinOutputFormat Format = new HanyuPinyinOutputFormat();\n private static readonly ConcurrentDictionary PinyinCache = new ConcurrentDictionary();\n\n static Alphabet()\n {\n Format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);\n }\n\n /// \n /// replace chinese character with pinyin, non chinese character won't be modified\n /// should be word or sentence, instead of single character. e.g. 微软 \n /// \n public static string[] Pinyin(string word)\n {\n var pinyin = word.Select(c =>\n {\n var pinyins = PinyinHelper.toHanyuPinyinStringArray(c);\n var result = pinyins == null ? c.ToString() : pinyins[0];\n return result;\n }).ToArray();\n return pinyin;\n }\n\n /// \n /// replace chinese character with pinyin, non chinese character won't be modified\n /// Because we don't have words dictionary, so we can only return all possiblie pinyin combination\n /// e.g. 音乐 will return yinyue and yinle\n /// should be word or sentence, instead of single character. e.g. 微软 \n /// \n public static string[][] PinyinComination(string characters)\n {\n if (!string.IsNullOrEmpty(characters))\n {\n if (!PinyinCache.ContainsKey(characters))\n {\n\n var allPinyins = new List();\n foreach (var c in characters)\n {\n var pinyins = PinyinHelper.toHanyuPinyinStringArray(c, Format);\n if (pinyins != null)\n {\n var r = pinyins.Distinct().ToArray();\n allPinyins.Add(r);\n }\n else\n {\n var r = new[] { c.ToString() };\n allPinyins.Add(r);\n }\n }\n\n var combination = allPinyins.Aggregate(Combination).Select(c => c.Split(';')).ToArray();\n PinyinCache[characters] = combination;\n return combination;\n }\n else\n {\n return PinyinCache[characters];\n }\n }\n else\n {\n return new string[][] { };\n }\n }\n\n public static string Acronym(string[] pinyin)\n {\n var acronym = string.Join(\"\", pinyin.Select(p => p[0]));\n return acronym;\n }\n\n public static bool ContainsChinese(string word)\n {\n var chinese = word.Select(PinyinHelper.toHanyuPinyinStringArray)\n .Any(p => p != null);\n return chinese;\n }\n\n private static string[] Combination(string[] array1, string[] array2)\n {\n var combination = (\n from a1 in array1\n from a2 in array2\n select $\"{a1};{a2}\"\n ).ToArray();\n return combination;\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"microsoft_PowerToys"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"dc46277d0c088c48e1a13ea5f72209ea462de929"}}},{"rowIdx":78,"cells":{"file_path":{"kind":"string","value":"Wox.Infrastructure/Image/ImageCache.cs"},"num_changed_lines":{"kind":"number","value":23,"string":"23"},"code":{"kind":"string","value":"using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows.Media;\n\nnamespace Wox.Infrastructure.Image\n{\n [Serializable]\n public class ImageCache\n {\n private const int MaxCached = 200;\n public ConcurrentDictionary Usage = new ConcurrentDictionary();\n private readonly ConcurrentDictionary _data = new ConcurrentDictionary();\n\n\n public ImageSource this[string path]\n {\n get\n {\n Usage.AddOrUpdate(path, 1, (k, v) => v + 1);\n var i = _data[path];\n return i;\n }\n set { _data[path] = value; }\n }\n\n public void Cleanup()\n {\n var images = Usage\n .OrderByDescending(o => o.Value)\n .Take(MaxCached)\n .ToDictionary(i => i.Key, i => i.Value);\n Usage = new ConcurrentDictionary(images);\n }\n\n public bool ContainsKey(string key)\n {\n var contains = _data.ContainsKey(key);\n return contains;\n }\n }\n\n}\n"},"repo_name":{"kind":"string","value":"microsoft_PowerToys"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"dc46277d0c088c48e1a13ea5f72209ea462de929"}}},{"rowIdx":79,"cells":{"file_path":{"kind":"string","value":"requests/packages/urllib3/util/selectors.py"},"num_changed_lines":{"kind":"number","value":524,"string":"524"},"code":{"kind":"string","value":"# Backport of selectors.py from Python 3.5+ to support Python < 3.4\n# Also has the behavior specified in PEP 475 which is to retry syscalls\n# in the case of an EINTR error. This module is required because selectors34\n# does not follow this behavior and instead returns that no dile descriptor\n# events have occurred rather than retry the syscall. The decision to drop\n# support for select.devpoll is made to maintain 100% test coverage.\n\nimport errno\nimport math\nimport select\nfrom collections import namedtuple, Mapping\n\nimport time\ntry:\n monotonic = time.monotonic\nexcept (AttributeError, ImportError): # Python 3.3<\n monotonic = time.time\n\nEVENT_READ = (1 << 0)\nEVENT_WRITE = (1 << 1)\n\nHAS_SELECT = True # Variable that shows whether the platform has a selector.\n_SYSCALL_SENTINEL = object() # Sentinel in case a system call returns None.\n\n\nclass SelectorError(Exception):\n def __init__(self, errcode):\n super(SelectorError, self).__init__()\n self.errno = errcode\n\n def __repr__(self):\n return \"\".format(self.errno)\n\n def __str__(self):\n return self.__repr__()\n\n\ndef _fileobj_to_fd(fileobj):\n \"\"\" Return a file descriptor from a file object. If\n given an integer will simply return that integer back. \"\"\"\n if isinstance(fileobj, int):\n fd = fileobj\n else:\n try:\n fd = int(fileobj.fileno())\n except (AttributeError, TypeError, ValueError):\n raise ValueError(\"Invalid file object: {0!r}\".format(fileobj))\n if fd < 0:\n raise ValueError(\"Invalid file descriptor: {0}\".format(fd))\n return fd\n\n\ndef _syscall_wrapper(func, recalc_timeout, *args, **kwargs):\n \"\"\" Wrapper function for syscalls that could fail due to EINTR.\n All functions should be retried if there is time left in the timeout\n in accordance with PEP 475. \"\"\"\n timeout = kwargs.get(\"timeout\", None)\n if timeout is None:\n expires = None\n recalc_timeout = False\n else:\n timeout = float(timeout)\n if timeout < 0.0: # Timeout less than 0 treated as no timeout.\n expires = None\n else:\n expires = monotonic() + timeout\n\n args = list(args)\n if recalc_timeout and \"timeout\" not in kwargs:\n raise ValueError(\n \"Timeout must be in args or kwargs to be recalculated\")\n\n result = _SYSCALL_SENTINEL\n while result is _SYSCALL_SENTINEL:\n try:\n result = func(*args, **kwargs)\n # OSError is thrown by select.select\n # IOError is thrown by select.epoll.poll\n # select.error is thrown by select.poll.poll\n # Aren't we thankful for Python 3.x rework for exceptions?\n except (OSError, IOError, select.error) as e:\n # select.error wasn't a subclass of OSError in the past.\n errcode = None\n if hasattr(e, \"errno\"):\n errcode = e.errno\n elif hasattr(e, \"args\"):\n errcode = e.args[0]\n\n # Also test for the Windows equivalent of EINTR.\n is_interrupt = (errcode == errno.EINTR or (hasattr(errno, \"WSAEINTR\") and\n errcode == errno.WSAEINTR))\n\n if is_interrupt:\n if expires is not None:\n current_time = monotonic()\n if current_time > expires:\n raise OSError(errno=errno.ETIMEDOUT)\n if recalc_timeout:\n if \"timeout\" in kwargs:\n kwargs[\"timeout\"] = expires - current_time\n continue\n if errcode:\n raise SelectorError(errcode)\n else:\n raise\n return result\n\n\nSelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])\n\n\nclass _SelectorMapping(Mapping):\n \"\"\" Mapping of file objects to selector keys \"\"\"\n\n def __init__(self, selector):\n self._selector = selector\n\n def __len__(self):\n return len(self._selector._fd_to_key)\n\n def __getitem__(self, fileobj):\n try:\n fd = self._selector._fileobj_lookup(fileobj)\n return self._selector._fd_to_key[fd]\n except KeyError:\n raise KeyError(\"{0!r} is not registered.\".format(fileobj))\n\n def __iter__(self):\n return iter(self._selector._fd_to_key)\n\n\nclass BaseSelector(object):\n \"\"\" Abstract Selector class\n\n A selector supports registering file objects to be monitored\n for specific I/O events.\n\n A file object is a file descriptor or any object with a\n `fileno()` method. An arbitrary object can be attached to the\n file object which can be used for example to store context info,\n a callback, etc.\n\n A selector can use various implementations (select(), poll(), epoll(),\n and kqueue()) depending on the platform. The 'DefaultSelector' class uses\n the most efficient implementation for the current platform.\n \"\"\"\n def __init__(self):\n # Maps file descriptors to keys.\n self._fd_to_key = {}\n\n # Read-only mapping returned by get_map()\n self._map = _SelectorMapping(self)\n\n def _fileobj_lookup(self, fileobj):\n \"\"\" Return a file descriptor from a file object.\n This wraps _fileobj_to_fd() to do an exhaustive\n search in case the object is invalid but we still\n have it in our map. Used by unregister() so we can\n unregister an object that was previously registered\n even if it is closed. It is also used by _SelectorMapping\n \"\"\"\n try:\n return _fileobj_to_fd(fileobj)\n except ValueError:\n\n # Search through all our mapped keys.\n for key in self._fd_to_key.values():\n if key.fileobj is fileobj:\n return key.fd\n\n # Raise ValueError after all.\n raise\n\n def register(self, fileobj, events, data=None):\n \"\"\" Register a file object for a set of events to monitor. \"\"\"\n if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)):\n raise ValueError(\"Invalid events: {0!r}\".format(events))\n\n key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)\n\n if key.fd in self._fd_to_key:\n raise KeyError(\"{0!r} (FD {1}) is already registered\"\n .format(fileobj, key.fd))\n\n self._fd_to_key[key.fd] = key\n return key\n\n def unregister(self, fileobj):\n \"\"\" Unregister a file object from being monitored. \"\"\"\n try:\n key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))\n except KeyError:\n raise KeyError(\"{0!r} is not registered\".format(fileobj))\n return key\n\n def modify(self, fileobj, events, data=None):\n \"\"\" Change a registered file object monitored events and data. \"\"\"\n # NOTE: Some subclasses optimize this operation even further.\n try:\n key = self._fd_to_key[self._fileobj_lookup(fileobj)]\n except KeyError:\n raise KeyError(\"{0!r} is not registered\".format(fileobj))\n\n if events != key.events:\n self.unregister(fileobj)\n key = self.register(fileobj, events, data)\n\n elif data != key.data:\n # Use a shortcut to update the data.\n key = key._replace(data=data)\n self._fd_to_key[key.fd] = key\n\n return key\n\n def select(self, timeout=None):\n \"\"\" Perform the actual selection until some monitored file objects\n are ready or the timeout expires. \"\"\"\n raise NotImplementedError()\n\n def close(self):\n \"\"\" Close the selector. This must be called to ensure that all\n underlying resources are freed. \"\"\"\n self._fd_to_key.clear()\n self._map = None\n\n def get_key(self, fileobj):\n \"\"\" Return the key associated with a registered file object. \"\"\"\n mapping = self.get_map()\n if mapping is None:\n raise RuntimeError(\"Selector is closed\")\n try:\n return mapping[fileobj]\n except KeyError:\n raise KeyError(\"{0!r} is not registered\".format(fileobj))\n\n def get_map(self):\n \"\"\" Return a mapping of file objects to selector keys \"\"\"\n return self._map\n\n def _key_from_fd(self, fd):\n \"\"\" Return the key associated to a given file descriptor\n Return None if it is not found. \"\"\"\n try:\n return self._fd_to_key[fd]\n except KeyError:\n return None\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n\n# Almost all platforms have select.select()\nif hasattr(select, \"select\"):\n class SelectSelector(BaseSelector):\n \"\"\" Select-based selector. \"\"\"\n def __init__(self):\n super(SelectSelector, self).__init__()\n self._readers = set()\n self._writers = set()\n\n def register(self, fileobj, events, data=None):\n key = super(SelectSelector, self).register(fileobj, events, data)\n if events & EVENT_READ:\n self._readers.add(key.fd)\n if events & EVENT_WRITE:\n self._writers.add(key.fd)\n return key\n\n def unregister(self, fileobj):\n key = super(SelectSelector, self).unregister(fileobj)\n self._readers.discard(key.fd)\n self._writers.discard(key.fd)\n return key\n\n def _select(self, r, w, timeout=None):\n \"\"\" Wrapper for select.select because timeout is a positional arg \"\"\"\n return select.select(r, w, [], timeout)\n\n def select(self, timeout=None):\n # Selecting on empty lists on Windows errors out.\n if not len(self._readers) and not len(self._writers):\n return []\n\n timeout = None if timeout is None else max(timeout, 0.0)\n ready = []\n r, w, _ = _syscall_wrapper(self._select, True, self._readers,\n self._writers, timeout)\n r = set(r)\n w = set(w)\n for fd in r | w:\n events = 0\n if fd in r:\n events |= EVENT_READ\n if fd in w:\n events |= EVENT_WRITE\n\n key = self._key_from_fd(fd)\n if key:\n ready.append((key, events & key.events))\n return ready\n\n\nif hasattr(select, \"poll\"):\n class PollSelector(BaseSelector):\n \"\"\" Poll-based selector \"\"\"\n def __init__(self):\n super(PollSelector, self).__init__()\n self._poll = select.poll()\n\n def register(self, fileobj, events, data=None):\n key = super(PollSelector, self).register(fileobj, events, data)\n event_mask = 0\n if events & EVENT_READ:\n event_mask |= select.POLLIN\n if events & EVENT_WRITE:\n event_mask |= select.POLLOUT\n self._poll.register(key.fd, event_mask)\n return key\n\n def unregister(self, fileobj):\n key = super(PollSelector, self).unregister(fileobj)\n self._poll.unregister(key.fd)\n return key\n\n def _wrap_poll(self, timeout=None):\n \"\"\" Wrapper function for select.poll.poll() so that\n _syscall_wrapper can work with only seconds. \"\"\"\n if timeout is not None:\n if timeout <= 0:\n timeout = 0\n else:\n # select.poll.poll() has a resolution of 1 millisecond,\n # round away from zero to wait *at least* timeout seconds.\n timeout = math.ceil(timeout * 1e3)\n\n result = self._poll.poll(timeout)\n return result\n\n def select(self, timeout=None):\n ready = []\n fd_events = _syscall_wrapper(self._wrap_poll, True, timeout=timeout)\n for fd, event_mask in fd_events:\n events = 0\n if event_mask & ~select.POLLIN:\n events |= EVENT_WRITE\n if event_mask & ~select.POLLOUT:\n events |= EVENT_READ\n\n key = self._key_from_fd(fd)\n if key:\n ready.append((key, events & key.events))\n\n return ready\n\n\nif hasattr(select, \"epoll\"):\n class EpollSelector(BaseSelector):\n \"\"\" Epoll-based selector \"\"\"\n def __init__(self):\n super(EpollSelector, self).__init__()\n self._epoll = select.epoll()\n\n def fileno(self):\n return self._epoll.fileno()\n\n def register(self, fileobj, events, data=None):\n key = super(EpollSelector, self).register(fileobj, events, data)\n events_mask = 0\n if events & EVENT_READ:\n events_mask |= select.EPOLLIN\n if events & EVENT_WRITE:\n events_mask |= select.EPOLLOUT\n _syscall_wrapper(self._epoll.register, False, key.fd, events_mask)\n return key\n\n def unregister(self, fileobj):\n key = super(EpollSelector, self).unregister(fileobj)\n try:\n _syscall_wrapper(self._epoll.unregister, False, key.fd)\n except SelectorError:\n # This can occur when the fd was closed since registry.\n pass\n return key\n\n def select(self, timeout=None):\n if timeout is not None:\n if timeout <= 0:\n timeout = 0.0\n else:\n # select.epoll.poll() has a resolution of 1 millisecond\n # but luckily takes seconds so we don't need a wrapper\n # like PollSelector. Just for better rounding.\n timeout = math.ceil(timeout * 1e3) * 1e-3\n timeout = float(timeout)\n else:\n timeout = -1.0 # epoll.poll() must have a float.\n\n # We always want at least 1 to ensure that select can be called\n # with no file descriptors registered. Otherwise will fail.\n max_events = max(len(self._fd_to_key), 1)\n\n ready = []\n fd_events = _syscall_wrapper(self._epoll.poll, True,\n timeout=timeout,\n maxevents=max_events)\n for fd, event_mask in fd_events:\n events = 0\n if event_mask & ~select.EPOLLIN:\n events |= EVENT_WRITE\n if event_mask & ~select.EPOLLOUT:\n events |= EVENT_READ\n\n key = self._key_from_fd(fd)\n if key:\n ready.append((key, events & key.events))\n return ready\n\n def close(self):\n self._epoll.close()\n super(EpollSelector, self).close()\n\n\nif hasattr(select, \"kqueue\"):\n class KqueueSelector(BaseSelector):\n \"\"\" Kqueue / Kevent-based selector \"\"\"\n def __init__(self):\n super(KqueueSelector, self).__init__()\n self._kqueue = select.kqueue()\n\n def fileno(self):\n return self._kqueue.fileno()\n\n def register(self, fileobj, events, data=None):\n key = super(KqueueSelector, self).register(fileobj, events, data)\n if events & EVENT_READ:\n kevent = select.kevent(key.fd,\n select.KQ_FILTER_READ,\n select.KQ_EV_ADD)\n\n _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)\n\n if events & EVENT_WRITE:\n kevent = select.kevent(key.fd,\n select.KQ_FILTER_WRITE,\n select.KQ_EV_ADD)\n\n _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)\n\n return key\n\n def unregister(self, fileobj):\n key = super(KqueueSelector, self).unregister(fileobj)\n if key.events & EVENT_READ:\n kevent = select.kevent(key.fd,\n select.KQ_FILTER_READ,\n select.KQ_EV_DELETE)\n try:\n _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)\n except SelectorError:\n pass\n if key.events & EVENT_WRITE:\n kevent = select.kevent(key.fd,\n select.KQ_FILTER_WRITE,\n select.KQ_EV_DELETE)\n try:\n _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0)\n except SelectorError:\n pass\n\n return key\n\n def select(self, timeout=None):\n if timeout is not None:\n timeout = max(timeout, 0)\n\n max_events = len(self._fd_to_key) * 2\n ready_fds = {}\n\n kevent_list = _syscall_wrapper(self._kqueue.control, True,\n None, max_events, timeout)\n\n for kevent in kevent_list:\n fd = kevent.ident\n event_mask = kevent.filter\n events = 0\n if event_mask == select.KQ_FILTER_READ:\n events |= EVENT_READ\n if event_mask == select.KQ_FILTER_WRITE:\n events |= EVENT_WRITE\n\n key = self._key_from_fd(fd)\n if key:\n if key.fd not in ready_fds:\n ready_fds[key.fd] = (key, events & key.events)\n else:\n old_events = ready_fds[key.fd][1]\n ready_fds[key.fd] = (key, (events | old_events) & key.events)\n\n return list(ready_fds.values())\n\n def close(self):\n self._kqueue.close()\n super(KqueueSelector, self).close()\n\n\n# Choose the best implementation, roughly:\n# kqueue == epoll > poll > select. Devpoll not supported. (See above)\n# select() also can't accept a FD > FD_SETSIZE (usually around 1024)\nif 'KqueueSelector' in globals(): # Platform-specific: Mac OS and BSD\n DefaultSelector = KqueueSelector\nelif 'EpollSelector' in globals(): # Platform-specific: Linux\n DefaultSelector = EpollSelector\nelif 'PollSelector' in globals(): # Platform-specific: Linux\n DefaultSelector = PollSelector\nelif 'SelectSelector' in globals(): # Platform-specific: Windows\n DefaultSelector = SelectSelector\nelse: # Platform-specific: AppEngine\n def no_selector(_):\n raise ValueError(\"Platform does not have a selector\")\n DefaultSelector = no_selector\n HAS_SELECT = False\n"},"repo_name":{"kind":"string","value":"psf_requests"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"8a58427d8aa73d6af81b6e5f6fd934b3386ef3de"}}},{"rowIdx":80,"cells":{"file_path":{"kind":"string","value":"requests/packages/urllib3/util/request.py"},"num_changed_lines":{"kind":"number","value":47,"string":"47"},"code":{"kind":"string","value":"from __future__ import absolute_import\nfrom base64 import b64encode\n\nfrom ..packages.six import b, integer_types\nfrom ..exceptions import UnrewindableBodyError\n\nACCEPT_ENCODING = 'gzip,deflate'\n_FAILEDTELL = object()\n\n\ndef make_headers(keep_alive=None, accept_encoding=None, user_agent=None,\n basic_auth=None, proxy_basic_auth=None, disable_cache=None):\n \"\"\"\n Shortcuts for generating request headers.\n\n :param keep_alive:\n If ``True``, adds 'connection: keep-alive' header.\n\n :param accept_encoding:\n Can be a boolean, list, or string.\n ``True`` translates to 'gzip,deflate'.\n List will get joined by comma.\n String will be used as provided.\n\n :param user_agent:\n String representing the user-agent you want, such as\n \"python-urllib3/0.6\"\n\n :param basic_auth:\n Colon-separated username:password string for 'authorization: basic ...'\n auth header.\n\n :param proxy_basic_auth:\n Colon-separated username:password string for 'proxy-authorization: basic ...'\n auth header.\n\n :param disable_cache:\n If ``True``, adds 'cache-control: no-cache' header.\n\n Example::\n\n >>> make_headers(keep_alive=True, user_agent=\"Batman/1.0\")\n {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}\n >>> make_headers(accept_encoding=True)\n {'accept-encoding': 'gzip,deflate'}\n \"\"\"\n headers = {}\n if accept_encoding:\n if isinstance(accept_encoding, str):\n pass\n elif isinstance(accept_encoding, list):\n accept_encoding = ','.join(accept_encoding)\n else:\n accept_encoding = ACCEPT_ENCODING\n headers['accept-encoding'] = accept_encoding\n\n if user_agent:\n headers['user-agent'] = user_agent\n\n if keep_alive:\n headers['connection'] = 'keep-alive'\n\n if basic_auth:\n headers['authorization'] = 'Basic ' + \\\n b64encode(b(basic_auth)).decode('utf-8')\n\n if proxy_basic_auth:\n headers['proxy-authorization'] = 'Basic ' + \\\n b64encode(b(proxy_basic_auth)).decode('utf-8')\n\n if disable_cache:\n headers['cache-control'] = 'no-cache'\n\n return headers\n\n\ndef set_file_position(body, pos):\n \"\"\"\n If a position is provided, move file to that point.\n Otherwise, we'll attempt to record a position for future use.\n \"\"\"\n if pos is not None:\n rewind_body(body, pos)\n elif getattr(body, 'tell', None) is not None:\n try:\n pos = body.tell()\n except (IOError, OSError):\n # This differentiates from None, allowing us to catch\n # a failed `tell()` later when trying to rewind the body.\n pos = _FAILEDTELL\n\n return pos\n\n\ndef rewind_body(body, body_pos):\n \"\"\"\n Attempt to rewind body to a certain position.\n Primarily used for request redirects and retries.\n\n :param body:\n File-like object that supports seek.\n\n :param int pos:\n Position to seek to in file.\n \"\"\"\n body_seek = getattr(body, 'seek', None)\n if body_seek is not None and isinstance(body_pos, integer_types):\n try:\n body_seek(body_pos)\n except (IOError, OSError):\n raise UnrewindableBodyError(\"An error occured when rewinding request \"\n \"body for redirect/retry.\")\n elif body_pos is _FAILEDTELL:\n raise UnrewindableBodyError(\"Unable to record file position for rewinding \"\n \"request body during a redirect/retry.\")\n else:\n raise ValueError(\"body_pos must be of type integer, \"\n \"instead it was %s.\" % type(body_pos))\n"},"repo_name":{"kind":"string","value":"psf_requests"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"8a58427d8aa73d6af81b6e5f6fd934b3386ef3de"}}},{"rowIdx":81,"cells":{"file_path":{"kind":"string","value":"requests/packages/urllib3/util/wait.py"},"num_changed_lines":{"kind":"number","value":40,"string":"40"},"code":{"kind":"string","value":"from .selectors import (\n HAS_SELECT,\n DefaultSelector,\n EVENT_READ,\n EVENT_WRITE\n)\n\n\ndef _wait_for_io_events(socks, events, timeout=None):\n \"\"\" Waits for IO events to be available from a list of sockets\n or optionally a single socket if passed in. Returns a list of\n sockets that can be interacted with immediately. \"\"\"\n if not HAS_SELECT:\n raise ValueError('Platform does not have a selector')\n if not isinstance(socks, list):\n # Probably just a single socket.\n if hasattr(socks, \"fileno\"):\n socks = [socks]\n # Otherwise it might be a non-list iterable.\n else:\n socks = list(socks)\n with DefaultSelector() as selector:\n for sock in socks:\n selector.register(sock, events)\n return [key[0].fileobj for key in\n selector.select(timeout) if key[1] & events]\n\n\ndef wait_for_read(socks, timeout=None):\n \"\"\" Waits for reading to be available from a list of sockets\n or optionally a single socket if passed in. Returns a list of\n sockets that can be read from immediately. \"\"\"\n return _wait_for_io_events(socks, EVENT_READ, timeout)\n\n\ndef wait_for_write(socks, timeout=None):\n \"\"\" Waits for writing to be available from a list of sockets\n or optionally a single socket if passed in. Returns a list of\n sockets that can be written to immediately. \"\"\"\n return _wait_for_io_events(socks, EVENT_WRITE, timeout)\n"},"repo_name":{"kind":"string","value":"psf_requests"},"commit_date":{"kind":"string","value":"2017-01-27"},"sha":{"kind":"string","value":"8a58427d8aa73d6af81b6e5f6fd934b3386ef3de"}}},{"rowIdx":82,"cells":{"file_path":{"kind":"string","value":"keras/utils/generic_utils.py"},"num_changed_lines":{"kind":"number","value":146,"string":"146"},"code":{"kind":"string","value":"\"\"\"Python utilities required by Keras.\"\"\"\nfrom __future__ import absolute_import\n\nimport numpy as np\n\nimport time\nimport sys\nimport six\nimport marshal\nimport types as python_types\n\n_GLOBAL_CUSTOM_OBJECTS = {}\n\n\nclass CustomObjectScope(object):\n \"\"\"Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape.\n\n Code within a `with` statement will be able to access custom objects\n by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with`\n statement, global custom objects are reverted to state at beginning of the `with` statement.\n\n # Example\n\n Consider a custom object `MyObject`\n\n ```python\n with CustomObjectScope({\"MyObject\":MyObject}):\n layer = Dense(..., W_regularizer=\"MyObject\")\n # save, load, etc. will recognize custom object by name\n ```\n \"\"\"\n def __init__(self, *args):\n self.custom_objects = args\n self.backup = None\n\n def __enter__(self):\n self.backup = _GLOBAL_CUSTOM_OBJECTS.copy()\n for objects in self.custom_objects:\n _GLOBAL_CUSTOM_OBJECTS.update(objects)\n return self\n\n def __exit__(self, type, value, traceback):\n _GLOBAL_CUSTOM_OBJECTS.clear()\n _GLOBAL_CUSTOM_OBJECTS.update(self.backup)\n\n\ndef custom_object_scope(*args):\n \"\"\"Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape.\n\n Convenience wrapper for `CustomObjectScope`. Code within a `with` statement will be able to access custom objects\n by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with`\n statement, global custom objects are reverted to state at beginning of the `with` statement.\n\n # Example\n\n Consider a custom object `MyObject`\n\n ```python\n with custom_object_scope({\"MyObject\":MyObject}):\n layer = Dense(..., W_regularizer=\"MyObject\")\n # save, load, etc. will recognize custom object by name\n ```\n\n # Arguments\n *args: Variable length list of dictionaries of name, class pairs to add to custom objects.\n\n # Returns\n Object of type `CustomObjectScope`.\n \"\"\"\n return CustomObjectScope(*args)\n\n\ndef get_custom_objects():\n \"\"\"Retrieves a live reference to the global dictionary of custom objects (`_GLOBAL_CUSTOM_OBJECTS`).\n\n Updating and clearing custom objects using `custom_object_scope` is preferred, but `get_custom_objects` can\n be used to directly access `_GLOBAL_CUSTOM_OBJECTS`.\n\n # Example\n\n ```python\n get_custom_objects().clear()\n get_custom_objects()[\"MyObject\"] = MyObject\n ```\n\n # Returns\n Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`).\n \"\"\"\n return _GLOBAL_CUSTOM_OBJECTS\n\n\ndef get_from_module(identifier, module_params, module_name,\n instantiate=False, kwargs=None):\n \"\"\"Retrieves a class or function member of a module.\n\n First checks `_GLOBAL_CUSTOM_OBJECTS` for `module_name`, then checks `module_params`.\n\n # Arguments\n identifier: the object to retrieve. It could be specified\n by name (as a string), or by dict. In any other case,\n `identifier` itself will be returned without any changes.\n module_params: the members of a module\n (e.g. the output of `globals()`).\n module_name: string; the name of the target module. Only used\n to format error messages.\n instantiate: whether to instantiate the returned object\n (if it's a class).\n kwargs: a dictionary of keyword arguments to pass to the\n class constructor if `instantiate` is `True`.\n\n # Returns\n The target object.\n\n # Raises\n ValueError: if the identifier cannot be found.\n \"\"\"\n if isinstance(identifier, six.string_types):\n res = None\n if identifier in _GLOBAL_CUSTOM_OBJECTS:\n res = _GLOBAL_CUSTOM_OBJECTS[identifier]\n if not res:\n res = module_params.get(identifier)\n if not res:\n raise ValueError('Invalid ' + str(module_name) + ': ' +\n str(identifier))\n if instantiate and not kwargs:\n return res()\n elif instantiate and kwargs:\n return res(**kwargs)\n else:\n return res\n elif isinstance(identifier, dict):\n name = identifier.pop('name')\n res = None\n if name in _GLOBAL_CUSTOM_OBJECTS:\n res = _GLOBAL_CUSTOM_OBJECTS[name]\n if not res:\n res = module_params.get(name)\n if res:\n return res(**identifier)\n else:\n raise ValueError('Invalid ' + str(module_name) + ': ' +\n str(identifier))\n return identifier\n\n\ndef make_tuple(*args):\n return args\n\n\ndef func_dump(func):\n \"\"\"Serializes a user defined function.\n\n # Arguments\n func: the function to serialize.\n\n # Returns\n A tuple `(code, defaults, closure)`.\n \"\"\"\n code = marshal.dumps(func.__code__).decode('raw_unicode_escape')\n defaults = func.__defaults__\n if func.__closure__:\n closure = tuple(c.cell_contents for c in func.__closure__)\n else:\n closure = None\n return code, defaults, closure\n\n\ndef func_load(code, defaults=None, closure=None, globs=None):\n \"\"\"Deserializes a user defined function.\n\n # Arguments\n code: bytecode of the function.\n defaults: defaults of the function.\n closure: closure of the function.\n globs: dictionary of global objects.\n\n # Returns\n A function object.\n \"\"\"\n if isinstance(code, (tuple, list)): # unpack previous dump\n code, defaults, closure = code\n code = marshal.loads(code.encode('raw_unicode_escape'))\n if globs is None:\n globs = globals()\n return python_types.FunctionType(code, globs,\n name=code.co_name,\n argdefs=defaults,\n closure=closure)\n\n\nclass Progbar(object):\n \"\"\"Displays a progress bar.\n\n # Arguments\n target: Total number of steps expected.\n interval: Minimum visual progress update interval (in seconds).\n \"\"\"\n\n def __init__(self, target, width=30, verbose=1, interval=0.01):\n self.width = width\n self.target = target\n self.sum_values = {}\n self.unique_values = []\n self.start = time.time()\n self.last_update = 0\n self.interval = interval\n self.total_width = 0\n self.seen_so_far = 0\n self.verbose = verbose\n\n def update(self, current, values=None, force=False):\n \"\"\"Updates the progress bar.\n\n # Arguments\n current: Index of current step.\n values: List of tuples (name, value_for_last_step).\n The progress bar will display averages for these values.\n force: Whether to force visual progress update.\n \"\"\"\n values = values or []\n for k, v in values:\n if k not in self.sum_values:\n self.sum_values[k] = [v * (current - self.seen_so_far),\n current - self.seen_so_far]\n self.unique_values.append(k)\n else:\n self.sum_values[k][0] += v * (current - self.seen_so_far)\n self.sum_values[k][1] += (current - self.seen_so_far)\n self.seen_so_far = current\n\n now = time.time()\n if self.verbose == 1:\n if not force and (now - self.last_update) < self.interval:\n return\n\n prev_total_width = self.total_width\n sys.stdout.write('\\b' * prev_total_width)\n sys.stdout.write('\\r')\n\n numdigits = int(np.floor(np.log10(self.target))) + 1\n barstr = '%%%dd/%%%dd [' % (numdigits, numdigits)\n bar = barstr % (current, self.target)\n prog = float(current) / self.target\n prog_width = int(self.width * prog)\n if prog_width > 0:\n bar += ('=' * (prog_width - 1))\n if current < self.target:\n bar += '>'\n else:\n bar += '='\n bar += ('.' * (self.width - prog_width))\n bar += ']'\n sys.stdout.write(bar)\n self.total_width = len(bar)\n\n if current:\n time_per_unit = (now - self.start) / current\n else:\n time_per_unit = 0\n eta = time_per_unit * (self.target - current)\n info = ''\n if current < self.target:\n info += ' - ETA: %ds' % eta\n else:\n info += ' - %ds' % (now - self.start)\n for k in self.unique_values:\n info += ' - %s:' % k\n if isinstance(self.sum_values[k], list):\n avg = self.sum_values[k][0] / max(1, self.sum_values[k][1])\n if abs(avg) > 1e-3:\n info += ' %.4f' % avg\n else:\n info += ' %.4e' % avg\n else:\n info += ' %s' % self.sum_values[k]\n\n self.total_width += len(info)\n if prev_total_width > self.total_width:\n info += ((prev_total_width - self.total_width) * ' ')\n\n sys.stdout.write(info)\n sys.stdout.flush()\n\n if current >= self.target:\n sys.stdout.write('\\n')\n\n if self.verbose == 2:\n if current >= self.target:\n info = '%ds' % (now - self.start)\n for k in self.unique_values:\n info += ' - %s:' % k\n avg = self.sum_values[k][0] / max(1, self.sum_values[k][1])\n if avg > 1e-3:\n info += ' %.4f' % avg\n else:\n info += ' %.4e' % avg\n sys.stdout.write(info + \"\\n\")\n\n self.last_update = now\n\n def add(self, n, values=None):\n self.update(self.seen_so_far + n, values)\n"},"repo_name":{"kind":"string","value":"keras-team_keras"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"ab3b93e8dd103f1d9729305825791a084c7c8493"}}},{"rowIdx":83,"cells":{"file_path":{"kind":"string","value":"keras/utils/np_utils.py"},"num_changed_lines":{"kind":"number","value":63,"string":"63"},"code":{"kind":"string","value":"\"\"\"Numpy-related utilities.\"\"\"\nfrom __future__ import absolute_import\n\nimport numpy as np\nfrom six.moves import range\nfrom six.moves import zip\nfrom .. import backend as K\n\n\ndef to_categorical(y, nb_classes=None):\n \"\"\"Converts a class vector (integers) to binary class matrix.\n\n E.g. for use with categorical_crossentropy.\n\n # Arguments\n y: class vector to be converted into a matrix\n (integers from 0 to nb_classes).\n nb_classes: total number of classes.\n\n # Returns\n A binary matrix representation of the input.\n \"\"\"\n y = np.array(y, dtype='int').ravel()\n if not nb_classes:\n nb_classes = np.max(y) + 1\n n = y.shape[0]\n categorical = np.zeros((n, nb_classes))\n categorical[np.arange(n), y] = 1\n return categorical\n\n\ndef normalize(a, axis=-1, order=2):\n l2 = np.atleast_1d(np.linalg.norm(a, order, axis))\n l2[l2 == 0] = 1\n return a / np.expand_dims(l2, axis)\n\n\ndef binary_logloss(p, y):\n epsilon = 1e-15\n p = np.maximum(epsilon, p)\n p = np.minimum(1 - epsilon, p)\n res = sum(y * np.log(p) + np.subtract(1, y) * np.log(np.subtract(1, p)))\n res *= -1.0 / len(y)\n return res\n\n\ndef multiclass_logloss(p, y):\n npreds = [p[i][y[i] - 1] for i in range(len(y))]\n score = -(1. / len(y)) * np.sum(np.log(npreds))\n return score\n\n\ndef accuracy(p, y):\n return np.mean([a == b for a, b in zip(p, y)])\n\n\ndef probas_to_classes(y_pred):\n if len(y_pred.shape) > 1 and y_pred.shape[1] > 1:\n return categorical_probas_to_classes(y_pred)\n return np.array([1 if p > 0.5 else 0 for p in y_pred])\n\n\ndef categorical_probas_to_classes(p):\n return np.argmax(p, axis=1)\n\n\ndef convert_kernel(kernel, dim_ordering=None):\n \"\"\"Converts a Numpy kernel matrix from Theano format to TensorFlow format.\n\n Also works reciprocally, since the transformation is its own inverse.\n\n # Arguments\n kernel: Numpy array (4D or 5D).\n dim_ordering: the data format.\n\n # Returns\n The converted kernel.\n\n # Raises\n ValueError: in case of invalid kernel shape or invalid dim_ordering.\n \"\"\"\n if dim_ordering is None:\n dim_ordering = K.image_dim_ordering()\n if not 4 <= kernel.ndim <= 5:\n raise ValueError('Invalid kernel shape:', kernel.shape)\n\n slices = [slice(None, None, -1) for _ in range(kernel.ndim)]\n no_flip = (slice(None, None), slice(None, None))\n if dim_ordering == 'th': # (out_depth, input_depth, ...)\n slices[:2] = no_flip\n elif dim_ordering == 'tf': # (..., input_depth, out_depth)\n slices[-2:] = no_flip\n else:\n raise ValueError('Invalid dim_ordering:', dim_ordering)\n\n return np.copy(kernel[slices])\n\n\ndef conv_output_length(input_length, filter_size,\n border_mode, stride, dilation=1):\n \"\"\"Determines output length of a convolution given input length.\n\n # Arguments\n input_length: integer.\n filter_size: integer.\n border_mode: one of \"same\", \"valid\", \"full\".\n stride: integer.\n dilation: dilation rate, integer.\n\n # Returns\n The output length (integer).\n \"\"\"\n if input_length is None:\n return None\n assert border_mode in {'same', 'valid', 'full'}\n dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1)\n if border_mode == 'same':\n output_length = input_length\n elif border_mode == 'valid':\n output_length = input_length - dilated_filter_size + 1\n elif border_mode == 'full':\n output_length = input_length + dilated_filter_size - 1\n return (output_length + stride - 1) // stride\n\n\ndef conv_input_length(output_length, filter_size, border_mode, stride):\n \"\"\"Determines input length of a convolution given output length.\n\n # Arguments\n output_length: integer.\n filter_size: integer.\n border_mode: one of \"same\", \"valid\", \"full\".\n stride: integer.\n\n # Returns\n The input length (integer).\n \"\"\"\n if output_length is None:\n return None\n assert border_mode in {'same', 'valid', 'full'}\n if border_mode == 'same':\n pad = filter_size // 2\n elif border_mode == 'valid':\n pad = 0\n elif border_mode == 'full':\n pad = filter_size - 1\n return (output_length - 1) * stride - 2 * pad + filter_size\n"},"repo_name":{"kind":"string","value":"keras-team_keras"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"ab3b93e8dd103f1d9729305825791a084c7c8493"}}},{"rowIdx":84,"cells":{"file_path":{"kind":"string","value":"keras/preprocessing/text.py"},"num_changed_lines":{"kind":"number","value":127,"string":"127"},"code":{"kind":"string","value":"# -*- coding: utf-8 -*-\n\"\"\"Utilities for text input preprocessing.\n\nMay benefit from a fast Cython rewrite.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport string\nimport sys\nimport numpy as np\nfrom six.moves import range\nfrom six.moves import zip\n\nif sys.version_info < (3,):\n maketrans = string.maketrans\nelse:\n maketrans = str.maketrans\n\n\ndef text_to_word_sequence(text,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True, split=\" \"):\n \"\"\"Converts a text to a sequence of word indices.\n\n # Arguments\n text: Input text (string).\n filters: Sequence of characters to filter out.\n lower: Whether to convert the input to lowercase.\n split: Sentence split marker (string).\n\n # Returns\n A list of integer word indices.\n \"\"\"\n if lower:\n text = text.lower()\n text = text.translate(maketrans(filters, split * len(filters)))\n seq = text.split(split)\n return [i for i in seq if i]\n\n\ndef one_hot(text, n,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True,\n split=' '):\n seq = text_to_word_sequence(text,\n filters=filters,\n lower=lower,\n split=split)\n return [(abs(hash(w)) % (n - 1) + 1) for w in seq]\n\n\nclass Tokenizer(object):\n \"\"\"Text tokenization utility class.\n\n This class allows to vectorize a text corpus, by turning each\n text into either a sequence of integers (each integer being the index\n of a token in a dictionary) or into a vector where the coefficient\n for each token could be binary, based on word count, based on tf-idf...\n\n # Arguments\n nb_words: the maximum number of words to keep, based\n on word frequency. Only the most common `nb_words` words will\n be kept.\n filters: a string where each element is a character that will be\n filtered from the texts. The default is all punctuation, plus\n tabs and line breaks, minus the `'` character.\n lower: boolean. Whether to convert the texts to lowercase.\n split: character or string to use for token splitting.\n char_level: if True, every character will be treated as a word.\n\n By default, all punctuation is removed, turning the texts into\n space-separated sequences of words\n (words maybe include the `'` character). These sequences are then\n split into lists of tokens. They will then be indexed or vectorized.\n\n `0` is a reserved index that won't be assigned to any word.\n \"\"\"\n\n def __init__(self, nb_words=None,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True,\n split=' ',\n char_level=False):\n self.word_counts = {}\n self.word_docs = {}\n self.filters = filters\n self.split = split\n self.lower = lower\n self.nb_words = nb_words\n self.document_count = 0\n self.char_level = char_level\n\n def fit_on_texts(self, texts):\n \"\"\"Updates internal vocabulary based on a list of texts.\n\n Required before using `texts_to_sequences` or `texts_to_matrix`.\n\n # Arguments\n texts: can be a list of strings,\n or a generator of strings (for memory-efficiency)\n \"\"\"\n self.document_count = 0\n for text in texts:\n self.document_count += 1\n seq = text if self.char_level else text_to_word_sequence(text,\n self.filters,\n self.lower,\n self.split)\n for w in seq:\n if w in self.word_counts:\n self.word_counts[w] += 1\n else:\n self.word_counts[w] = 1\n for w in set(seq):\n if w in self.word_docs:\n self.word_docs[w] += 1\n else:\n self.word_docs[w] = 1\n\n wcounts = list(self.word_counts.items())\n wcounts.sort(key=lambda x: x[1], reverse=True)\n sorted_voc = [wc[0] for wc in wcounts]\n # note that index 0 is reserved, never assigned to an existing word\n self.word_index = dict(list(zip(sorted_voc, list(range(1, len(sorted_voc) + 1)))))\n\n self.index_docs = {}\n for w, c in list(self.word_docs.items()):\n self.index_docs[self.word_index[w]] = c\n\n def fit_on_sequences(self, sequences):\n \"\"\"Updates internal vocabulary based on a list of sequences.\n\n Required before using `sequences_to_matrix`\n (if `fit_on_texts` was never called).\n\n # Arguments\n sequences: A list of sequence.\n A \"sequence\" is a list of integer word indices.\n \"\"\"\n self.document_count = len(sequences)\n self.index_docs = {}\n for seq in sequences:\n seq = set(seq)\n for i in seq:\n if i not in self.index_docs:\n self.index_docs[i] = 1\n else:\n self.index_docs[i] += 1\n\n def texts_to_sequences(self, texts):\n \"\"\"Transforms each text in texts in a sequence of integers.\n\n Only top \"nb_words\" most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n\n # Arguments\n texts: A list of texts (strings).\n\n # Returns\n A list of sequences.\n \"\"\"\n res = []\n for vect in self.texts_to_sequences_generator(texts):\n res.append(vect)\n return res\n\n def texts_to_sequences_generator(self, texts):\n \"\"\"Transforms each text in texts in a sequence of integers.\n\n Only top \"nb_words\" most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n\n # Arguments\n texts: A list of texts (strings).\n\n # Yields\n Yields individual sequences.\n \"\"\"\n nb_words = self.nb_words\n for text in texts:\n seq = text if self.char_level else text_to_word_sequence(text,\n self.filters,\n self.lower,\n self.split)\n vect = []\n for w in seq:\n i = self.word_index.get(w)\n if i is not None:\n if nb_words and i >= nb_words:\n continue\n else:\n vect.append(i)\n yield vect\n\n def texts_to_matrix(self, texts, mode='binary'):\n \"\"\"Convert a list of texts to a Numpy matrix.\n\n # Arguments\n texts: list of strings.\n mode: one of \"binary\", \"count\", \"tfidf\", \"freq\".\n\n # Returns\n A Numpy matrix.\n \"\"\"\n sequences = self.texts_to_sequences(texts)\n return self.sequences_to_matrix(sequences, mode=mode)\n\n def sequences_to_matrix(self, sequences, mode='binary'):\n \"\"\"Converts a list of sequences into a Numpy matrix.\n\n # Arguments\n sequences: list of sequences\n (a sequence is a list of integer word indices).\n mode: one of \"binary\", \"count\", \"tfidf\", \"freq\"\n\n # Returns\n A Numpy matrix.\n\n # Raises\n ValueError: In case of invalid `mode` argument,\n or if the Tokenizer requires to be fit to sample data.\n \"\"\"\n if not self.nb_words:\n if self.word_index:\n nb_words = len(self.word_index) + 1\n else:\n raise ValueError('Specify a dimension (nb_words argument), '\n 'or fit on some text data first.')\n else:\n nb_words = self.nb_words\n\n if mode == 'tfidf' and not self.document_count:\n raise ValueError('Fit the Tokenizer on some data '\n 'before using tfidf mode.')\n\n x = np.zeros((len(sequences), nb_words))\n for i, seq in enumerate(sequences):\n if not seq:\n continue\n counts = {}\n for j in seq:\n if j >= nb_words:\n continue\n if j not in counts:\n counts[j] = 1.\n else:\n counts[j] += 1\n for j, c in list(counts.items()):\n if mode == 'count':\n x[i][j] = c\n elif mode == 'freq':\n x[i][j] = c / len(seq)\n elif mode == 'binary':\n x[i][j] = 1\n elif mode == 'tfidf':\n # Use weighting scheme 2 in\n # https://en.wikipedia.org/wiki/Tf%E2%80%93idf\n tf = 1 + np.log(c)\n idf = np.log(1 + self.document_count /\n (1 + self.index_docs.get(j, 0)))\n x[i][j] = tf * idf\n else:\n raise ValueError('Unknown vectorization mode:', mode)\n return x\n"},"repo_name":{"kind":"string","value":"keras-team_keras"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"ab3b93e8dd103f1d9729305825791a084c7c8493"}}},{"rowIdx":85,"cells":{"file_path":{"kind":"string","value":"tests/keras/test_multiprocessing.py"},"num_changed_lines":{"kind":"number","value":96,"string":"96"},"code":{"kind":"string","value":"from __future__ import print_function\nimport pytest\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.utils.test_utils import keras_test\n\n\n@keras_test\ndef test_multiprocessing_training():\n\n reached_end = False\n\n arr_data = np.random.randint(0, 256, (500, 2))\n arr_labels = np.random.randint(0, 2, 500)\n\n def myGenerator():\n\n batch_size = 32\n n_samples = 500\n\n while True:\n batch_index = np.random.randint(0, n_samples - batch_size)\n start = batch_index\n end = start + batch_size\n X = arr_data[start: end]\n y = arr_labels[start: end]\n yield X, y\n\n # Build a NN\n model = Sequential()\n model.add(Dense(1, input_shape=(2, )))\n model.compile(loss='mse', optimizer='adadelta')\n\n model.fit_generator(myGenerator(),\n samples_per_epoch=320,\n nb_epoch=1,\n verbose=1,\n max_q_size=10,\n nb_worker=4,\n pickle_safe=True)\n\n model.fit_generator(myGenerator(),\n samples_per_epoch=320,\n nb_epoch=1,\n verbose=1,\n max_q_size=10,\n pickle_safe=False)\n\n reached_end = True\n\n assert reached_end\n\n\n@keras_test\ndef test_multiprocessing_training_fromfile():\n\n reached_end = False\n\n arr_data = np.random.randint(0, 256, (500, 2))\n arr_labels = np.random.randint(0, 2, 500)\n np.savez(\"data.npz\", **{\"data\": arr_data, \"labels\": arr_labels})\n\n def myGenerator():\n\n batch_size = 32\n n_samples = 500\n\n arr = np.load(\"data.npz\")\n\n while True:\n batch_index = np.random.randint(0, n_samples - batch_size)\n start = batch_index\n end = start + batch_size\n X = arr[\"data\"][start: end]\n y = arr[\"labels\"][start: end]\n yield X, y\n\n # Build a NN\n model = Sequential()\n model.add(Dense(1, input_shape=(2, )))\n model.compile(loss='mse', optimizer='adadelta')\n\n model.fit_generator(myGenerator(),\n samples_per_epoch=320,\n nb_epoch=1,\n verbose=1,\n max_q_size=10,\n nb_worker=2,\n pickle_safe=True)\n\n model.fit_generator(myGenerator(),\n samples_per_epoch=320,\n nb_epoch=1,\n verbose=1,\n max_q_size=10,\n pickle_safe=False)\n reached_end = True\n\n assert reached_end\n\n\n@keras_test\ndef test_multiprocessing_predicting():\n\n reached_end = False\n\n arr_data = np.random.randint(0, 256, (500, 2))\n\n def myGenerator():\n\n batch_size = 32\n n_samples = 500\n\n while True:\n batch_index = np.random.randint(0, n_samples - batch_size)\n start = batch_index\n end = start + batch_size\n X = arr_data[start: end]\n yield X\n\n # Build a NN\n model = Sequential()\n model.add(Dense(1, input_shape=(2, )))\n model.compile(loss='mse', optimizer='adadelta')\n model.predict_generator(myGenerator(),\n val_samples=320,\n max_q_size=10,\n nb_worker=2,\n pickle_safe=True)\n model.predict_generator(myGenerator(),\n val_samples=320,\n max_q_size=10,\n pickle_safe=False)\n reached_end = True\n\n assert reached_end\n\n\n@keras_test\ndef test_multiprocessing_evaluating():\n\n reached_end = False\n\n arr_data = np.random.randint(0, 256, (500, 2))\n arr_labels = np.random.randint(0, 2, 500)\n\n def myGenerator():\n\n batch_size = 32\n n_samples = 500\n\n while True:\n batch_index = np.random.randint(0, n_samples - batch_size)\n start = batch_index\n end = start + batch_size\n X = arr_data[start: end]\n y = arr_labels[start: end]\n yield X, y\n\n # Build a NN\n model = Sequential()\n model.add(Dense(1, input_shape=(2, )))\n model.compile(loss='mse', optimizer='adadelta')\n\n model.evaluate_generator(myGenerator(),\n val_samples=320,\n max_q_size=10,\n nb_worker=2,\n pickle_safe=True)\n model.evaluate_generator(myGenerator(),\n val_samples=320,\n max_q_size=10,\n pickle_safe=False)\n reached_end = True\n\n assert reached_end\n\n\n@keras_test\ndef test_multiprocessing_fit_error():\n\n batch_size = 32\n good_batches = 5\n\n def myGenerator():\n \"\"\"Raises an exception after a few good batches\"\"\"\n for i in range(good_batches):\n yield (np.random.randint(batch_size, 256, (500, 2)),\n np.random.randint(batch_size, 2, 500))\n raise RuntimeError\n\n model = Sequential()\n model.add(Dense(1, input_shape=(2, )))\n model.compile(loss='mse', optimizer='adadelta')\n\n samples = batch_size * (good_batches + 1)\n\n with pytest.raises(Exception):\n model.fit_generator(\n myGenerator(), samples, 1,\n nb_worker=4, pickle_safe=True,\n )\n\n with pytest.raises(Exception):\n model.fit_generator(\n myGenerator(), samples, 1,\n pickle_safe=False,\n )\n\n\n@keras_test\ndef test_multiprocessing_evaluate_error():\n\n batch_size = 32\n good_batches = 5\n\n def myGenerator():\n \"\"\"Raises an exception after a few good batches\"\"\"\n for i in range(good_batches):\n yield (np.random.randint(batch_size, 256, (500, 2)),\n np.random.randint(batch_size, 2, 500))\n raise RuntimeError\n\n model = Sequential()\n model.add(Dense(1, input_shape=(2, )))\n model.compile(loss='mse', optimizer='adadelta')\n\n samples = batch_size * (good_batches + 1)\n\n with pytest.raises(Exception):\n model.evaluate_generator(\n myGenerator(), samples, 1,\n nb_worker=4, pickle_safe=True,\n )\n\n with pytest.raises(Exception):\n model.evaluate_generator(\n myGenerator(), samples, 1,\n pickle_safe=False,\n )\n\n\n@keras_test\ndef test_multiprocessing_predict_error():\n\n batch_size = 32\n good_batches = 5\n\n def myGenerator():\n \"\"\"Raises an exception after a few good batches\"\"\"\n for i in range(good_batches):\n yield (np.random.randint(batch_size, 256, (500, 2)),\n np.random.randint(batch_size, 2, 500))\n raise RuntimeError\n\n model = Sequential()\n model.add(Dense(1, input_shape=(2, )))\n model.compile(loss='mse', optimizer='adadelta')\n\n samples = batch_size * (good_batches + 1)\n\n with pytest.raises(Exception):\n model.predict_generator(\n myGenerator(), samples, 1,\n nb_worker=4, pickle_safe=True,\n )\n\n with pytest.raises(Exception):\n model.predict_generator(\n myGenerator(), samples, 1,\n pickle_safe=False,\n )\n\n\nif __name__ == '__main__':\n\n pytest.main([__file__])\n"},"repo_name":{"kind":"string","value":"keras-team_keras"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"ab3b93e8dd103f1d9729305825791a084c7c8493"}}},{"rowIdx":86,"cells":{"file_path":{"kind":"string","value":"keras/datasets/cifar100.py"},"num_changed_lines":{"kind":"number","value":16,"string":"16"},"code":{"kind":"string","value":"from __future__ import absolute_import\nfrom .cifar import load_batch\nfrom ..utils.data_utils import get_file\nfrom .. import backend as K\nimport numpy as np\nimport os\n\n\ndef load_data(label_mode='fine'):\n \"\"\"Loads CIFAR100 dataset.\n\n # Arguments\n label_mode: one of \"fine\", \"coarse\".\n\n # Returns\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n\n # Raises\n ValueError: in case of invalid `label_mode`.\n \"\"\"\n if label_mode not in ['fine', 'coarse']:\n raise ValueError('label_mode must be one of \"fine\" \"coarse\".')\n\n dirname = 'cifar-100-python'\n origin = 'http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz'\n path = get_file(dirname, origin=origin, untar=True)\n\n fpath = os.path.join(path, 'train')\n x_train, y_train = load_batch(fpath, label_key=label_mode + '_labels')\n\n fpath = os.path.join(path, 'test')\n x_test, y_test = load_batch(fpath, label_key=label_mode + '_labels')\n\n y_train = np.reshape(y_train, (len(y_train), 1))\n y_test = np.reshape(y_test, (len(y_test), 1))\n\n if K.image_dim_ordering() == 'tf':\n x_train = x_train.transpose(0, 2, 3, 1)\n x_test = x_test.transpose(0, 2, 3, 1)\n\n return (x_train, y_train), (x_test, y_test)\n"},"repo_name":{"kind":"string","value":"keras-team_keras"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"ab3b93e8dd103f1d9729305825791a084c7c8493"}}},{"rowIdx":87,"cells":{"file_path":{"kind":"string","value":"keras/datasets/cifar.py"},"num_changed_lines":{"kind":"number","value":13,"string":"13"},"code":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nimport sys\nfrom six.moves import cPickle\n\n\ndef load_batch(fpath, label_key='labels'):\n \"\"\"Internal utility for parsing CIFAR data.\n\n # Arguments\n fpath: path the file to parse.\n label_key: key for label data in the retrieve\n dictionary.\n\n # Returns\n A tuple `(data, labels)`.\n \"\"\"\n f = open(fpath, 'rb')\n if sys.version_info < (3,):\n d = cPickle.load(f)\n else:\n d = cPickle.load(f, encoding='bytes')\n # decode utf8\n d_decoded = {}\n for k, v in d.items():\n d_decoded[k.decode('utf8')] = v\n d = d_decoded\n f.close()\n data = d['data']\n labels = d[label_key]\n\n data = data.reshape(data.shape[0], 3, 32, 32)\n return data, labels\n"},"repo_name":{"kind":"string","value":"keras-team_keras"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"ab3b93e8dd103f1d9729305825791a084c7c8493"}}},{"rowIdx":88,"cells":{"file_path":{"kind":"string","value":"tests/keras/utils/test_generic_utils.py"},"num_changed_lines":{"kind":"number","value":30,"string":"30"},"code":{"kind":"string","value":"import pytest\nimport keras\nfrom keras import backend as K\nfrom keras.utils.generic_utils import custom_object_scope, get_custom_objects, get_from_module\n\n\ndef test_custom_object_scope_adds_objects():\n get_custom_objects().clear()\n assert (len(get_custom_objects()) == 0)\n with custom_object_scope({\"Test1\": object, \"Test2\": object}, {\"Test3\": object}):\n assert (len(get_custom_objects()) == 3)\n assert (len(get_custom_objects()) == 0)\n\n\nclass CustomObject(object):\n def __init__(self):\n pass\n\n\ndef test_get_from_module_uses_custom_object():\n get_custom_objects().clear()\n assert (get_from_module(\"CustomObject\", globals(), \"test_generic_utils\") == CustomObject)\n with pytest.raises(ValueError):\n get_from_module(\"TestObject\", globals(), \"test_generic_utils\")\n with custom_object_scope({\"TestObject\": CustomObject}):\n assert (get_from_module(\"TestObject\", globals(), \"test_generic_utils\") == CustomObject)\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n"},"repo_name":{"kind":"string","value":"keras-team_keras"},"commit_date":{"kind":"string","value":"2017-01-28"},"sha":{"kind":"string","value":"ab3b93e8dd103f1d9729305825791a084c7c8493"}}},{"rowIdx":89,"cells":{"file_path":{"kind":"string","value":"fuzz/server.c"},"num_changed_lines":{"kind":"number","value":345,"string":"345"},"code":{"kind":"string","value":"/*\n * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.\n *\n * Licensed under the OpenSSL licenses, (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * https://www.openssl.org/source/license.html\n * or in the file LICENSE in the source distribution.\n */\n\n/* Shamelessly copied from BoringSSL and converted to C. */\n\n/* Test first part of SSL server handshake. */\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"fuzzer.h\"\n\nstatic const uint8_t kCertificateDER[] = {\n 0x30, 0x82, 0x02, 0xff, 0x30, 0x82, 0x01, 0xe7, 0xa0, 0x03, 0x02, 0x01,\n 0x02, 0x02, 0x11, 0x00, 0xb1, 0x84, 0xee, 0x34, 0x99, 0x98, 0x76, 0xfb,\n 0x6f, 0xb2, 0x15, 0xc8, 0x47, 0x79, 0x05, 0x9b, 0x30, 0x0d, 0x06, 0x09,\n 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30,\n 0x12, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x07,\n 0x41, 0x63, 0x6d, 0x65, 0x20, 0x43, 0x6f, 0x30, 0x1e, 0x17, 0x0d, 0x31,\n 0x35, 0x31, 0x31, 0x30, 0x37, 0x30, 0x30, 0x32, 0x34, 0x35, 0x36, 0x5a,\n 0x17, 0x0d, 0x31, 0x36, 0x31, 0x31, 0x30, 0x36, 0x30, 0x30, 0x32, 0x34,\n 0x35, 0x36, 0x5a, 0x30, 0x12, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55,\n 0x04, 0x0a, 0x13, 0x07, 0x41, 0x63, 0x6d, 0x65, 0x20, 0x43, 0x6f, 0x30,\n 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,\n 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30,\n 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xce, 0x47, 0xcb, 0x11,\n 0xbb, 0xd2, 0x9d, 0x8e, 0x9e, 0xd2, 0x1e, 0x14, 0xaf, 0xc7, 0xea, 0xb6,\n 0xc9, 0x38, 0x2a, 0x6f, 0xb3, 0x7e, 0xfb, 0xbc, 0xfc, 0x59, 0x42, 0xb9,\n 0x56, 0xf0, 0x4c, 0x3f, 0xf7, 0x31, 0x84, 0xbe, 0xac, 0x03, 0x9e, 0x71,\n 0x91, 0x85, 0xd8, 0x32, 0xbd, 0x00, 0xea, 0xac, 0x65, 0xf6, 0x03, 0xc8,\n 0x0f, 0x8b, 0xfd, 0x6e, 0x58, 0x88, 0x04, 0x41, 0x92, 0x74, 0xa6, 0x57,\n 0x2e, 0x8e, 0x88, 0xd5, 0x3d, 0xda, 0x14, 0x3e, 0x63, 0x88, 0x22, 0xe3,\n 0x53, 0xe9, 0xba, 0x39, 0x09, 0xac, 0xfb, 0xd0, 0x4c, 0xf2, 0x3c, 0x20,\n 0xd6, 0x97, 0xe6, 0xed, 0xf1, 0x62, 0x1e, 0xe5, 0xc9, 0x48, 0xa0, 0xca,\n 0x2e, 0x3c, 0x14, 0x5a, 0x82, 0xd4, 0xed, 0xb1, 0xe3, 0x43, 0xc1, 0x2a,\n 0x59, 0xa5, 0xb9, 0xc8, 0x48, 0xa7, 0x39, 0x23, 0x74, 0xa7, 0x37, 0xb0,\n 0x6f, 0xc3, 0x64, 0x99, 0x6c, 0xa2, 0x82, 0xc8, 0xf6, 0xdb, 0x86, 0x40,\n 0xce, 0xd1, 0x85, 0x9f, 0xce, 0x69, 0xf4, 0x15, 0x2a, 0x23, 0xca, 0xea,\n 0xb7, 0x7b, 0xdf, 0xfb, 0x43, 0x5f, 0xff, 0x7a, 0x49, 0x49, 0x0e, 0xe7,\n 0x02, 0x51, 0x45, 0x13, 0xe8, 0x90, 0x64, 0x21, 0x0c, 0x26, 0x2b, 0x5d,\n 0xfc, 0xe4, 0xb5, 0x86, 0x89, 0x43, 0x22, 0x4c, 0xf3, 0x3b, 0xf3, 0x09,\n 0xc4, 0xa4, 0x10, 0x80, 0xf2, 0x46, 0xe2, 0x46, 0x8f, 0x76, 0x50, 0xbf,\n 0xaf, 0x2b, 0x90, 0x1b, 0x78, 0xc7, 0xcf, 0xc1, 0x77, 0xd0, 0xfb, 0xa9,\n 0xfb, 0xc9, 0x66, 0x5a, 0xc5, 0x9b, 0x31, 0x41, 0x67, 0x01, 0xbe, 0x33,\n 0x10, 0xba, 0x05, 0x58, 0xed, 0x76, 0x53, 0xde, 0x5d, 0xc1, 0xe8, 0xbb,\n 0x9f, 0xf1, 0xcd, 0xfb, 0xdf, 0x64, 0x7f, 0xd7, 0x18, 0xab, 0x0f, 0x94,\n 0x28, 0x95, 0x4a, 0xcc, 0x6a, 0xa9, 0x50, 0xc7, 0x05, 0x47, 0x10, 0x41,\n 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x0e, 0x06,\n 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x05,\n 0xa0, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x0c, 0x30, 0x0a,\n 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x0c,\n 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00,\n 0x30, 0x19, 0x06, 0x03, 0x55, 0x1d, 0x11, 0x04, 0x12, 0x30, 0x10, 0x82,\n 0x0e, 0x66, 0x75, 0x7a, 0x7a, 0x2e, 0x62, 0x6f, 0x72, 0x69, 0x6e, 0x67,\n 0x73, 0x73, 0x6c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,\n 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x92,\n 0xde, 0xef, 0x96, 0x06, 0x7b, 0xff, 0x71, 0x7d, 0x4e, 0xa0, 0x7d, 0xae,\n 0xb8, 0x22, 0xb4, 0x2c, 0xf7, 0x96, 0x9c, 0x37, 0x1d, 0x8f, 0xe7, 0xd9,\n 0x47, 0xff, 0x3f, 0xe9, 0x35, 0x95, 0x0e, 0xdd, 0xdc, 0x7f, 0xc8, 0x8a,\n 0x1e, 0x36, 0x1d, 0x38, 0x47, 0xfc, 0x76, 0xd2, 0x1f, 0x98, 0xa1, 0x36,\n 0xac, 0xc8, 0x70, 0x38, 0x0a, 0x3d, 0x51, 0x8d, 0x0f, 0x03, 0x1b, 0xef,\n 0x62, 0xa1, 0xcb, 0x2b, 0x4a, 0x8c, 0x12, 0x2b, 0x54, 0x50, 0x9a, 0x6b,\n 0xfe, 0xaf, 0xd9, 0xf6, 0xbf, 0x58, 0x11, 0x58, 0x5e, 0xe5, 0x86, 0x1e,\n 0x3b, 0x6b, 0x30, 0x7e, 0x72, 0x89, 0xe8, 0x6b, 0x7b, 0xb7, 0xaf, 0xef,\n 0x8b, 0xa9, 0x3e, 0xb0, 0xcd, 0x0b, 0xef, 0xb0, 0x0c, 0x96, 0x2b, 0xc5,\n 0x3b, 0xd5, 0xf1, 0xc2, 0xae, 0x3a, 0x60, 0xd9, 0x0f, 0x75, 0x37, 0x55,\n 0x4d, 0x62, 0xd2, 0xed, 0x96, 0xac, 0x30, 0x6b, 0xda, 0xa1, 0x48, 0x17,\n 0x96, 0x23, 0x85, 0x9a, 0x57, 0x77, 0xe9, 0x22, 0xa2, 0x37, 0x03, 0xba,\n 0x49, 0x77, 0x40, 0x3b, 0x76, 0x4b, 0xda, 0xc1, 0x04, 0x57, 0x55, 0x34,\n 0x22, 0x83, 0x45, 0x29, 0xab, 0x2e, 0x11, 0xff, 0x0d, 0xab, 0x55, 0xb1,\n 0xa7, 0x58, 0x59, 0x05, 0x25, 0xf9, 0x1e, 0x3d, 0xb7, 0xac, 0x04, 0x39,\n 0x2c, 0xf9, 0xaf, 0xb8, 0x68, 0xfb, 0x8e, 0x35, 0x71, 0x32, 0xff, 0x70,\n 0xe9, 0x46, 0x6d, 0x5c, 0x06, 0x90, 0x88, 0x23, 0x48, 0x0c, 0x50, 0xeb,\n 0x0a, 0xa9, 0xae, 0xe8, 0xfc, 0xbe, 0xa5, 0x76, 0x94, 0xd7, 0x64, 0x22,\n 0x38, 0x98, 0x17, 0xa4, 0x3a, 0xa7, 0x59, 0x9f, 0x1d, 0x3b, 0x75, 0x90,\n 0x1a, 0x81, 0xef, 0x19, 0xfb, 0x2b, 0xb7, 0xa7, 0x64, 0x61, 0x22, 0xa4,\n 0x6f, 0x7b, 0xfa, 0x58, 0xbb, 0x8c, 0x4e, 0x77, 0x67, 0xd0, 0x5d, 0x58,\n 0x76, 0x8a, 0xbb,\n};\n\nstatic const uint8_t kRSAPrivateKeyDER[] = {\n 0x30, 0x82, 0x04, 0xa5, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00,\n 0xce, 0x47, 0xcb, 0x11, 0xbb, 0xd2, 0x9d, 0x8e, 0x9e, 0xd2, 0x1e, 0x14,\n 0xaf, 0xc7, 0xea, 0xb6, 0xc9, 0x38, 0x2a, 0x6f, 0xb3, 0x7e, 0xfb, 0xbc,\n 0xfc, 0x59, 0x42, 0xb9, 0x56, 0xf0, 0x4c, 0x3f, 0xf7, 0x31, 0x84, 0xbe,\n 0xac, 0x03, 0x9e, 0x71, 0x91, 0x85, 0xd8, 0x32, 0xbd, 0x00, 0xea, 0xac,\n 0x65, 0xf6, 0x03, 0xc8, 0x0f, 0x8b, 0xfd, 0x6e, 0x58, 0x88, 0x04, 0x41,\n 0x92, 0x74, 0xa6, 0x57, 0x2e, 0x8e, 0x88, 0xd5, 0x3d, 0xda, 0x14, 0x3e,\n 0x63, 0x88, 0x22, 0xe3, 0x53, 0xe9, 0xba, 0x39, 0x09, 0xac, 0xfb, 0xd0,\n 0x4c, 0xf2, 0x3c, 0x20, 0xd6, 0x97, 0xe6, 0xed, 0xf1, 0x62, 0x1e, 0xe5,\n 0xc9, 0x48, 0xa0, 0xca, 0x2e, 0x3c, 0x14, 0x5a, 0x82, 0xd4, 0xed, 0xb1,\n 0xe3, 0x43, 0xc1, 0x2a, 0x59, 0xa5, 0xb9, 0xc8, 0x48, 0xa7, 0x39, 0x23,\n 0x74, 0xa7, 0x37, 0xb0, 0x6f, 0xc3, 0x64, 0x99, 0x6c, 0xa2, 0x82, 0xc8,\n 0xf6, 0xdb, 0x86, 0x40, 0xce, 0xd1, 0x85, 0x9f, 0xce, 0x69, 0xf4, 0x15,\n 0x2a, 0x23, 0xca, 0xea, 0xb7, 0x7b, 0xdf, 0xfb, 0x43, 0x5f, 0xff, 0x7a,\n 0x49, 0x49, 0x0e, 0xe7, 0x02, 0x51, 0x45, 0x13, 0xe8, 0x90, 0x64, 0x21,\n 0x0c, 0x26, 0x2b, 0x5d, 0xfc, 0xe4, 0xb5, 0x86, 0x89, 0x43, 0x22, 0x4c,\n 0xf3, 0x3b, 0xf3, 0x09, 0xc4, 0xa4, 0x10, 0x80, 0xf2, 0x46, 0xe2, 0x46,\n 0x8f, 0x76, 0x50, 0xbf, 0xaf, 0x2b, 0x90, 0x1b, 0x78, 0xc7, 0xcf, 0xc1,\n 0x77, 0xd0, 0xfb, 0xa9, 0xfb, 0xc9, 0x66, 0x5a, 0xc5, 0x9b, 0x31, 0x41,\n 0x67, 0x01, 0xbe, 0x33, 0x10, 0xba, 0x05, 0x58, 0xed, 0x76, 0x53, 0xde,\n 0x5d, 0xc1, 0xe8, 0xbb, 0x9f, 0xf1, 0xcd, 0xfb, 0xdf, 0x64, 0x7f, 0xd7,\n 0x18, 0xab, 0x0f, 0x94, 0x28, 0x95, 0x4a, 0xcc, 0x6a, 0xa9, 0x50, 0xc7,\n 0x05, 0x47, 0x10, 0x41, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01,\n 0x01, 0x00, 0xa8, 0x47, 0xb9, 0x4a, 0x06, 0x47, 0x93, 0x71, 0x3d, 0xef,\n 0x7b, 0xca, 0xb4, 0x7c, 0x0a, 0xe6, 0x82, 0xd0, 0xe7, 0x0d, 0xa9, 0x08,\n 0xf6, 0xa4, 0xfd, 0xd8, 0x73, 0xae, 0x6f, 0x56, 0x29, 0x5e, 0x25, 0x72,\n 0xa8, 0x30, 0x44, 0x73, 0xcf, 0x56, 0x26, 0xb9, 0x61, 0xde, 0x42, 0x81,\n 0xf4, 0xf0, 0x1f, 0x5d, 0xcb, 0x47, 0xf2, 0x26, 0xe9, 0xe0, 0x93, 0x28,\n 0xa3, 0x10, 0x3b, 0x42, 0x1e, 0x51, 0x11, 0x12, 0x06, 0x5e, 0xaf, 0xce,\n 0xb0, 0xa5, 0x14, 0xdd, 0x82, 0x58, 0xa1, 0xa4, 0x12, 0xdf, 0x65, 0x1d,\n 0x51, 0x70, 0x64, 0xd5, 0x58, 0x68, 0x11, 0xa8, 0x6a, 0x23, 0xc2, 0xbf,\n 0xa1, 0x25, 0x24, 0x47, 0xb3, 0xa4, 0x3c, 0x83, 0x96, 0xb7, 0x1f, 0xf4,\n 0x44, 0xd4, 0xd1, 0xe9, 0xfc, 0x33, 0x68, 0x5e, 0xe2, 0x68, 0x99, 0x9c,\n 0x91, 0xe8, 0x72, 0xc9, 0xd7, 0x8c, 0x80, 0x20, 0x8e, 0x77, 0x83, 0x4d,\n 0xe4, 0xab, 0xf9, 0x74, 0xa1, 0xdf, 0xd3, 0xc0, 0x0d, 0x5b, 0x05, 0x51,\n 0xc2, 0x6f, 0xb2, 0x91, 0x02, 0xec, 0xc0, 0x02, 0x1a, 0x5c, 0x91, 0x05,\n 0xf1, 0xe3, 0xfa, 0x65, 0xc2, 0xad, 0x24, 0xe6, 0xe5, 0x3c, 0xb6, 0x16,\n 0xf1, 0xa1, 0x67, 0x1a, 0x9d, 0x37, 0x56, 0xbf, 0x01, 0xd7, 0x3b, 0x35,\n 0x30, 0x57, 0x73, 0xf4, 0xf0, 0x5e, 0xa7, 0xe8, 0x0a, 0xc1, 0x94, 0x17,\n 0xcf, 0x0a, 0xbd, 0xf5, 0x31, 0xa7, 0x2d, 0xf7, 0xf5, 0xd9, 0x8c, 0xc2,\n 0x01, 0xbd, 0xda, 0x16, 0x8e, 0xb9, 0x30, 0x40, 0xa6, 0x6e, 0xbd, 0xcd,\n 0x4d, 0x84, 0x67, 0x4e, 0x0b, 0xce, 0xd5, 0xef, 0xf8, 0x08, 0x63, 0x02,\n 0xc6, 0xc7, 0xf7, 0x67, 0x92, 0xe2, 0x23, 0x9d, 0x27, 0x22, 0x1d, 0xc6,\n 0x67, 0x5e, 0x66, 0xbf, 0x03, 0xb8, 0xa9, 0x67, 0xd4, 0x39, 0xd8, 0x75,\n 0xfa, 0xe8, 0xed, 0x56, 0xb8, 0x81, 0x02, 0x81, 0x81, 0x00, 0xf7, 0x46,\n 0x68, 0xc6, 0x13, 0xf8, 0xba, 0x0f, 0x83, 0xdb, 0x05, 0xa8, 0x25, 0x00,\n 0x70, 0x9c, 0x9e, 0x8b, 0x12, 0x34, 0x0d, 0x96, 0xcf, 0x0d, 0x98, 0x9b,\n 0x8d, 0x9c, 0x96, 0x78, 0xd1, 0x3c, 0x01, 0x8c, 0xb9, 0x35, 0x5c, 0x20,\n 0x42, 0xb4, 0x38, 0xe3, 0xd6, 0x54, 0xe7, 0x55, 0xd6, 0x26, 0x8a, 0x0c,\n 0xf6, 0x1f, 0xe0, 0x04, 0xc1, 0x22, 0x42, 0x19, 0x61, 0xc4, 0x94, 0x7c,\n 0x07, 0x2e, 0x80, 0x52, 0xfe, 0x8d, 0xe6, 0x92, 0x3a, 0x91, 0xfe, 0x72,\n 0x99, 0xe1, 0x2a, 0x73, 0x76, 0xb1, 0x24, 0x20, 0x67, 0xde, 0x28, 0xcb,\n 0x0e, 0xe6, 0x52, 0xb5, 0xfa, 0xfb, 0x8b, 0x1e, 0x6a, 0x1d, 0x09, 0x26,\n 0xb9, 0xa7, 0x61, 0xba, 0xf8, 0x79, 0xd2, 0x66, 0x57, 0x28, 0xd7, 0x31,\n 0xb5, 0x0b, 0x27, 0x19, 0x1e, 0x6f, 0x46, 0xfc, 0x54, 0x95, 0xeb, 0x78,\n 0x01, 0xb6, 0xd9, 0x79, 0x5a, 0x4d, 0x02, 0x81, 0x81, 0x00, 0xd5, 0x8f,\n 0x16, 0x53, 0x2f, 0x57, 0x93, 0xbf, 0x09, 0x75, 0xbf, 0x63, 0x40, 0x3d,\n 0x27, 0xfd, 0x23, 0x21, 0xde, 0x9b, 0xe9, 0x73, 0x3f, 0x49, 0x02, 0xd2,\n 0x38, 0x96, 0xcf, 0xc3, 0xba, 0x92, 0x07, 0x87, 0x52, 0xa9, 0x35, 0xe3,\n 0x0c, 0xe4, 0x2f, 0x05, 0x7b, 0x37, 0xa5, 0x40, 0x9c, 0x3b, 0x94, 0xf7,\n 0xad, 0xa0, 0xee, 0x3a, 0xa8, 0xfb, 0x1f, 0x11, 0x1f, 0xd8, 0x9a, 0x80,\n 0x42, 0x3d, 0x7f, 0xa4, 0xb8, 0x9a, 0xaa, 0xea, 0x72, 0xc1, 0xe3, 0xed,\n 0x06, 0x60, 0x92, 0x37, 0xf9, 0xba, 0xfb, 0x9e, 0xed, 0x05, 0xa6, 0xd4,\n 0x72, 0x68, 0x4f, 0x63, 0xfe, 0xd6, 0x10, 0x0d, 0x4f, 0x0a, 0x93, 0xc6,\n 0xb9, 0xd7, 0xaf, 0xfd, 0xd9, 0x57, 0x7d, 0xcb, 0x75, 0xe8, 0x93, 0x2b,\n 0xae, 0x4f, 0xea, 0xd7, 0x30, 0x0b, 0x58, 0x44, 0x82, 0x0f, 0x84, 0x5d,\n 0x62, 0x11, 0x78, 0xea, 0x5f, 0xc5, 0x02, 0x81, 0x81, 0x00, 0x82, 0x0c,\n 0xc1, 0xe6, 0x0b, 0x72, 0xf1, 0x48, 0x5f, 0xac, 0xbd, 0x98, 0xe5, 0x7d,\n 0x09, 0xbd, 0x15, 0x95, 0x47, 0x09, 0xa1, 0x6c, 0x03, 0x91, 0xbf, 0x05,\n 0x70, 0xc1, 0x3e, 0x52, 0x64, 0x99, 0x0e, 0xa7, 0x98, 0x70, 0xfb, 0xf6,\n 0xeb, 0x9e, 0x25, 0x9d, 0x8e, 0x88, 0x30, 0xf2, 0xf0, 0x22, 0x6c, 0xd0,\n 0xcc, 0x51, 0x8f, 0x5c, 0x70, 0xc7, 0x37, 0xc4, 0x69, 0xab, 0x1d, 0xfc,\n 0xed, 0x3a, 0x03, 0xbb, 0xa2, 0xad, 0xb6, 0xea, 0x89, 0x6b, 0x67, 0x4b,\n 0x96, 0xaa, 0xd9, 0xcc, 0xc8, 0x4b, 0xfa, 0x18, 0x21, 0x08, 0xb2, 0xa3,\n 0xb9, 0x3e, 0x61, 0x99, 0xdc, 0x5a, 0x97, 0x9c, 0x73, 0x6a, 0xb9, 0xf9,\n 0x68, 0x03, 0x24, 0x5f, 0x55, 0x77, 0x9c, 0xb4, 0xbe, 0x7a, 0x78, 0x53,\n 0x68, 0x48, 0x69, 0x53, 0xc8, 0xb1, 0xf5, 0xbf, 0x98, 0x2d, 0x11, 0x1e,\n 0x98, 0xa8, 0x36, 0x50, 0xa0, 0xb1, 0x02, 0x81, 0x81, 0x00, 0x90, 0x88,\n 0x30, 0x71, 0xc7, 0xfe, 0x9b, 0x6d, 0x95, 0x37, 0x6d, 0x79, 0xfc, 0x85,\n 0xe7, 0x44, 0x78, 0xbc, 0x79, 0x6e, 0x47, 0x86, 0xc9, 0xf3, 0xdd, 0xc6,\n 0xec, 0xa9, 0x94, 0x9f, 0x40, 0xeb, 0x87, 0xd0, 0xdb, 0xee, 0xcd, 0x1b,\n 0x87, 0x23, 0xff, 0x76, 0xd4, 0x37, 0x8a, 0xcd, 0xb9, 0x6e, 0xd1, 0x98,\n 0xf6, 0x97, 0x8d, 0xe3, 0x81, 0x6d, 0xc3, 0x4e, 0xd1, 0xa0, 0xc4, 0x9f,\n 0xbd, 0x34, 0xe5, 0xe8, 0x53, 0x4f, 0xca, 0x10, 0xb5, 0xed, 0xe7, 0x16,\n 0x09, 0x54, 0xde, 0x60, 0xa7, 0xd1, 0x16, 0x6e, 0x2e, 0xb7, 0xbe, 0x7a,\n 0xd5, 0x9b, 0x26, 0xef, 0xe4, 0x0e, 0x77, 0xfa, 0xa9, 0xdd, 0xdc, 0xb9,\n 0x88, 0x19, 0x23, 0x70, 0xc7, 0xe1, 0x60, 0xaf, 0x8c, 0x73, 0x04, 0xf7,\n 0x71, 0x17, 0x81, 0x36, 0x75, 0xbb, 0x97, 0xd7, 0x75, 0xb6, 0x8e, 0xbc,\n 0xac, 0x9c, 0x6a, 0x9b, 0x24, 0x89, 0x02, 0x81, 0x80, 0x5a, 0x2b, 0xc7,\n 0x6b, 0x8c, 0x65, 0xdb, 0x04, 0x73, 0xab, 0x25, 0xe1, 0x5b, 0xbc, 0x3c,\n 0xcf, 0x5a, 0x3c, 0x04, 0xae, 0x97, 0x2e, 0xfd, 0xa4, 0x97, 0x1f, 0x05,\n 0x17, 0x27, 0xac, 0x7c, 0x30, 0x85, 0xb4, 0x82, 0x3f, 0x5b, 0xb7, 0x94,\n 0x3b, 0x7f, 0x6c, 0x0c, 0xc7, 0x16, 0xc6, 0xa0, 0xbd, 0x80, 0xb0, 0x81,\n 0xde, 0xa0, 0x23, 0xa6, 0xf6, 0x75, 0x33, 0x51, 0x35, 0xa2, 0x75, 0x55,\n 0x70, 0x4d, 0x42, 0xbb, 0xcf, 0x54, 0xe4, 0xdb, 0x2d, 0x88, 0xa0, 0x7a,\n 0xf2, 0x17, 0xa7, 0xdd, 0x13, 0x44, 0x9f, 0x5f, 0x6b, 0x2c, 0x42, 0x42,\n 0x8b, 0x13, 0x4d, 0xf9, 0x5b, 0xf8, 0x33, 0x42, 0xd9, 0x9e, 0x50, 0x1c,\n 0x7c, 0xbc, 0xfa, 0x62, 0x85, 0x0b, 0xcf, 0x99, 0xda, 0x9e, 0x04, 0x90,\n 0xb2, 0xc6, 0xb2, 0x0a, 0x2a, 0x7c, 0x6d, 0x6a, 0x40, 0xfc, 0xf5, 0x50,\n 0x98, 0x46, 0x89, 0x82, 0x40,\n};\n\n\n#ifndef OPENSSL_NO_EC\n/*\n * -----BEGIN EC PRIVATE KEY-----\n * MHcCAQEEIJLyl7hJjpQL/RhP1x2zS79xdiPJQB683gWeqcqHPeZkoAoGCCqGSM49\n * AwEHoUQDQgAEdsjygVYjjaKBF4CNECVllNf017p5/MxNSWDoTHy9I2GeDwEDDazI\n * D/xy8JiYjtPKVE/Zqwbmivp2UwtH28a7NQ==\n * -----END EC PRIVATE KEY-----\n */\nstatic const char ECDSAPrivateKeyPEM[] = {\n 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x45,\n 0x43, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b, 0x45,\n 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x48, 0x63, 0x43, 0x41,\n 0x51, 0x45, 0x45, 0x49, 0x4a, 0x4c, 0x79, 0x6c, 0x37, 0x68, 0x4a, 0x6a,\n 0x70, 0x51, 0x4c, 0x2f, 0x52, 0x68, 0x50, 0x31, 0x78, 0x32, 0x7a, 0x53,\n 0x37, 0x39, 0x78, 0x64, 0x69, 0x50, 0x4a, 0x51, 0x42, 0x36, 0x38, 0x33,\n 0x67, 0x57, 0x65, 0x71, 0x63, 0x71, 0x48, 0x50, 0x65, 0x5a, 0x6b, 0x6f,\n 0x41, 0x6f, 0x47, 0x43, 0x43, 0x71, 0x47, 0x53, 0x4d, 0x34, 0x39, 0x0a,\n 0x41, 0x77, 0x45, 0x48, 0x6f, 0x55, 0x51, 0x44, 0x51, 0x67, 0x41, 0x45,\n 0x64, 0x73, 0x6a, 0x79, 0x67, 0x56, 0x59, 0x6a, 0x6a, 0x61, 0x4b, 0x42,\n 0x46, 0x34, 0x43, 0x4e, 0x45, 0x43, 0x56, 0x6c, 0x6c, 0x4e, 0x66, 0x30,\n 0x31, 0x37, 0x70, 0x35, 0x2f, 0x4d, 0x78, 0x4e, 0x53, 0x57, 0x44, 0x6f,\n 0x54, 0x48, 0x79, 0x39, 0x49, 0x32, 0x47, 0x65, 0x44, 0x77, 0x45, 0x44,\n 0x44, 0x61, 0x7a, 0x49, 0x0a, 0x44, 0x2f, 0x78, 0x79, 0x38, 0x4a, 0x69,\n 0x59, 0x6a, 0x74, 0x50, 0x4b, 0x56, 0x45, 0x2f, 0x5a, 0x71, 0x77, 0x62,\n 0x6d, 0x69, 0x76, 0x70, 0x32, 0x55, 0x77, 0x74, 0x48, 0x32, 0x38, 0x61,\n 0x37, 0x4e, 0x51, 0x3d, 0x3d, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45,\n 0x4e, 0x44, 0x20, 0x45, 0x43, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54,\n 0x45, 0x20, 0x4b, 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a\n};\n\n/*\n * -----BEGIN CERTIFICATE-----\n * MIIBXzCCAQagAwIBAgIJAK6/Yvf/ain6MAoGCCqGSM49BAMCMBIxEDAOBgNVBAoM\n * B0FjbWUgQ28wHhcNMTYxMjI1MTEzOTI3WhcNMjYxMjI1MTEzOTI3WjASMRAwDgYD\n * VQQKDAdBY21lIENvMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEdsjygVYjjaKB\n * F4CNECVllNf017p5/MxNSWDoTHy9I2GeDwEDDazID/xy8JiYjtPKVE/Zqwbmivp2\n * UwtH28a7NaNFMEMwCQYDVR0TBAIwADALBgNVHQ8EBAMCBaAwEwYDVR0lBAwwCgYI\n * KwYBBQUHAwEwFAYDVR0RBA0wC4IJbG9jYWxob3N0MAoGCCqGSM49BAMCA0cAMEQC\n * IEzr3t/jejVE9oSnBp8c3P2p+lDLVRrB8zxLyjZvirUXAiAyQPaE9MNcL8/nRpuu\n * 99I1enCSmWIAJ57IwuJ/n1d45Q==\n * -----END CERTIFICATE-----\n */\nstatic const char ECDSACertPEM[] = {\n 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43,\n 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d,\n 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x49, 0x49, 0x42, 0x58, 0x7a, 0x43, 0x43,\n 0x41, 0x51, 0x61, 0x67, 0x41, 0x77, 0x49, 0x42, 0x41, 0x67, 0x49, 0x4a,\n 0x41, 0x4b, 0x36, 0x2f, 0x59, 0x76, 0x66, 0x2f, 0x61, 0x69, 0x6e, 0x36,\n 0x4d, 0x41, 0x6f, 0x47, 0x43, 0x43, 0x71, 0x47, 0x53, 0x4d, 0x34, 0x39,\n 0x42, 0x41, 0x4d, 0x43, 0x4d, 0x42, 0x49, 0x78, 0x45, 0x44, 0x41, 0x4f,\n 0x42, 0x67, 0x4e, 0x56, 0x42, 0x41, 0x6f, 0x4d, 0x0a, 0x42, 0x30, 0x46,\n 0x6a, 0x62, 0x57, 0x55, 0x67, 0x51, 0x32, 0x38, 0x77, 0x48, 0x68, 0x63,\n 0x4e, 0x4d, 0x54, 0x59, 0x78, 0x4d, 0x6a, 0x49, 0x31, 0x4d, 0x54, 0x45,\n 0x7a, 0x4f, 0x54, 0x49, 0x33, 0x57, 0x68, 0x63, 0x4e, 0x4d, 0x6a, 0x59,\n 0x78, 0x4d, 0x6a, 0x49, 0x31, 0x4d, 0x54, 0x45, 0x7a, 0x4f, 0x54, 0x49,\n 0x33, 0x57, 0x6a, 0x41, 0x53, 0x4d, 0x52, 0x41, 0x77, 0x44, 0x67, 0x59,\n 0x44, 0x0a, 0x56, 0x51, 0x51, 0x4b, 0x44, 0x41, 0x64, 0x42, 0x59, 0x32,\n 0x31, 0x6c, 0x49, 0x45, 0x4e, 0x76, 0x4d, 0x46, 0x6b, 0x77, 0x45, 0x77,\n 0x59, 0x48, 0x4b, 0x6f, 0x5a, 0x49, 0x7a, 0x6a, 0x30, 0x43, 0x41, 0x51,\n 0x59, 0x49, 0x4b, 0x6f, 0x5a, 0x49, 0x7a, 0x6a, 0x30, 0x44, 0x41, 0x51,\n 0x63, 0x44, 0x51, 0x67, 0x41, 0x45, 0x64, 0x73, 0x6a, 0x79, 0x67, 0x56,\n 0x59, 0x6a, 0x6a, 0x61, 0x4b, 0x42, 0x0a, 0x46, 0x34, 0x43, 0x4e, 0x45,\n 0x43, 0x56, 0x6c, 0x6c, 0x4e, 0x66, 0x30, 0x31, 0x37, 0x70, 0x35, 0x2f,\n 0x4d, 0x78, 0x4e, 0x53, 0x57, 0x44, 0x6f, 0x54, 0x48, 0x79, 0x39, 0x49,\n 0x32, 0x47, 0x65, 0x44, 0x77, 0x45, 0x44, 0x44, 0x61, 0x7a, 0x49, 0x44,\n 0x2f, 0x78, 0x79, 0x38, 0x4a, 0x69, 0x59, 0x6a, 0x74, 0x50, 0x4b, 0x56,\n 0x45, 0x2f, 0x5a, 0x71, 0x77, 0x62, 0x6d, 0x69, 0x76, 0x70, 0x32, 0x0a,\n 0x55, 0x77, 0x74, 0x48, 0x32, 0x38, 0x61, 0x37, 0x4e, 0x61, 0x4e, 0x46,\n 0x4d, 0x45, 0x4d, 0x77, 0x43, 0x51, 0x59, 0x44, 0x56, 0x52, 0x30, 0x54,\n 0x42, 0x41, 0x49, 0x77, 0x41, 0x44, 0x41, 0x4c, 0x42, 0x67, 0x4e, 0x56,\n 0x48, 0x51, 0x38, 0x45, 0x42, 0x41, 0x4d, 0x43, 0x42, 0x61, 0x41, 0x77,\n 0x45, 0x77, 0x59, 0x44, 0x56, 0x52, 0x30, 0x6c, 0x42, 0x41, 0x77, 0x77,\n 0x43, 0x67, 0x59, 0x49, 0x0a, 0x4b, 0x77, 0x59, 0x42, 0x42, 0x51, 0x55,\n 0x48, 0x41, 0x77, 0x45, 0x77, 0x46, 0x41, 0x59, 0x44, 0x56, 0x52, 0x30,\n 0x52, 0x42, 0x41, 0x30, 0x77, 0x43, 0x34, 0x49, 0x4a, 0x62, 0x47, 0x39,\n 0x6a, 0x59, 0x57, 0x78, 0x6f, 0x62, 0x33, 0x4e, 0x30, 0x4d, 0x41, 0x6f,\n 0x47, 0x43, 0x43, 0x71, 0x47, 0x53, 0x4d, 0x34, 0x39, 0x42, 0x41, 0x4d,\n 0x43, 0x41, 0x30, 0x63, 0x41, 0x4d, 0x45, 0x51, 0x43, 0x0a, 0x49, 0x45,\n 0x7a, 0x72, 0x33, 0x74, 0x2f, 0x6a, 0x65, 0x6a, 0x56, 0x45, 0x39, 0x6f,\n 0x53, 0x6e, 0x42, 0x70, 0x38, 0x63, 0x33, 0x50, 0x32, 0x70, 0x2b, 0x6c,\n 0x44, 0x4c, 0x56, 0x52, 0x72, 0x42, 0x38, 0x7a, 0x78, 0x4c, 0x79, 0x6a,\n 0x5a, 0x76, 0x69, 0x72, 0x55, 0x58, 0x41, 0x69, 0x41, 0x79, 0x51, 0x50,\n 0x61, 0x45, 0x39, 0x4d, 0x4e, 0x63, 0x4c, 0x38, 0x2f, 0x6e, 0x52, 0x70,\n 0x75, 0x75, 0x0a, 0x39, 0x39, 0x49, 0x31, 0x65, 0x6e, 0x43, 0x53, 0x6d,\n 0x57, 0x49, 0x41, 0x4a, 0x35, 0x37, 0x49, 0x77, 0x75, 0x4a, 0x2f, 0x6e,\n 0x31, 0x64, 0x34, 0x35, 0x51, 0x3d, 0x3d, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d,\n 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49,\n 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a\n};\n#endif\n\n#ifndef OPENSSL_NO_DSA\n/*\n * -----BEGIN DSA PRIVATE KEY-----\n * MIIBuwIBAAKBgQDdkFKzNABLOha7Eqj7004+p5fhtR6bxpujToMmSZTYi8igVVXP\n * Wzf03ULKS5UKjA6WpR6EiZAhm+PdxusZ5xfAuRZLdKy0bgxn1f348Rwh+EQNaEM8\n * 0TGcnw5ijwKmSw5yyHPDWdiHzoqEBlhAf8Nl22YTXax/clsc/pu/RRLAdwIVAIEg\n * QqWRf/1EIZZcgM65Qpd65YuxAoGBAKBauV/RuloFHoSy5iWXESDywiS380tN5974\n * GukGwoYdZo5uSIH6ahpeNSef0MbHGAzr7ZVEnhCQfRAwH1gRvSHoq/Rbmcvtd3r+\n * QtQHOwvQHgLAynhI4i73c794czHaR+439bmcaSwDnQduRM85Mho/jiiZzAVPxBmG\n * POIMWNXXAoGAI6Ep5IE7yn3JzkXO9B6tC3bbDM+ZzuuInwZLbtZ8lim7Dsqabg4k\n * 2YbE4R95Bnfwnjsyl80mq/DbQN5lAHBvjDrkC6ItojBGKI3+iIrqGUEJdxvl4ulj\n * F0PmSD7zvIG8BfocKOel+EHH0YryExiW6krV1KW2ZRmJrqSFw6KCjV0CFFQFbPfU\n * xy5PmKytJmXR8BmppkIO\n * -----END DSA PRIVATE KEY-----\n */\nstatic const char DSAPrivateKeyPEM[] = {\n 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x44,\n 0x53, 0x41, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b,\n 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x49, 0x49, 0x42,\n 0x75, 0x77, 0x49, 0x42, 0x41, 0x41, 0x4b, 0x42, 0x67, 0x51, 0x44, 0x64,\n 0x6b, 0x46, 0x4b, 0x7a, 0x4e, 0x41, 0x42, 0x4c, 0x4f, 0x68, 0x61, 0x37,\n 0x45, 0x71, 0x6a, 0x37, 0x30, 0x30, 0x34, 0x2b, 0x70, 0x35, 0x66, 0x68,\n 0x74, 0x52, 0x36, 0x62, 0x78, 0x70, 0x75, 0x6a, 0x54, 0x6f, 0x4d, 0x6d,\n 0x53, 0x5a, 0x54, 0x59, 0x69, 0x38, 0x69, 0x67, 0x56, 0x56, 0x58, 0x50,\n 0x0a, 0x57, 0x7a, 0x66, 0x30, 0x33, 0x55, 0x4c, 0x4b, 0x53, 0x35, 0x55,\n 0x4b, 0x6a, 0x41, 0x36, 0x57, 0x70, 0x52, 0x36, 0x45, 0x69, 0x5a, 0x41,\n 0x68, 0x6d, 0x2b, 0x50, 0x64, 0x78, 0x75, 0x73, 0x5a, 0x35, 0x78, 0x66,\n 0x41, 0x75, 0x52, 0x5a, 0x4c, 0x64, 0x4b, 0x79, 0x30, 0x62, 0x67, 0x78,\n 0x6e, 0x31, 0x66, 0x33, 0x34, 0x38, 0x52, 0x77, 0x68, 0x2b, 0x45, 0x51,\n 0x4e, 0x61, 0x45, 0x4d, 0x38, 0x0a, 0x30, 0x54, 0x47, 0x63, 0x6e, 0x77,\n 0x35, 0x69, 0x6a, 0x77, 0x4b, 0x6d, 0x53, 0x77, 0x35, 0x79, 0x79, 0x48,\n 0x50, 0x44, 0x57, 0x64, 0x69, 0x48, 0x7a, 0x6f, 0x71, 0x45, 0x42, 0x6c,\n 0x68, 0x41, 0x66, 0x38, 0x4e, 0x6c, 0x32, 0x32, 0x59, 0x54, 0x58, 0x61,\n 0x78, 0x2f, 0x63, 0x6c, 0x73, 0x63, 0x2f, 0x70, 0x75, 0x2f, 0x52, 0x52,\n 0x4c, 0x41, 0x64, 0x77, 0x49, 0x56, 0x41, 0x49, 0x45, 0x67, 0x0a, 0x51,\n 0x71, 0x57, 0x52, 0x66, 0x2f, 0x31, 0x45, 0x49, 0x5a, 0x5a, 0x63, 0x67,\n 0x4d, 0x36, 0x35, 0x51, 0x70, 0x64, 0x36, 0x35, 0x59, 0x75, 0x78, 0x41,\n 0x6f, 0x47, 0x42, 0x41, 0x4b, 0x42, 0x61, 0x75, 0x56, 0x2f, 0x52, 0x75,\n 0x6c, 0x6f, 0x46, 0x48, 0x6f, 0x53, 0x79, 0x35, 0x69, 0x57, 0x58, 0x45,\n 0x53, 0x44, 0x79, 0x77, 0x69, 0x53, 0x33, 0x38, 0x30, 0x74, 0x4e, 0x35,\n 0x39, 0x37, 0x34, 0x0a, 0x47, 0x75, 0x6b, 0x47, 0x77, 0x6f, 0x59, 0x64,\n 0x5a, 0x6f, 0x35, 0x75, 0x53, 0x49, 0x48, 0x36, 0x61, 0x68, 0x70, 0x65,\n 0x4e, 0x53, 0x65, 0x66, 0x30, 0x4d, 0x62, 0x48, 0x47, 0x41, 0x7a, 0x72,\n 0x37, 0x5a, 0x56, 0x45, 0x6e, 0x68, 0x43, 0x51, 0x66, 0x52, 0x41, 0x77,\n 0x48, 0x31, 0x67, 0x52, 0x76, 0x53, 0x48, 0x6f, 0x71, 0x2f, 0x52, 0x62,\n 0x6d, 0x63, 0x76, 0x74, 0x64, 0x33, 0x72, 0x2b, 0x0a, 0x51, 0x74, 0x51,\n 0x48, 0x4f, 0x77, 0x76, 0x51, 0x48, 0x67, 0x4c, 0x41, 0x79, 0x6e, 0x68,\n 0x49, 0x34, 0x69, 0x37, 0x33, 0x63, 0x37, 0x39, 0x34, 0x63, 0x7a, 0x48,\n 0x61, 0x52, 0x2b, 0x34, 0x33, 0x39, 0x62, 0x6d, 0x63, 0x61, 0x53, 0x77,\n 0x44, 0x6e, 0x51, 0x64, 0x75, 0x52, 0x4d, 0x38, 0x35, 0x4d, 0x68, 0x6f,\n 0x2f, 0x6a, 0x69, 0x69, 0x5a, 0x7a, 0x41, 0x56, 0x50, 0x78, 0x42, 0x6d,\n 0x47, 0x0a, 0x50, 0x4f, 0x49, 0x4d, 0x57, 0x4e, 0x58, 0x58, 0x41, 0x6f,\n 0x47, 0x41, 0x49, 0x36, 0x45, 0x70, 0x35, 0x49, 0x45, 0x37, 0x79, 0x6e,\n 0x33, 0x4a, 0x7a, 0x6b, 0x58, 0x4f, 0x39, 0x42, 0x36, 0x74, 0x43, 0x33,\n 0x62, 0x62, 0x44, 0x4d, 0x2b, 0x5a, 0x7a, 0x75, 0x75, 0x49, 0x6e, 0x77,\n 0x5a, 0x4c, 0x62, 0x74, 0x5a, 0x38, 0x6c, 0x69, 0x6d, 0x37, 0x44, 0x73,\n 0x71, 0x61, 0x62, 0x67, 0x34, 0x6b, 0x0a, 0x32, 0x59, 0x62, 0x45, 0x34,\n 0x52, 0x39, 0x35, 0x42, 0x6e, 0x66, 0x77, 0x6e, 0x6a, 0x73, 0x79, 0x6c,\n 0x38, 0x30, 0x6d, 0x71, 0x2f, 0x44, 0x62, 0x51, 0x4e, 0x35, 0x6c, 0x41,\n 0x48, 0x42, 0x76, 0x6a, 0x44, 0x72, 0x6b, 0x43, 0x36, 0x49, 0x74, 0x6f,\n 0x6a, 0x42, 0x47, 0x4b, 0x49, 0x33, 0x2b, 0x69, 0x49, 0x72, 0x71, 0x47,\n 0x55, 0x45, 0x4a, 0x64, 0x78, 0x76, 0x6c, 0x34, 0x75, 0x6c, 0x6a, 0x0a,\n 0x46, 0x30, 0x50, 0x6d, 0x53, 0x44, 0x37, 0x7a, 0x76, 0x49, 0x47, 0x38,\n 0x42, 0x66, 0x6f, 0x63, 0x4b, 0x4f, 0x65, 0x6c, 0x2b, 0x45, 0x48, 0x48,\n 0x30, 0x59, 0x72, 0x79, 0x45, 0x78, 0x69, 0x57, 0x36, 0x6b, 0x72, 0x56,\n 0x31, 0x4b, 0x57, 0x32, 0x5a, 0x52, 0x6d, 0x4a, 0x72, 0x71, 0x53, 0x46,\n 0x77, 0x36, 0x4b, 0x43, 0x6a, 0x56, 0x30, 0x43, 0x46, 0x46, 0x51, 0x46,\n 0x62, 0x50, 0x66, 0x55, 0x0a, 0x78, 0x79, 0x35, 0x50, 0x6d, 0x4b, 0x79,\n 0x74, 0x4a, 0x6d, 0x58, 0x52, 0x38, 0x42, 0x6d, 0x70, 0x70, 0x6b, 0x49,\n 0x4f, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x44,\n 0x53, 0x41, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b,\n 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a\n};\n\n/*\n * -----BEGIN CERTIFICATE-----\n * MIICqTCCAmegAwIBAgIJAILDGUk37fWGMAsGCWCGSAFlAwQDAjASMRAwDgYDVQQK\n * DAdBY21lIENvMB4XDTE2MTIyNTEzMjUzNloXDTI2MTIyNTEzMjUzNlowEjEQMA4G\n * A1UECgwHQWNtZSBDbzCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQDdkFKzNABLOha7\n * Eqj7004+p5fhtR6bxpujToMmSZTYi8igVVXPWzf03ULKS5UKjA6WpR6EiZAhm+Pd\n * xusZ5xfAuRZLdKy0bgxn1f348Rwh+EQNaEM80TGcnw5ijwKmSw5yyHPDWdiHzoqE\n * BlhAf8Nl22YTXax/clsc/pu/RRLAdwIVAIEgQqWRf/1EIZZcgM65Qpd65YuxAoGB\n * AKBauV/RuloFHoSy5iWXESDywiS380tN5974GukGwoYdZo5uSIH6ahpeNSef0MbH\n * GAzr7ZVEnhCQfRAwH1gRvSHoq/Rbmcvtd3r+QtQHOwvQHgLAynhI4i73c794czHa\n * R+439bmcaSwDnQduRM85Mho/jiiZzAVPxBmGPOIMWNXXA4GEAAKBgCOhKeSBO8p9\n * yc5FzvQerQt22wzPmc7riJ8GS27WfJYpuw7Kmm4OJNmGxOEfeQZ38J47MpfNJqvw\n * 20DeZQBwb4w65AuiLaIwRiiN/oiK6hlBCXcb5eLpYxdD5kg+87yBvAX6HCjnpfhB\n * x9GK8hMYlupK1dSltmUZia6khcOigo1do0UwQzAJBgNVHRMEAjAAMAsGA1UdDwQE\n * AwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATAUBgNVHREEDTALgglsb2NhbGhvc3Qw\n * CwYJYIZIAWUDBAMCAy8AMCwCFClxInXTRWNJEWdi5ilNr/fbM1bKAhQy4B7wtmfd\n * I+zV6g3w9qBkNqStpA==\n * -----END CERTIFICATE-----\n */\nstatic const char DSACertPEM[] = {\n 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43,\n 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d,\n 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x49, 0x49, 0x43, 0x71, 0x54, 0x43, 0x43,\n 0x41, 0x6d, 0x65, 0x67, 0x41, 0x77, 0x49, 0x42, 0x41, 0x67, 0x49, 0x4a,\n 0x41, 0x49, 0x4c, 0x44, 0x47, 0x55, 0x6b, 0x33, 0x37, 0x66, 0x57, 0x47,\n 0x4d, 0x41, 0x73, 0x47, 0x43, 0x57, 0x43, 0x47, 0x53, 0x41, 0x46, 0x6c,\n 0x41, 0x77, 0x51, 0x44, 0x41, 0x6a, 0x41, 0x53, 0x4d, 0x52, 0x41, 0x77,\n 0x44, 0x67, 0x59, 0x44, 0x56, 0x51, 0x51, 0x4b, 0x0a, 0x44, 0x41, 0x64,\n 0x42, 0x59, 0x32, 0x31, 0x6c, 0x49, 0x45, 0x4e, 0x76, 0x4d, 0x42, 0x34,\n 0x58, 0x44, 0x54, 0x45, 0x32, 0x4d, 0x54, 0x49, 0x79, 0x4e, 0x54, 0x45,\n 0x7a, 0x4d, 0x6a, 0x55, 0x7a, 0x4e, 0x6c, 0x6f, 0x58, 0x44, 0x54, 0x49,\n 0x32, 0x4d, 0x54, 0x49, 0x79, 0x4e, 0x54, 0x45, 0x7a, 0x4d, 0x6a, 0x55,\n 0x7a, 0x4e, 0x6c, 0x6f, 0x77, 0x45, 0x6a, 0x45, 0x51, 0x4d, 0x41, 0x34,\n 0x47, 0x0a, 0x41, 0x31, 0x55, 0x45, 0x43, 0x67, 0x77, 0x48, 0x51, 0x57,\n 0x4e, 0x74, 0x5a, 0x53, 0x42, 0x44, 0x62, 0x7a, 0x43, 0x43, 0x41, 0x62,\n 0x63, 0x77, 0x67, 0x67, 0x45, 0x73, 0x42, 0x67, 0x63, 0x71, 0x68, 0x6b,\n 0x6a, 0x4f, 0x4f, 0x41, 0x51, 0x42, 0x4d, 0x49, 0x49, 0x42, 0x48, 0x77,\n 0x4b, 0x42, 0x67, 0x51, 0x44, 0x64, 0x6b, 0x46, 0x4b, 0x7a, 0x4e, 0x41,\n 0x42, 0x4c, 0x4f, 0x68, 0x61, 0x37, 0x0a, 0x45, 0x71, 0x6a, 0x37, 0x30,\n 0x30, 0x34, 0x2b, 0x70, 0x35, 0x66, 0x68, 0x74, 0x52, 0x36, 0x62, 0x78,\n 0x70, 0x75, 0x6a, 0x54, 0x6f, 0x4d, 0x6d, 0x53, 0x5a, 0x54, 0x59, 0x69,\n 0x38, 0x69, 0x67, 0x56, 0x56, 0x58, 0x50, 0x57, 0x7a, 0x66, 0x30, 0x33,\n 0x55, 0x4c, 0x4b, 0x53, 0x35, 0x55, 0x4b, 0x6a, 0x41, 0x36, 0x57, 0x70,\n 0x52, 0x36, 0x45, 0x69, 0x5a, 0x41, 0x68, 0x6d, 0x2b, 0x50, 0x64, 0x0a,\n 0x78, 0x75, 0x73, 0x5a, 0x35, 0x78, 0x66, 0x41, 0x75, 0x52, 0x5a, 0x4c,\n 0x64, 0x4b, 0x79, 0x30, 0x62, 0x67, 0x78, 0x6e, 0x31, 0x66, 0x33, 0x34,\n 0x38, 0x52, 0x77, 0x68, 0x2b, 0x45, 0x51, 0x4e, 0x61, 0x45, 0x4d, 0x38,\n 0x30, 0x54, 0x47, 0x63, 0x6e, 0x77, 0x35, 0x69, 0x6a, 0x77, 0x4b, 0x6d,\n 0x53, 0x77, 0x35, 0x79, 0x79, 0x48, 0x50, 0x44, 0x57, 0x64, 0x69, 0x48,\n 0x7a, 0x6f, 0x71, 0x45, 0x0a, 0x42, 0x6c, 0x68, 0x41, 0x66, 0x38, 0x4e,\n 0x6c, 0x32, 0x32, 0x59, 0x54, 0x58, 0x61, 0x78, 0x2f, 0x63, 0x6c, 0x73,\n 0x63, 0x2f, 0x70, 0x75, 0x2f, 0x52, 0x52, 0x4c, 0x41, 0x64, 0x77, 0x49,\n 0x56, 0x41, 0x49, 0x45, 0x67, 0x51, 0x71, 0x57, 0x52, 0x66, 0x2f, 0x31,\n 0x45, 0x49, 0x5a, 0x5a, 0x63, 0x67, 0x4d, 0x36, 0x35, 0x51, 0x70, 0x64,\n 0x36, 0x35, 0x59, 0x75, 0x78, 0x41, 0x6f, 0x47, 0x42, 0x0a, 0x41, 0x4b,\n 0x42, 0x61, 0x75, 0x56, 0x2f, 0x52, 0x75, 0x6c, 0x6f, 0x46, 0x48, 0x6f,\n 0x53, 0x79, 0x35, 0x69, 0x57, 0x58, 0x45, 0x53, 0x44, 0x79, 0x77, 0x69,\n 0x53, 0x33, 0x38, 0x30, 0x74, 0x4e, 0x35, 0x39, 0x37, 0x34, 0x47, 0x75,\n 0x6b, 0x47, 0x77, 0x6f, 0x59, 0x64, 0x5a, 0x6f, 0x35, 0x75, 0x53, 0x49,\n 0x48, 0x36, 0x61, 0x68, 0x70, 0x65, 0x4e, 0x53, 0x65, 0x66, 0x30, 0x4d,\n 0x62, 0x48, 0x0a, 0x47, 0x41, 0x7a, 0x72, 0x37, 0x5a, 0x56, 0x45, 0x6e,\n 0x68, 0x43, 0x51, 0x66, 0x52, 0x41, 0x77, 0x48, 0x31, 0x67, 0x52, 0x76,\n 0x53, 0x48, 0x6f, 0x71, 0x2f, 0x52, 0x62, 0x6d, 0x63, 0x76, 0x74, 0x64,\n 0x33, 0x72, 0x2b, 0x51, 0x74, 0x51, 0x48, 0x4f, 0x77, 0x76, 0x51, 0x48,\n 0x67, 0x4c, 0x41, 0x79, 0x6e, 0x68, 0x49, 0x34, 0x69, 0x37, 0x33, 0x63,\n 0x37, 0x39, 0x34, 0x63, 0x7a, 0x48, 0x61, 0x0a, 0x52, 0x2b, 0x34, 0x33,\n 0x39, 0x62, 0x6d, 0x63, 0x61, 0x53, 0x77, 0x44, 0x6e, 0x51, 0x64, 0x75,\n 0x52, 0x4d, 0x38, 0x35, 0x4d, 0x68, 0x6f, 0x2f, 0x6a, 0x69, 0x69, 0x5a,\n 0x7a, 0x41, 0x56, 0x50, 0x78, 0x42, 0x6d, 0x47, 0x50, 0x4f, 0x49, 0x4d,\n 0x57, 0x4e, 0x58, 0x58, 0x41, 0x34, 0x47, 0x45, 0x41, 0x41, 0x4b, 0x42,\n 0x67, 0x43, 0x4f, 0x68, 0x4b, 0x65, 0x53, 0x42, 0x4f, 0x38, 0x70, 0x39,\n 0x0a, 0x79, 0x63, 0x35, 0x46, 0x7a, 0x76, 0x51, 0x65, 0x72, 0x51, 0x74,\n 0x32, 0x32, 0x77, 0x7a, 0x50, 0x6d, 0x63, 0x37, 0x72, 0x69, 0x4a, 0x38,\n 0x47, 0x53, 0x32, 0x37, 0x57, 0x66, 0x4a, 0x59, 0x70, 0x75, 0x77, 0x37,\n 0x4b, 0x6d, 0x6d, 0x34, 0x4f, 0x4a, 0x4e, 0x6d, 0x47, 0x78, 0x4f, 0x45,\n 0x66, 0x65, 0x51, 0x5a, 0x33, 0x38, 0x4a, 0x34, 0x37, 0x4d, 0x70, 0x66,\n 0x4e, 0x4a, 0x71, 0x76, 0x77, 0x0a, 0x32, 0x30, 0x44, 0x65, 0x5a, 0x51,\n 0x42, 0x77, 0x62, 0x34, 0x77, 0x36, 0x35, 0x41, 0x75, 0x69, 0x4c, 0x61,\n 0x49, 0x77, 0x52, 0x69, 0x69, 0x4e, 0x2f, 0x6f, 0x69, 0x4b, 0x36, 0x68,\n 0x6c, 0x42, 0x43, 0x58, 0x63, 0x62, 0x35, 0x65, 0x4c, 0x70, 0x59, 0x78,\n 0x64, 0x44, 0x35, 0x6b, 0x67, 0x2b, 0x38, 0x37, 0x79, 0x42, 0x76, 0x41,\n 0x58, 0x36, 0x48, 0x43, 0x6a, 0x6e, 0x70, 0x66, 0x68, 0x42, 0x0a, 0x78,\n 0x39, 0x47, 0x4b, 0x38, 0x68, 0x4d, 0x59, 0x6c, 0x75, 0x70, 0x4b, 0x31,\n 0x64, 0x53, 0x6c, 0x74, 0x6d, 0x55, 0x5a, 0x69, 0x61, 0x36, 0x6b, 0x68,\n 0x63, 0x4f, 0x69, 0x67, 0x6f, 0x31, 0x64, 0x6f, 0x30, 0x55, 0x77, 0x51,\n 0x7a, 0x41, 0x4a, 0x42, 0x67, 0x4e, 0x56, 0x48, 0x52, 0x4d, 0x45, 0x41,\n 0x6a, 0x41, 0x41, 0x4d, 0x41, 0x73, 0x47, 0x41, 0x31, 0x55, 0x64, 0x44,\n 0x77, 0x51, 0x45, 0x0a, 0x41, 0x77, 0x49, 0x46, 0x6f, 0x44, 0x41, 0x54,\n 0x42, 0x67, 0x4e, 0x56, 0x48, 0x53, 0x55, 0x45, 0x44, 0x44, 0x41, 0x4b,\n 0x42, 0x67, 0x67, 0x72, 0x42, 0x67, 0x45, 0x46, 0x42, 0x51, 0x63, 0x44,\n 0x41, 0x54, 0x41, 0x55, 0x42, 0x67, 0x4e, 0x56, 0x48, 0x52, 0x45, 0x45,\n 0x44, 0x54, 0x41, 0x4c, 0x67, 0x67, 0x6c, 0x73, 0x62, 0x32, 0x4e, 0x68,\n 0x62, 0x47, 0x68, 0x76, 0x63, 0x33, 0x51, 0x77, 0x0a, 0x43, 0x77, 0x59,\n 0x4a, 0x59, 0x49, 0x5a, 0x49, 0x41, 0x57, 0x55, 0x44, 0x42, 0x41, 0x4d,\n 0x43, 0x41, 0x79, 0x38, 0x41, 0x4d, 0x43, 0x77, 0x43, 0x46, 0x43, 0x6c,\n 0x78, 0x49, 0x6e, 0x58, 0x54, 0x52, 0x57, 0x4e, 0x4a, 0x45, 0x57, 0x64,\n 0x69, 0x35, 0x69, 0x6c, 0x4e, 0x72, 0x2f, 0x66, 0x62, 0x4d, 0x31, 0x62,\n 0x4b, 0x41, 0x68, 0x51, 0x79, 0x34, 0x42, 0x37, 0x77, 0x74, 0x6d, 0x66,\n 0x64, 0x0a, 0x49, 0x2b, 0x7a, 0x56, 0x36, 0x67, 0x33, 0x77, 0x39, 0x71,\n 0x42, 0x6b, 0x4e, 0x71, 0x53, 0x74, 0x70, 0x41, 0x3d, 0x3d, 0x0a, 0x2d,\n 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54,\n 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d,\n 0x0a\n};\n#endif\n\n#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\nextern int rand_predictable;\n#endif\n#define ENTROPY_NEEDED 32\n\n/* unused, to avoid warning. */\nstatic int idx;\n\nint FuzzerInitialize(int *argc, char ***argv)\n{\n STACK_OF(SSL_COMP) *comp_methods;\n\n OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS | OPENSSL_INIT_ASYNC, NULL);\n OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);\n ERR_get_state();\n CRYPTO_free_ex_index(0, -1);\n idx = SSL_get_ex_data_X509_STORE_CTX_idx();\n RAND_add(\"\", 1, ENTROPY_NEEDED);\n RAND_status();\n RSA_get_default_method();\n#ifndef OPENSSL_NO_DSA\n DSA_get_default_method();\n#endif\n#ifndef OPENSSL_NO_EC\n EC_KEY_get_default_method();\n#endif\n#ifndef OPENSSL_NO_DH\n DH_get_default_method();\n#endif\n comp_methods = SSL_COMP_get_compression_methods();\n OPENSSL_sk_sort((OPENSSL_STACK *)comp_methods);\n\n\n#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\n rand_predictable = 1;\n#endif\n\n return 1;\n}\n\nint FuzzerTestOneInput(const uint8_t *buf, size_t len)\n{\n SSL *server;\n BIO *in;\n BIO *out;\n BIO *bio_buf;\n SSL_CTX *ctx;\n int ret;\n RSA *privkey;\n const uint8_t *bufp;\n EVP_PKEY *pkey;\n X509 *cert;\n#ifndef OPENSSL_NO_EC\n EC_KEY *ecdsakey = NULL;\n#endif\n#ifndef OPENSSL_NO_DSA\n DSA *dsakey = NULL;\n#endif\n\n if (len == 0)\n return 0;\n\n /*\n * TODO: use the ossltest engine (optionally?) to disable crypto checks.\n */\n\n /* This only fuzzes the initial flow from the client so far. */\n ctx = SSL_CTX_new(SSLv23_method());\n\n /* RSA */\n bufp = kRSAPrivateKeyDER;\n privkey = d2i_RSAPrivateKey(NULL, &bufp, sizeof(kRSAPrivateKeyDER));\n OPENSSL_assert(privkey != NULL);\n pkey = EVP_PKEY_new();\n EVP_PKEY_assign_RSA(pkey, privkey);\n ret = SSL_CTX_use_PrivateKey(ctx, pkey);\n OPENSSL_assert(ret == 1);\n EVP_PKEY_free(pkey);\n\n bufp = kCertificateDER;\n cert = d2i_X509(NULL, &bufp, sizeof(kCertificateDER));\n OPENSSL_assert(cert != NULL);\n ret = SSL_CTX_use_certificate(ctx, cert);\n OPENSSL_assert(ret == 1);\n X509_free(cert);\n\n#ifndef OPENSSL_NO_EC\n /* ECDSA */\n bio_buf = BIO_new(BIO_s_mem());\n OPENSSL_assert((size_t)BIO_write(bio_buf, ECDSAPrivateKeyPEM, sizeof(ECDSAPrivateKeyPEM)) == sizeof(ECDSAPrivateKeyPEM));\n ecdsakey = PEM_read_bio_ECPrivateKey(bio_buf, NULL, NULL, NULL);\n ERR_print_errors_fp(stderr);\n OPENSSL_assert(ecdsakey != NULL);\n BIO_free(bio_buf);\n pkey = EVP_PKEY_new();\n EVP_PKEY_assign_EC_KEY(pkey, ecdsakey);\n ret = SSL_CTX_use_PrivateKey(ctx, pkey);\n OPENSSL_assert(ret == 1);\n EVP_PKEY_free(pkey);\n\n bio_buf = BIO_new(BIO_s_mem());\n OPENSSL_assert((size_t)BIO_write(bio_buf, ECDSACertPEM, sizeof(ECDSACertPEM)) == sizeof(ECDSACertPEM));\n cert = PEM_read_bio_X509(bio_buf, NULL, NULL, NULL);\n OPENSSL_assert(cert != NULL);\n BIO_free(bio_buf);\n ret = SSL_CTX_use_certificate(ctx, cert);\n OPENSSL_assert(ret == 1);\n X509_free(cert);\n#endif\n\n#ifndef OPENSSL_NO_DSA\n /* DSA */\n bio_buf = BIO_new(BIO_s_mem());\n OPENSSL_assert((size_t)BIO_write(bio_buf, DSAPrivateKeyPEM, sizeof(DSAPrivateKeyPEM)) == sizeof(DSAPrivateKeyPEM));\n dsakey = PEM_read_bio_DSAPrivateKey(bio_buf, NULL, NULL, NULL);\n ERR_print_errors_fp(stderr);\n OPENSSL_assert(dsakey != NULL);\n BIO_free(bio_buf);\n pkey = EVP_PKEY_new();\n EVP_PKEY_assign_DSA(pkey, dsakey);\n ret = SSL_CTX_use_PrivateKey(ctx, pkey);\n OPENSSL_assert(ret == 1);\n EVP_PKEY_free(pkey);\n\n bio_buf = BIO_new(BIO_s_mem());\n OPENSSL_assert((size_t)BIO_write(bio_buf, DSACertPEM, sizeof(DSACertPEM)) == sizeof(DSACertPEM));\n cert = PEM_read_bio_X509(bio_buf, NULL, NULL, NULL);\n OPENSSL_assert(cert != NULL);\n BIO_free(bio_buf);\n ret = SSL_CTX_use_certificate(ctx, cert);\n OPENSSL_assert(ret == 1);\n X509_free(cert);\n#endif\n\n /* TODO: Set up support for SRP and PSK */\n\n server = SSL_new(ctx);\n ret = SSL_set_cipher_list(server, \"ALL:eNULL:@SECLEVEL=0\");\n OPENSSL_assert(ret == 1);\n in = BIO_new(BIO_s_mem());\n out = BIO_new(BIO_s_mem());\n SSL_set_bio(server, in, out);\n SSL_set_accept_state(server);\n OPENSSL_assert((size_t)BIO_write(in, buf, len) == len);\n if (SSL_do_handshake(server) == 1) {\n /* Keep reading application data until error or EOF. */\n uint8_t tmp[1024];\n for (;;) {\n if (SSL_read(server, tmp, sizeof(tmp)) <= 0) {\n break;\n }\n }\n }\n SSL_free(server);\n ERR_clear_error();\n SSL_CTX_free(ctx);\n\n return 0;\n}\n\nvoid FuzzerCleanup(void)\n{\n}\n"},"repo_name":{"kind":"string","value":"openssl_openssl"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"26a39fa953c11c4257471570655b0193828d4721"}}},{"rowIdx":90,"cells":{"file_path":{"kind":"string","value":"crypto/ui/ui_util.c"},"num_changed_lines":{"kind":"number","value":109,"string":"109"},"code":{"kind":"string","value":"/*\n * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.\n *\n * Licensed under the OpenSSL license (the \"License\"). You may not use\n * this file except in compliance with the License. You can obtain a copy\n * in the file LICENSE in the source distribution or at\n * https://www.openssl.org/source/license.html\n */\n\n#include \n#include \"internal/thread_once.h\"\n#include \"ui_locl.h\"\n\n#ifndef BUFSIZ\n#define BUFSIZ 256\n#endif\n\nint UI_UTIL_read_pw_string(char *buf, int length, const char *prompt,\n int verify)\n{\n char buff[BUFSIZ];\n int ret;\n\n ret =\n UI_UTIL_read_pw(buf, buff, (length > BUFSIZ) ? BUFSIZ : length,\n prompt, verify);\n OPENSSL_cleanse(buff, BUFSIZ);\n return (ret);\n}\n\nint UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt,\n int verify)\n{\n int ok = 0;\n UI *ui;\n\n if (size < 1)\n return -1;\n\n ui = UI_new();\n if (ui != NULL) {\n ok = UI_add_input_string(ui, prompt, 0, buf, 0, size - 1);\n if (ok >= 0 && verify)\n ok = UI_add_verify_string(ui, prompt, 0, buff, 0, size - 1, buf);\n if (ok >= 0)\n ok = UI_process(ui);\n UI_free(ui);\n }\n if (ok > 0)\n ok = 0;\n return (ok);\n}\n\n/*\n * Wrapper around pem_password_cb, a method to help older APIs use newer\n * ones.\n */\nstruct pem_password_cb_data {\n pem_password_cb *cb;\n int rwflag;\n};\n\nstatic void ui_new_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad,\n int idx, long argl, void *argp)\n{\n /*\n * Do nothing, the data is allocated externally and assigned later with\n * CRYPTO_set_ex_data()\n */\n}\n\nstatic int ui_dup_method_data(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,\n void *from_d, int idx, long argl, void *argp)\n{\n void **pptr = (void **)from_d;\n if (*pptr != NULL)\n *pptr = OPENSSL_memdup(*pptr, sizeof(struct pem_password_cb_data));\n return 1;\n}\n\nstatic void ui_free_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad,\n int idx, long argl, void *argp)\n{\n OPENSSL_free(ptr);\n}\n\nstatic CRYPTO_ONCE get_index_once = CRYPTO_ONCE_STATIC_INIT;\nstatic int ui_method_data_index = -1;\nDEFINE_RUN_ONCE_STATIC(ui_method_data_index_init)\n{\n ui_method_data_index = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI_METHOD,\n 0, NULL, ui_new_method_data,\n ui_dup_method_data,\n ui_free_method_data);\n return 1;\n}\n\nstatic int ui_open(UI *ui)\n{\n return 1;\n}\nstatic int ui_read(UI *ui, UI_STRING *uis)\n{\n switch (UI_get_string_type(uis)) {\n case UIT_PROMPT:\n {\n char result[PEM_BUFSIZE];\n const struct pem_password_cb_data *data =\n UI_method_get_ex_data(UI_get_method(ui), ui_method_data_index);\n int maxsize = UI_get_result_maxsize(uis);\n int len = data->cb(result,\n maxsize > PEM_BUFSIZE ? PEM_BUFSIZE : maxsize,\n data->rwflag, UI_get0_user_data(ui));\n\n if (len <= 0)\n return len;\n if (UI_set_result(ui, uis, result) >= 0)\n return 1;\n return 0;\n }\n case UIT_VERIFY:\n case UIT_NONE:\n case UIT_BOOLEAN:\n case UIT_INFO:\n case UIT_ERROR:\n break;\n }\n return 1;\n}\nstatic int ui_write(UI *ui, UI_STRING *uis)\n{\n return 1;\n}\nstatic int ui_close(UI *ui)\n{\n return 1;\n}\n\nUI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag)\n{\n struct pem_password_cb_data *data = NULL;\n UI_METHOD *ui_method = NULL;\n\n if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL\n || (ui_method = UI_create_method(\"PEM password callback wrapper\")) == NULL\n || UI_method_set_opener(ui_method, ui_open) < 0\n || UI_method_set_reader(ui_method, ui_read) < 0\n || UI_method_set_writer(ui_method, ui_write) < 0\n || UI_method_set_closer(ui_method, ui_close) < 0\n || !RUN_ONCE(&get_index_once, ui_method_data_index_init)\n || UI_method_set_ex_data(ui_method, ui_method_data_index, data) < 0) {\n UI_destroy_method(ui_method);\n OPENSSL_free(data);\n return NULL;\n }\n data->rwflag = rwflag;\n data->cb = cb;\n\n return ui_method;\n}\n"},"repo_name":{"kind":"string","value":"openssl_openssl"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"26a39fa953c11c4257471570655b0193828d4721"}}},{"rowIdx":91,"cells":{"file_path":{"kind":"string","value":"crypto/poly1305/poly1305_pmeth.c"},"num_changed_lines":{"kind":"number","value":192,"string":"192"},"code":{"kind":"string","value":"/*\n * Copyright 2007-2017 The OpenSSL Project Authors. All Rights Reserved.\n *\n * Licensed under the OpenSSL license (the \"License\"). You may not use\n * this file except in compliance with the License. You can obtain a copy\n * in the file LICENSE in the source distribution or at\n * https://www.openssl.org/source/license.html\n */\n\n#include \n#include \"internal/cryptlib.h\"\n#include \n#include \n#include \n#include \"internal/poly1305.h\"\n#include \"poly1305_local.h\"\n#include \"internal/evp_int.h\"\n\n/* POLY1305 pkey context structure */\n\ntypedef struct {\n ASN1_OCTET_STRING ktmp; /* Temp storage for key */\n POLY1305 ctx;\n} POLY1305_PKEY_CTX;\n\nstatic int pkey_poly1305_init(EVP_PKEY_CTX *ctx)\n{\n POLY1305_PKEY_CTX *pctx;\n\n pctx = OPENSSL_zalloc(sizeof(*pctx));\n if (pctx == NULL)\n return 0;\n pctx->ktmp.type = V_ASN1_OCTET_STRING;\n\n EVP_PKEY_CTX_set_data(ctx, pctx);\n EVP_PKEY_CTX_set0_keygen_info(ctx, NULL, 0);\n return 1;\n}\n\nstatic void pkey_poly1305_cleanup(EVP_PKEY_CTX *ctx)\n{\n POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx);\n\n if (pctx != NULL) {\n OPENSSL_clear_free(pctx->ktmp.data, pctx->ktmp.length);\n OPENSSL_clear_free(pctx, sizeof(*pctx));\n EVP_PKEY_CTX_set_data(ctx, NULL);\n }\n}\n\nstatic int pkey_poly1305_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src)\n{\n POLY1305_PKEY_CTX *sctx, *dctx;\n\n /* allocate memory for dst->data and a new POLY1305_CTX in dst->data->ctx */\n if (!pkey_poly1305_init(dst))\n return 0;\n sctx = EVP_PKEY_CTX_get_data(src);\n dctx = EVP_PKEY_CTX_get_data(dst);\n if (ASN1_STRING_get0_data(&sctx->ktmp) != NULL &&\n !ASN1_STRING_copy(&dctx->ktmp, &sctx->ktmp)) {\n /* cleanup and free the POLY1305_PKEY_CTX in dst->data */\n pkey_poly1305_cleanup(dst);\n return 0;\n }\n memcpy(&dctx->ctx, &sctx->ctx, sizeof(POLY1305));\n return 1;\n}\n\nstatic int pkey_poly1305_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)\n{\n ASN1_OCTET_STRING *key;\n POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx);\n\n if (ASN1_STRING_get0_data(&pctx->ktmp) == NULL)\n return 0;\n key = ASN1_OCTET_STRING_dup(&pctx->ktmp);\n if (key == NULL)\n return 0;\n return EVP_PKEY_assign_POLY1305(pkey, key);\n}\n\nstatic int int_update(EVP_MD_CTX *ctx, const void *data, size_t count)\n{\n POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(EVP_MD_CTX_pkey_ctx(ctx));\n\n Poly1305_Update(&pctx->ctx, data, count);\n return 1;\n}\n\nstatic int poly1305_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)\n{\n POLY1305_PKEY_CTX *pctx = ctx->data;\n ASN1_OCTET_STRING *key = (ASN1_OCTET_STRING *)ctx->pkey->pkey.ptr;\n\n if (key->length != POLY1305_KEY_SIZE)\n return 0;\n EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT);\n EVP_MD_CTX_set_update_fn(mctx, int_update);\n Poly1305_Init(&pctx->ctx, key->data);\n return 1;\n}\nstatic int poly1305_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,\n EVP_MD_CTX *mctx)\n{\n POLY1305_PKEY_CTX *pctx = ctx->data;\n\n *siglen = POLY1305_DIGEST_SIZE;\n if (sig != NULL)\n Poly1305_Final(&pctx->ctx, sig);\n return 1;\n}\n\nstatic int pkey_poly1305_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)\n{\n POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx);\n const unsigned char *key;\n size_t len;\n\n switch (type) {\n\n case EVP_PKEY_CTRL_MD:\n /* ignore */\n break;\n\n case EVP_PKEY_CTRL_SET_MAC_KEY:\n case EVP_PKEY_CTRL_DIGESTINIT:\n if (type == EVP_PKEY_CTRL_SET_MAC_KEY) {\n /* user explicitly setting the key */\n key = p2;\n len = p1;\n } else {\n /* user indirectly setting the key via EVP_DigestSignInit */\n key = EVP_PKEY_get0_poly1305(EVP_PKEY_CTX_get0_pkey(ctx), &len);\n }\n if (key == NULL || len != POLY1305_KEY_SIZE ||\n !ASN1_OCTET_STRING_set(&pctx->ktmp, key, len))\n return 0;\n Poly1305_Init(&pctx->ctx, ASN1_STRING_get0_data(&pctx->ktmp));\n break;\n\n default:\n return -2;\n\n }\n return 1;\n}\n\nstatic int pkey_poly1305_ctrl_str(EVP_PKEY_CTX *ctx,\n const char *type, const char *value)\n{\n if (value == NULL)\n return 0;\n if (strcmp(type, \"key\") == 0)\n return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value);\n if (strcmp(type, \"hexkey\") == 0)\n return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value);\n return -2;\n}\n\nconst EVP_PKEY_METHOD poly1305_pkey_meth = {\n EVP_PKEY_POLY1305,\n EVP_PKEY_FLAG_SIGCTX_CUSTOM, /* we don't deal with a separate MD */\n pkey_poly1305_init,\n pkey_poly1305_copy,\n pkey_poly1305_cleanup,\n\n 0, 0,\n\n 0,\n pkey_poly1305_keygen,\n\n 0, 0,\n\n 0, 0,\n\n 0, 0,\n\n poly1305_signctx_init,\n poly1305_signctx,\n\n 0, 0,\n\n 0, 0,\n\n 0, 0,\n\n 0, 0,\n\n pkey_poly1305_ctrl,\n pkey_poly1305_ctrl_str\n};\n"},"repo_name":{"kind":"string","value":"openssl_openssl"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"26a39fa953c11c4257471570655b0193828d4721"}}},{"rowIdx":92,"cells":{"file_path":{"kind":"string","value":"test/uitest.c"},"num_changed_lines":{"kind":"number","value":141,"string":"141"},"code":{"kind":"string","value":"/*\n * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.\n *\n * Licensed under the OpenSSL license (the \"License\"). You may not use\n * this file except in compliance with the License. You can obtain a copy\n * in the file LICENSE in the source distribution or at\n * https://www.openssl.org/source/license.html\n */\n\n#include \n#include \n#include \n#include \n\n/*\n * We know that on VMS, the [.apps] object files are compiled with uppercased\n * symbols. We must therefore follow suit, or there will be linking errors.\n * Additionally, the VMS build does stdio via a socketpair.\n */\n#ifdef __VMS\n# pragma names save\n# pragma names uppercase, truncated\n\n# include \"../apps/vms_term_sock.h\"\n#endif\n\n#include \"../apps/apps.h\"\n\n#ifdef __VMS\n# pragma names restore\n#endif\n\n#include \"testutil.h\"\n#include \"test_main_custom.h\"\n\n/* apps/apps.c depend on these */\nchar *default_config_file = NULL;\nBIO *bio_err = NULL;\n\n#ifndef OPENSSL_NO_UI\n# include \n\n/* Old style PEM password callback */\nstatic int test_pem_password_cb(char *buf, int size, int rwflag, void *userdata)\n{\n OPENSSL_strlcpy(buf, (char *)userdata, (size_t)size);\n return 1;\n}\n\n/*\n * Test wrapping old style PEM password callback in a UI method through the\n * use of UI utility functions\n */\nstatic int test_old()\n{\n UI_METHOD *ui_method = NULL;\n UI *ui = NULL;\n char defpass[] = \"password\";\n char pass[16];\n int ok = 0;\n\n if ((ui_method =\n UI_UTIL_wrap_read_pem_callback(test_pem_password_cb, 0)) == NULL\n || (ui = UI_new_method(ui_method)) == NULL)\n goto err;\n\n /* The wrapper passes the UI userdata as the callback userdata param */\n UI_add_user_data(ui, defpass);\n\n if (!UI_add_input_string(ui, \"prompt\", UI_INPUT_FLAG_DEFAULT_PWD,\n pass, 0, sizeof(pass) - 1))\n goto err;\n\n switch (UI_process(ui)) {\n case -2:\n BIO_printf(bio_err, \"test_old: UI process interrupted or cancelled\\n\");\n /* fall through */\n case -1:\n goto err;\n default:\n break;\n }\n\n if (strcmp(pass, defpass) == 0)\n ok = 1;\n else\n BIO_printf(bio_err, \"test_old: password failure\\n\");\n\n err:\n if (!ok)\n ERR_print_errors_fp(stderr);\n UI_free(ui);\n UI_destroy_method(ui_method);\n\n return ok;\n}\n\n/* Test of UI. This uses the UI method defined in apps/apps.c */\nstatic int test_new_ui()\n{\n PW_CB_DATA cb_data = {\n \"password\",\n \"prompt\"\n };\n char pass[16];\n int ok = 0;\n\n setup_ui_method();\n if (password_callback(pass, sizeof(pass), 0, &cb_data) > 0\n && strcmp(pass, cb_data.password) == 0)\n ok = 1;\n else\n BIO_printf(bio_err, \"test_new: password failure\\n\");\n\n if (!ok)\n ERR_print_errors_fp(stderr);\n\n destroy_ui_method();\n return ok;\n}\n\n#endif\n\nint test_main(int argc, char *argv[])\n{\n int ret;\n\n bio_err = dup_bio_err(FORMAT_TEXT);\n\n#ifndef OPENSSL_NO_UI\n ADD_TEST(test_old);\n ADD_TEST(test_new_ui);\n#endif\n\n ret = run_tests(argv[0]);\n\n (void)BIO_flush(bio_err);\n BIO_free(bio_err);\n\n return ret;\n}\n"},"repo_name":{"kind":"string","value":"openssl_openssl"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"26a39fa953c11c4257471570655b0193828d4721"}}},{"rowIdx":93,"cells":{"file_path":{"kind":"string","value":"crypto/poly1305/poly1305_ameth.c"},"num_changed_lines":{"kind":"number","value":67,"string":"67"},"code":{"kind":"string","value":"/*\n * Copyright 2007-2017 The OpenSSL Project Authors. All Rights Reserved.\n *\n * Licensed under the OpenSSL license (the \"License\"). You may not use\n * this file except in compliance with the License. You can obtain a copy\n * in the file LICENSE in the source distribution or at\n * https://www.openssl.org/source/license.html\n */\n\n#include \n#include \"internal/cryptlib.h\"\n#include \n#include \"internal/asn1_int.h\"\n#include \"internal/poly1305.h\"\n#include \"poly1305_local.h\"\n\n/*\n * POLY1305 \"ASN1\" method. This is just here to indicate the maximum\n * POLY1305 output length and to free up a POLY1305 key.\n */\n\nstatic int poly1305_size(const EVP_PKEY *pkey)\n{\n return POLY1305_DIGEST_SIZE;\n}\n\nstatic void poly1305_key_free(EVP_PKEY *pkey)\n{\n ASN1_OCTET_STRING *os = EVP_PKEY_get0(pkey);\n if (os != NULL) {\n if (os->data != NULL)\n OPENSSL_cleanse(os->data, os->length);\n ASN1_OCTET_STRING_free(os);\n }\n}\n\nstatic int poly1305_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)\n{\n /* nothing, (including ASN1_PKEY_CTRL_DEFAULT_MD_NID), is supported */\n return -2;\n}\n\nstatic int poly1305_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b)\n{\n return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b));\n}\n\nconst EVP_PKEY_ASN1_METHOD poly1305_asn1_meth = {\n EVP_PKEY_POLY1305,\n EVP_PKEY_POLY1305,\n 0,\n\n \"POLY1305\",\n \"OpenSSL POLY1305 method\",\n\n 0, 0, poly1305_pkey_public_cmp, 0,\n\n 0, 0, 0,\n\n poly1305_size,\n 0, 0,\n 0, 0, 0, 0, 0, 0, 0,\n\n poly1305_key_free,\n poly1305_pkey_ctrl,\n 0, 0\n};\n"},"repo_name":{"kind":"string","value":"openssl_openssl"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"26a39fa953c11c4257471570655b0193828d4721"}}},{"rowIdx":94,"cells":{"file_path":{"kind":"string","value":"sklearn/tests/test_multioutput.py"},"num_changed_lines":{"kind":"number","value":126,"string":"126"},"code":{"kind":"string","value":"from __future__ import division\nimport numpy as np\nimport scipy.sparse as sp\nfrom sklearn.utils import shuffle\nfrom sklearn.utils.testing import assert_almost_equal\nfrom sklearn.utils.testing import assert_raises\nfrom sklearn.utils.testing import assert_false\nfrom sklearn.utils.testing import assert_raises_regex\nfrom sklearn.utils.testing import assert_array_equal\nfrom sklearn.utils.testing import assert_equal\nfrom sklearn.utils.testing import assert_not_equal\nfrom sklearn.utils.testing import assert_array_almost_equal\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn import datasets\nfrom sklearn.base import clone\nfrom sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.linear_model import SGDRegressor\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import LinearSVC\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.multioutput import MultiOutputRegressor, MultiOutputClassifier\n\n\ndef test_multi_target_regression():\n X, y = datasets.make_regression(n_targets=3)\n X_train, y_train = X[:50], y[:50]\n X_test, y_test = X[50:], y[50:]\n\n references = np.zeros_like(y_test)\n for n in range(3):\n rgr = GradientBoostingRegressor(random_state=0)\n rgr.fit(X_train, y_train[:, n])\n references[:, n] = rgr.predict(X_test)\n\n rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0))\n rgr.fit(X_train, y_train)\n y_pred = rgr.predict(X_test)\n\n assert_almost_equal(references, y_pred)\n\n\ndef test_multi_target_regression_partial_fit():\n X, y = datasets.make_regression(n_targets=3)\n X_train, y_train = X[:50], y[:50]\n X_test, y_test = X[50:], y[50:]\n\n references = np.zeros_like(y_test)\n half_index = 25\n for n in range(3):\n sgr = SGDRegressor(random_state=0)\n sgr.partial_fit(X_train[:half_index], y_train[:half_index, n])\n sgr.partial_fit(X_train[half_index:], y_train[half_index:, n])\n references[:, n] = sgr.predict(X_test)\n\n sgr = MultiOutputRegressor(SGDRegressor(random_state=0))\n\n sgr.partial_fit(X_train[:half_index], y_train[:half_index])\n sgr.partial_fit(X_train[half_index:], y_train[half_index:])\n\n y_pred = sgr.predict(X_test)\n assert_almost_equal(references, y_pred)\n\n\ndef test_multi_target_regression_one_target():\n # Test multi target regression raises\n X, y = datasets.make_regression(n_targets=1)\n\n rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0))\n assert_raises(ValueError, rgr.fit, X, y)\n\n\ndef test_multi_target_sparse_regression():\n X, y = datasets.make_regression(n_targets=3)\n X_train, y_train = X[:50], y[:50]\n X_test = X[50:]\n\n for sparse in [sp.csr_matrix, sp.csc_matrix, sp.coo_matrix, sp.dok_matrix,\n sp.lil_matrix]:\n rgr = MultiOutputRegressor(Lasso(random_state=0))\n rgr_sparse = MultiOutputRegressor(Lasso(random_state=0))\n\n rgr.fit(X_train, y_train)\n rgr_sparse.fit(sparse(X_train), y_train)\n\n assert_almost_equal(rgr.predict(X_test),\n rgr_sparse.predict(sparse(X_test)))\n\n\ndef test_multi_target_sample_weights_api():\n X = [[1, 2, 3], [4, 5, 6]]\n y = [[3.141, 2.718], [2.718, 3.141]]\n w = [0.8, 0.6]\n\n rgr = MultiOutputRegressor(Lasso())\n assert_raises_regex(ValueError, \"does not support sample weights\",\n rgr.fit, X, y, w)\n\n # no exception should be raised if the base estimator supports weights\n rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0))\n rgr.fit(X, y, w)\n\n\ndef test_multi_target_sample_weight_partial_fit():\n # weighted regressor\n X = [[1, 2, 3], [4, 5, 6]]\n y = [[3.141, 2.718], [2.718, 3.141]]\n w = [2., 1.]\n rgr_w = MultiOutputRegressor(SGDRegressor(random_state=0))\n rgr_w.partial_fit(X, y, w)\n\n # weighted with different weights\n w = [2., 2.]\n rgr = MultiOutputRegressor(SGDRegressor(random_state=0))\n rgr.partial_fit(X, y, w)\n\n assert_not_equal(rgr.predict(X)[0][0], rgr_w.predict(X)[0][0])\n\n\ndef test_multi_target_sample_weights():\n # weighted regressor\n Xw = [[1, 2, 3], [4, 5, 6]]\n yw = [[3.141, 2.718], [2.718, 3.141]]\n w = [2., 1.]\n rgr_w = MultiOutputRegressor(GradientBoostingRegressor(random_state=0))\n rgr_w.fit(Xw, yw, w)\n\n # unweighted, but with repeated samples\n X = [[1, 2, 3], [1, 2, 3], [4, 5, 6]]\n y = [[3.141, 2.718], [3.141, 2.718], [2.718, 3.141]]\n rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0))\n rgr.fit(X, y)\n\n X_test = [[1.5, 2.5, 3.5], [3.5, 4.5, 5.5]]\n assert_almost_equal(rgr.predict(X_test), rgr_w.predict(X_test))\n\n\n# Import the data\niris = datasets.load_iris()\n# create a multiple targets by randomized shuffling and concatenating y.\nX = iris.data\ny1 = iris.target\ny2 = shuffle(y1, random_state=1)\ny3 = shuffle(y1, random_state=2)\ny = np.column_stack((y1, y2, y3))\nn_samples, n_features = X.shape\nn_outputs = y.shape[1]\nn_classes = len(np.unique(y1))\nclasses = list(map(np.unique, (y1, y2, y3)))\n\n\ndef test_multi_output_classification_partial_fit_parallelism():\n sgd_linear_clf = SGDClassifier(loss='log', random_state=1)\n mor = MultiOutputClassifier(sgd_linear_clf, n_jobs=-1)\n mor.partial_fit(X, y, classes)\n est1 = mor.estimators_[0]\n mor.partial_fit(X, y)\n est2 = mor.estimators_[0]\n # parallelism requires this to be the case for a sane implementation\n assert_false(est1 is est2)\n\n\ndef test_multi_output_classification_partial_fit():\n # test if multi_target initializes correctly with base estimator and fit\n # assert predictions work as expected for predict\n\n sgd_linear_clf = SGDClassifier(loss='log', random_state=1)\n multi_target_linear = MultiOutputClassifier(sgd_linear_clf)\n\n # train the multi_target_linear and also get the predictions.\n half_index = X.shape[0] // 2\n multi_target_linear.partial_fit(\n X[:half_index], y[:half_index], classes=classes)\n\n first_predictions = multi_target_linear.predict(X)\n assert_equal((n_samples, n_outputs), first_predictions.shape)\n\n multi_target_linear.partial_fit(X[half_index:], y[half_index:])\n second_predictions = multi_target_linear.predict(X)\n assert_equal((n_samples, n_outputs), second_predictions.shape)\n\n # train the linear classification with each column and assert that\n # predictions are equal after first partial_fit and second partial_fit\n for i in range(3):\n # create a clone with the same state\n sgd_linear_clf = clone(sgd_linear_clf)\n sgd_linear_clf.partial_fit(\n X[:half_index], y[:half_index, i], classes=classes[i])\n assert_array_equal(sgd_linear_clf.predict(X), first_predictions[:, i])\n sgd_linear_clf.partial_fit(X[half_index:], y[half_index:, i])\n assert_array_equal(sgd_linear_clf.predict(X), second_predictions[:, i])\n\n\ndef test_mutli_output_classifiation_partial_fit_no_first_classes_exception():\n sgd_linear_clf = SGDClassifier(loss='log', random_state=1)\n multi_target_linear = MultiOutputClassifier(sgd_linear_clf)\n assert_raises_regex(ValueError, \"classes must be passed on the first call \"\n \"to partial_fit.\",\n multi_target_linear.partial_fit, X, y)\n\n\ndef test_multi_output_classification():\n # test if multi_target initializes correctly with base estimator and fit\n # assert predictions work as expected for predict, prodict_proba and score\n\n forest = RandomForestClassifier(n_estimators=10, random_state=1)\n multi_target_forest = MultiOutputClassifier(forest)\n\n # train the multi_target_forest and also get the predictions.\n multi_target_forest.fit(X, y)\n\n predictions = multi_target_forest.predict(X)\n assert_equal((n_samples, n_outputs), predictions.shape)\n\n predict_proba = multi_target_forest.predict_proba(X)\n\n assert len(predict_proba) == n_outputs\n for class_probabilities in predict_proba:\n assert_equal((n_samples, n_classes), class_probabilities.shape)\n\n assert_array_equal(np.argmax(np.dstack(predict_proba), axis=1),\n predictions)\n\n # train the forest with each column and assert that predictions are equal\n for i in range(3):\n forest_ = clone(forest) # create a clone with the same state\n forest_.fit(X, y[:, i])\n assert_equal(list(forest_.predict(X)), list(predictions[:, i]))\n assert_array_equal(list(forest_.predict_proba(X)),\n list(predict_proba[i]))\n\n\ndef test_multiclass_multioutput_estimator():\n # test to check meta of meta estimators\n svc = LinearSVC(random_state=0)\n multi_class_svc = OneVsRestClassifier(svc)\n multi_target_svc = MultiOutputClassifier(multi_class_svc)\n\n multi_target_svc.fit(X, y)\n\n predictions = multi_target_svc.predict(X)\n assert_equal((n_samples, n_outputs), predictions.shape)\n\n # train the forest with each column and assert that predictions are equal\n for i in range(3):\n multi_class_svc_ = clone(multi_class_svc) # create a clone\n multi_class_svc_.fit(X, y[:, i])\n assert_equal(list(multi_class_svc_.predict(X)),\n list(predictions[:, i]))\n\n\ndef test_multiclass_multioutput_estimator_predict_proba():\n seed = 542\n\n # make test deterministic\n rng = np.random.RandomState(seed)\n\n # random features\n X = rng.normal(size=(5, 5))\n\n # random labels\n y1 = np.array(['b', 'a', 'a', 'b', 'a']).reshape(5, 1) # 2 classes\n y2 = np.array(['d', 'e', 'f', 'e', 'd']).reshape(5, 1) # 3 classes\n\n Y = np.concatenate([y1, y2], axis=1)\n\n clf = MultiOutputClassifier(LogisticRegression(random_state=seed))\n\n clf.fit(X, Y)\n\n y_result = clf.predict_proba(X)\n y_actual = [np.array([[0.23481764, 0.76518236],\n [0.67196072, 0.32803928],\n [0.54681448, 0.45318552],\n [0.34883923, 0.65116077],\n [0.73687069, 0.26312931]]),\n np.array([[0.5171785, 0.23878628, 0.24403522],\n [0.22141451, 0.64102704, 0.13755846],\n [0.16751315, 0.18256843, 0.64991843],\n [0.27357372, 0.55201592, 0.17441036],\n [0.65745193, 0.26062899, 0.08191907]])]\n\n for i in range(len(y_actual)):\n assert_almost_equal(y_result[i], y_actual[i])\n\n\ndef test_multi_output_classification_sample_weights():\n # weighted classifier\n Xw = [[1, 2, 3], [4, 5, 6]]\n yw = [[3, 2], [2, 3]]\n w = np.asarray([2., 1.])\n forest = RandomForestClassifier(n_estimators=10, random_state=1)\n clf_w = MultiOutputClassifier(forest)\n clf_w.fit(Xw, yw, w)\n\n # unweighted, but with repeated samples\n X = [[1, 2, 3], [1, 2, 3], [4, 5, 6]]\n y = [[3, 2], [3, 2], [2, 3]]\n forest = RandomForestClassifier(n_estimators=10, random_state=1)\n clf = MultiOutputClassifier(forest)\n clf.fit(X, y)\n\n X_test = [[1.5, 2.5, 3.5], [3.5, 4.5, 5.5]]\n assert_almost_equal(clf.predict(X_test), clf_w.predict(X_test))\n\n\ndef test_multi_output_classification_partial_fit_sample_weights():\n # weighted classifier\n Xw = [[1, 2, 3], [4, 5, 6], [1.5, 2.5, 3.5]]\n yw = [[3, 2], [2, 3], [3, 2]]\n w = np.asarray([2., 1., 1.])\n sgd_linear_clf = SGDClassifier(random_state=1)\n clf_w = MultiOutputClassifier(sgd_linear_clf)\n clf_w.fit(Xw, yw, w)\n\n # unweighted, but with repeated samples\n X = [[1, 2, 3], [1, 2, 3], [4, 5, 6], [1.5, 2.5, 3.5]]\n y = [[3, 2], [3, 2], [2, 3], [3, 2]]\n sgd_linear_clf = SGDClassifier(random_state=1)\n clf = MultiOutputClassifier(sgd_linear_clf)\n clf.fit(X, y)\n X_test = [[1.5, 2.5, 3.5]]\n assert_array_almost_equal(clf.predict(X_test), clf_w.predict(X_test))\n\n\ndef test_multi_output_exceptions():\n # NotFittedError when fit is not done but score, predict and\n # and predict_proba are called\n moc = MultiOutputClassifier(LinearSVC(random_state=0))\n assert_raises(NotFittedError, moc.predict, y)\n assert_raises(NotFittedError, moc.predict_proba, y)\n assert_raises(NotFittedError, moc.score, X, y)\n # ValueError when number of outputs is different\n # for fit and score\n y_new = np.column_stack((y1, y2))\n moc.fit(X, y)\n assert_raises(ValueError, moc.score, X, y_new)\n"},"repo_name":{"kind":"string","value":"scikit-learn_scikit-learn"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"9f6b849c3523faf2271dea105e4129cb1e1a1cb8"}}},{"rowIdx":95,"cells":{"file_path":{"kind":"string","value":"build_tools/circle/checkout_merge_commit.sh"},"num_changed_lines":{"kind":"number","value":29,"string":"29"},"code":{"kind":"string","value":"#!/bin/bash\n\n\n# Add `master` branch to the update list.\n# Otherwise CircleCI will give us a cached one.\nFETCH_REFS=\"+master:master\"\n\n# Update PR refs for testing.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n FETCH_REFS=\"${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/head:pr/${CIRCLE_PR_NUMBER}/head\"\n FETCH_REFS=\"${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/merge:pr/${CIRCLE_PR_NUMBER}/merge\"\nfi\n\n# Retrieve the refs.\ngit fetch -u origin ${FETCH_REFS}\n\n# Checkout the PR merge ref.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n git checkout -qf \"pr/${CIRCLE_PR_NUMBER}/merge\"\nfi\n\n# Check for merge conflicts.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n git branch --merged | grep master > /dev/null\n git branch --merged | grep \"pr/${CIRCLE_PR_NUMBER}/head\" > /dev/null\nfi\n"},"repo_name":{"kind":"string","value":"scikit-learn_scikit-learn"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"9f6b849c3523faf2271dea105e4129cb1e1a1cb8"}}},{"rowIdx":96,"cells":{"file_path":{"kind":"string","value":"doc/sphinxext/sphinx_gallery/notebook.py"},"num_changed_lines":{"kind":"number","value":106,"string":"106"},"code":{"kind":"string","value":"# -*- coding: utf-8 -*-\nr\"\"\"\n============================\nParser for Jupyter notebooks\n============================\n\nClass that holds the Jupyter notebook information\n\n\"\"\"\n# Author: Óscar Nájera\n# License: 3-clause BSD\n\nfrom __future__ import division, absolute_import, print_function\nfrom functools import partial\nimport argparse\nimport json\nimport re\nimport sys\nfrom .py_source_parser import split_code_and_text_blocks\n\n\ndef text2string(content):\n \"\"\"Returns a string without the extra triple quotes\"\"\"\n try:\n return ast.literal_eval(content) + '\\n'\n except Exception:\n return content + '\\n'\n\n\ndef jupyter_notebook_skeleton():\n \"\"\"Returns a dictionary with the elements of a Jupyter notebook\"\"\"\n py_version = sys.version_info\n notebook_skeleton = {\n \"cells\": [],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"Python \" + str(py_version[0]),\n \"language\": \"python\",\n \"name\": \"python\" + str(py_version[0])\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": py_version[0]\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython\" + str(py_version[0]),\n \"version\": '{0}.{1}.{2}'.format(*sys.version_info[:3])\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 0\n }\n return notebook_skeleton\n\n\ndef directive_fun(match, directive):\n \"\"\"Helper to fill in directives\"\"\"\n directive_to_alert = dict(note=\"info\", warning=\"danger\")\n return ('

{1}

{2}

'\n .format(directive_to_alert[directive], directive.capitalize(),\n match.group(1).strip()))\n\n\ndef rst2md(text):\n \"\"\"Converts the RST text from the examples docstrigs and comments\n into markdown text for the Jupyter notebooks\"\"\"\n\n top_heading = re.compile(r'^=+$\\s^([\\w\\s-]+)^=+$', flags=re.M)\n text = re.sub(top_heading, r'# \\1', text)\n\n math_eq = re.compile(r'^\\.\\. math::((?:.+)?(?:\\n+^ .+)*)', flags=re.M)\n text = re.sub(math_eq,\n lambda match: r'\\begin{{align}}{0}\\end{{align}}'.format(\n match.group(1).strip()),\n text)\n inline_math = re.compile(r':math:`(.+?)`', re.DOTALL)\n text = re.sub(inline_math, r'$\\1$', text)\n\n directives = ('warning', 'note')\n for directive in directives:\n directive_re = re.compile(r'^\\.\\. %s::((?:.+)?(?:\\n+^ .+)*)'\n % directive, flags=re.M)\n text = re.sub(directive_re,\n partial(directive_fun, directive=directive), text)\n\n links = re.compile(r'^ *\\.\\. _.*:.*$\\n', flags=re.M)\n text = re.sub(links, '', text)\n\n refs = re.compile(r':ref:`')\n text = re.sub(refs, '`', text)\n\n contents = re.compile(r'^\\s*\\.\\. contents::.*$(\\n +:\\S+: *$)*\\n',\n flags=re.M)\n text = re.sub(contents, '', text)\n\n images = re.compile(\n r'^\\.\\. image::(.*$)(?:\\n *:alt:(.*$)\\n)?(?: +:\\S+:.*$\\n)*',\n flags=re.M)\n text = re.sub(\n images, lambda match: '![{1}]({0})\\n'.format(\n match.group(1).strip(), (match.group(2) or '').strip()), text)\n\n return text\n\n\ndef jupyter_notebook(script_blocks):\n \"\"\"Generate a Jupyter notebook file cell-by-cell\n\n Parameters\n ----------\n script_blocks: list\n script execution cells\n \"\"\"\n\n work_notebook = jupyter_notebook_skeleton()\n add_code_cell(work_notebook, \"%matplotlib inline\")\n fill_notebook(work_notebook, script_blocks)\n\n return work_notebook\n\n\ndef add_code_cell(work_notebook, code):\n \"\"\"Add a code cell to the notebook\n\n Parameters\n ----------\n code : str\n Cell content\n \"\"\"\n\n code_cell = {\n \"cell_type\": \"code\",\n \"execution_count\": None,\n \"metadata\": {\"collapsed\": False},\n \"outputs\": [],\n \"source\": [code.strip()]\n }\n work_notebook[\"cells\"].append(code_cell)\n\n\ndef add_markdown_cell(work_notebook, text):\n \"\"\"Add a markdown cell to the notebook\n\n Parameters\n ----------\n code : str\n Cell content\n \"\"\"\n markdown_cell = {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [rst2md(text)]\n }\n work_notebook[\"cells\"].append(markdown_cell)\n\n\ndef fill_notebook(work_notebook, script_blocks):\n \"\"\"Writes the Jupyter notebook cells\n\n Parameters\n ----------\n script_blocks : list of tuples\n \"\"\"\n\n for blabel, bcontent in script_blocks:\n if blabel == 'code':\n add_code_cell(work_notebook, bcontent)\n else:\n add_markdown_cell(work_notebook, text2string(bcontent))\n\n\ndef save_notebook(work_notebook, write_file):\n \"\"\"Saves the Jupyter work_notebook to write_file\"\"\"\n with open(write_file, 'w') as out_nb:\n json.dump(work_notebook, out_nb, indent=2)\n\n\n###############################################################################\n# Notebook shell utility\n\ndef python_to_jupyter_cli(args=None, namespace=None):\n \"\"\"Exposes the jupyter notebook renderer to the command line\n\n Takes the same arguments as ArgumentParser.parse_args\n \"\"\"\n parser = argparse.ArgumentParser(\n description='Sphinx-Gallery Notebook converter')\n parser.add_argument('python_src_file', nargs='+',\n help='Input Python file script to convert. '\n 'Supports multiple files and shell wildcards'\n ' (e.g. *.py)')\n args = parser.parse_args(args, namespace)\n\n for src_file in args.python_src_file:\n blocks = split_code_and_text_blocks(src_file)\n print('Converting {0}'.format(src_file))\n example_nb = jupyter_notebook(blocks)\n save_notebook(example_nb, src_file.replace('.py', '.ipynb'))\n"},"repo_name":{"kind":"string","value":"scikit-learn_scikit-learn"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"9f6b849c3523faf2271dea105e4129cb1e1a1cb8"}}},{"rowIdx":97,"cells":{"file_path":{"kind":"string","value":"doc/sphinxext/sphinx_gallery/py_source_parser.py"},"num_changed_lines":{"kind":"number","value":88,"string":"88"},"code":{"kind":"string","value":"# -*- coding: utf-8 -*-\nr\"\"\"\nParser for python source files\n==============================\n\"\"\"\n# Created Sun Nov 27 14:03:07 2016\n# Author: Óscar Nájera\n\nfrom __future__ import division, absolute_import, print_function\nimport ast\nimport re\nfrom textwrap import dedent\n\n\ndef get_docstring_and_rest(filename):\n \"\"\"Separate `filename` content between docstring and the rest\n\n Strongly inspired from ast.get_docstring.\n\n Returns\n -------\n docstring: str\n docstring of `filename`\n rest: str\n `filename` content without the docstring\n \"\"\"\n # can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't\n # seem to work with unicode strings in Python2.7\n # \"SyntaxError: encoding declaration in Unicode string\"\n with open(filename, 'rb') as f:\n content = f.read()\n # change from Windows format to UNIX for uniformity\n content = content.replace(b'\\r\\n', b'\\n')\n\n node = ast.parse(content)\n if not isinstance(node, ast.Module):\n raise TypeError(\"This function only supports modules. \"\n \"You provided {0}\".format(node.__class__.__name__))\n if node.body and isinstance(node.body[0], ast.Expr) and \\\n isinstance(node.body[0].value, ast.Str):\n docstring_node = node.body[0]\n docstring = docstring_node.value.s\n if hasattr(docstring, 'decode'): # python2.7\n docstring = docstring.decode('utf-8')\n # This get the content of the file after the docstring last line\n # Note: 'maxsplit' argument is not a keyword argument in python2\n rest = content.decode('utf-8').split('\\n', docstring_node.lineno)[-1]\n return docstring, rest\n else:\n raise ValueError(('Could not find docstring in file \"{0}\". '\n 'A docstring is required by sphinx-gallery')\n .format(filename))\n\n\ndef split_code_and_text_blocks(source_file):\n \"\"\"Return list with source file separated into code and text blocks.\n\n Returns\n -------\n blocks : list of (label, content)\n List where each element is a tuple with the label ('text' or 'code'),\n and content string of block.\n \"\"\"\n docstring, rest_of_content = get_docstring_and_rest(source_file)\n blocks = [('text', docstring)]\n\n pattern = re.compile(\n r'(?P^#{20,}.*)\\s(?P(?:^#.*\\s)*)',\n flags=re.M)\n\n pos_so_far = 0\n for match in re.finditer(pattern, rest_of_content):\n match_start_pos, match_end_pos = match.span()\n code_block_content = rest_of_content[pos_so_far:match_start_pos]\n text_content = match.group('text_content')\n sub_pat = re.compile('^#', flags=re.M)\n text_block_content = dedent(re.sub(sub_pat, '', text_content)).lstrip()\n if code_block_content.strip():\n blocks.append(('code', code_block_content))\n if text_block_content.strip():\n blocks.append(('text', text_block_content))\n pos_so_far = match_end_pos\n\n remaining_content = rest_of_content[pos_so_far:]\n if remaining_content.strip():\n blocks.append(('code', remaining_content))\n\n return blocks\n"},"repo_name":{"kind":"string","value":"scikit-learn_scikit-learn"},"commit_date":{"kind":"string","value":"2017-01-26"},"sha":{"kind":"string","value":"9f6b849c3523faf2271dea105e4129cb1e1a1cb8"}}},{"rowIdx":98,"cells":{"file_path":{"kind":"string","value":"doc/themes/scikit-learn/static/jquery.js"},"num_changed_lines":{"kind":"number","value":4,"string":"4"},"code":{"kind":"string","value":"/*! jQuery v3.1.1 | (c) jQuery Foundation | jquery.org/license */\n!function(a,b){\"use strict\";\"object\"==typeof module&&\"object\"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error(\"jQuery requires a window with a document\");return b(a)}:b(a)}(\"undefined\"!=typeof window?window:this,function(a,b){\"use strict\";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement(\"script\");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q=\"3.1.1\",r=function(a,b){return new r.fn.init(a,b)},s=/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u=\"sizzle\"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c+~]|\"+K+\")\"+K+\"*\"),S=new RegExp(\"=\"+K+\"*([^\\\\]'\\\"]*?)\"+K+\"*\\\\]\",\"g\"),T=new RegExp(N),U=new RegExp(\"^\"+L+\"$\"),V={ID:new RegExp(\"^#(\"+L+\")\"),CLASS:new RegExp(\"^\\\\.(\"+L+\")\"),TAG:new RegExp(\"^(\"+L+\"|[*])\"),ATTR:new RegExp(\"^\"+M),PSEUDO:new RegExp(\"^\"+N),CHILD:new RegExp(\"^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\\\(\"+K+\"*(even|odd|(([+-]|)(\\\\d*)n|)\"+K+\"*(?:([+-]|)\"+K+\"*(\\\\d+)|))\"+K+\"*\\\\)|)\",\"i\"),bool:new RegExp(\"^(?:\"+J+\")$\",\"i\"),needsContext:new RegExp(\"^\"+K+\"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\\\(\"+K+\"*((?:-\\\\d)?\\\\d*)\"+K+\"*\\\\)|)(?=[^-]|$)\",\"i\")},W=/^(?:input|select|textarea|button)$/i,X=/^h\\d$/i,Y=/^[^{]+\\{\\s*\\[native \\w/,Z=/^(?:#([\\w-]+)|(\\w+)|\\.([\\w-]+))$/,$=/[+~]/,_=new RegExp(\"\\\\\\\\([\\\\da-f]{1,6}\"+K+\"?|(\"+K+\")|.)\",\"ig\"),aa=function(a,b,c){var d=\"0x\"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\\0-\\x1f\\x7f]|^-?\\d)|^-$|[^\\0-\\x1f\\x7f-\\uFFFF\\w-]/g,ca=function(a,b){return b?\"\\0\"===a?\"\\ufffd\":a.slice(0,-1)+\"\\\\\"+a.charCodeAt(a.length-1).toString(16)+\" \":\"\\\\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&(\"form\"in a||\"label\"in a)},{dir:\"parentNode\",next:\"legend\"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],\"string\"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+\" \"]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if(\"object\"!==b.nodeName.toLowerCase()){(k=b.getAttribute(\"id\"))?k=k.replace(ba,ca):b.setAttribute(\"id\",k=u),o=g(a),h=o.length;while(h--)o[h]=\"#\"+k+\" \"+sa(o[h]);r=o.join(\",\"),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute(\"id\")}}}return i(a.replace(P,\"$1\"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+\" \")>d.cacheLength&&delete b[a.shift()],b[c+\" \"]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement(\"fieldset\");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split(\"|\"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return\"input\"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return(\"input\"===c||\"button\"===c)&&b.type===a}}function oa(a){return function(b){return\"form\"in b?b.parentNode&&b.disabled===!1?\"label\"in b?\"label\"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:\"label\"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&\"undefined\"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&\"HTML\"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener(\"unload\",da,!1):e.attachEvent&&e.attachEvent(\"onunload\",da)),c.attributes=ja(function(a){return a.className=\"i\",!a.getAttribute(\"className\")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment(\"\")),!a.getElementsByTagName(\"*\").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute(\"id\")===b}},d.find.ID=function(a,b){if(\"undefined\"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c=\"undefined\"!=typeof a.getAttributeNode&&a.getAttributeNode(\"id\");return c&&c.value===b}},d.find.ID=function(a,b){if(\"undefined\"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode(\"id\"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode(\"id\"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return\"undefined\"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if(\"*\"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if(\"undefined\"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML=\"
\",a.querySelectorAll(\"[msallowcapture^='']\").length&&q.push(\"[*^$]=\"+K+\"*(?:''|\\\"\\\")\"),a.querySelectorAll(\"[selected]\").length||q.push(\"\\\\[\"+K+\"*(?:value|\"+J+\")\"),a.querySelectorAll(\"[id~=\"+u+\"-]\").length||q.push(\"~=\"),a.querySelectorAll(\":checked\").length||q.push(\":checked\"),a.querySelectorAll(\"a#\"+u+\"+*\").length||q.push(\".#.+[+~]\")}),ja(function(a){a.innerHTML=\"\";var b=n.createElement(\"input\");b.setAttribute(\"type\",\"hidden\"),a.appendChild(b).setAttribute(\"name\",\"D\"),a.querySelectorAll(\"[name=d]\").length&&q.push(\"name\"+K+\"*[*^$|!~]?=\"),2!==a.querySelectorAll(\":enabled\").length&&q.push(\":enabled\",\":disabled\"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(\":disabled\").length&&q.push(\":enabled\",\":disabled\"),a.querySelectorAll(\"*,:x\"),q.push(\",.*:\")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,\"*\"),s.call(a,\"[s!='']:x\"),r.push(\"!=\",N)}),q=q.length&&new RegExp(q.join(\"|\")),r=r.length&&new RegExp(r.join(\"|\")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,\"='$1']\"),c.matchesSelector&&p&&!A[b+\" \"]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+\"\").replace(ba,ca)},ga.error=function(a){throw new Error(\"Syntax error, unrecognized expression: \"+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c=\"\",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if(\"string\"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{\">\":{dir:\"parentNode\",first:!0},\" \":{dir:\"parentNode\"},\"+\":{dir:\"previousSibling\",first:!0},\"~\":{dir:\"previousSibling\"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||\"\").replace(_,aa),\"~=\"===a[2]&&(a[3]=\" \"+a[3]+\" \"),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),\"nth\"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*(\"even\"===a[3]||\"odd\"===a[3])),a[5]=+(a[7]+a[8]||\"odd\"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||\"\":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(\")\",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return\"*\"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+\" \"];return b||(b=new RegExp(\"(^|\"+K+\")\"+a+\"(\"+K+\"|$)\"))&&y(a,function(a){return b.test(\"string\"==typeof a.className&&a.className||\"undefined\"!=typeof a.getAttribute&&a.getAttribute(\"class\")||\"\")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?\"!=\"===b:!b||(e+=\"\",\"=\"===b?e===c:\"!=\"===b?e!==c:\"^=\"===b?c&&0===e.indexOf(c):\"*=\"===b?c&&e.indexOf(c)>-1:\"$=\"===b?c&&e.slice(-c.length)===c:\"~=\"===b?(\" \"+e.replace(O,\" \")+\" \").indexOf(c)>-1:\"|=\"===b&&(e===c||e.slice(0,c.length+1)===c+\"-\"))}},CHILD:function(a,b,c,d,e){var f=\"nth\"!==a.slice(0,3),g=\"last\"!==a.slice(-4),h=\"of-type\"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?\"nextSibling\":\"previousSibling\",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p=\"only\"===a&&!o&&\"nextSibling\"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error(\"unsupported pseudo: \"+a);return e[u]?e(b):e.length>1?(c=[a,a,\"\",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,\"$1\"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||\"\")||ga.error(\"unsupported lang: \"+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute(\"xml:lang\")||b.getAttribute(\"lang\"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+\"-\");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return\"input\"===b&&!!a.checked||\"option\"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return\"input\"===b&&\"button\"===a.type||\"button\"===b},text:function(a){var b;return\"input\"===a.nodeName.toLowerCase()&&\"text\"===a.type&&(null==(b=a.getAttribute(\"type\"))||\"text\"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[\" \"],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:\" \"===a[i-2].type?\"*\":\"\"})).replace(P,\"$1\"),c,i0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s=\"0\",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG(\"*\",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+\" \"];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m=\"function\"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&\"ID\"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split(\"\").sort(B).join(\"\")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement(\"fieldset\"))}),ja(function(a){return a.innerHTML=\"\",\"#\"===a.firstChild.getAttribute(\"href\")})||ka(\"type|href|height|width\",function(a,b,c){if(!c)return a.getAttribute(b,\"type\"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML=\"\",a.firstChild.setAttribute(\"value\",\"\"),\"\"===a.firstChild.getAttribute(\"value\")})||ka(\"value\",function(a,b,c){if(!c&&\"input\"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute(\"disabled\")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[\":\"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext,B=/^<([a-z][^\\/\\0>:\\x20\\t\\r\\n\\f]*)[\\x20\\t\\r\\n\\f]*\\/?>(?:<\\/\\1>|)$/i,C=/^.[^:#\\[\\.,]*$/;function D(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):\"string\"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):C.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=\":not(\"+a+\")\"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if(\"string\"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(D(this,a||[],!1))},not:function(a){return this.pushStack(D(this,a||[],!0))},is:function(a){return!!D(this,\"string\"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var E,F=/^(?:\\s*(<[\\w\\W]+>)[^>]*|#([\\w-]+))$/,G=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||E,\"string\"==typeof a){if(e=\"<\"===a[0]&&\">\"===a[a.length-1]&&a.length>=3?[null,a,null]:F.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),B.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};G.prototype=r.fn,E=r(d);var H=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?\"string\"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function J(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,\"parentNode\")},parentsUntil:function(a,b,c){return y(a,\"parentNode\",c)},next:function(a){return J(a,\"nextSibling\")},prev:function(a){return J(a,\"previousSibling\")},nextAll:function(a){return y(a,\"nextSibling\")},prevAll:function(a){return y(a,\"previousSibling\")},nextUntil:function(a,b,c){return y(a,\"nextSibling\",c)},prevUntil:function(a,b,c){return y(a,\"previousSibling\",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return a.contentDocument||r.merge([],a.childNodes)}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return\"Until\"!==a.slice(-5)&&(d=c),d&&\"string\"==typeof d&&(e=r.filter(d,e)),this.length>1&&(I[a]||r.uniqueSort(e),H.test(a)&&e.reverse()),this.pushStack(e)}});var K=/[^\\x20\\t\\r\\n\\f]+/g;function L(a){var b={};return r.each(a.match(K)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a=\"string\"==typeof a?L(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c=\"\",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=\"\"),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function M(a){return a}function N(a){throw a}function O(a,b,c){var d;try{a&&r.isFunction(d=a.promise)?d.call(a).done(b).fail(c):a&&r.isFunction(d=a.then)?d.call(a,b,c):b.call(void 0,a)}catch(a){c.call(void 0,a)}}r.extend({Deferred:function(b){var c=[[\"notify\",\"progress\",r.Callbacks(\"memory\"),r.Callbacks(\"memory\"),2],[\"resolve\",\"done\",r.Callbacks(\"once memory\"),r.Callbacks(\"once memory\"),0,\"resolved\"],[\"reject\",\"fail\",r.Callbacks(\"once memory\"),r.Callbacks(\"once memory\"),1,\"rejected\"]],d=\"pending\",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},\"catch\":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+\"With\"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b=f&&(d!==N&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:M,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:M)),c[2][3].add(g(0,a,r.isFunction(d)?d:N))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+\"With\"](this===f?void 0:this,arguments),this},f[b[0]+\"With\"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(O(a,g.done(h(c)).resolve,g.reject),\"pending\"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)O(e[c],h(c),g.reject);return g.promise()}});var P=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&P.test(b.name)&&a.console.warn(\"jQuery.Deferred exception: \"+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var Q=r.Deferred();r.fn.ready=function(a){return Q.then(a)[\"catch\"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,holdReady:function(a){a?r.readyWait++:r.ready(!0)},ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||Q.resolveWith(d,[r]))}}),r.ready.then=Q.then;function R(){d.removeEventListener(\"DOMContentLoaded\",R),\na.removeEventListener(\"load\",R),r.ready()}\"complete\"===d.readyState||\"loading\"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener(\"DOMContentLoaded\",R),a.addEventListener(\"load\",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if(\"object\"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||\"fx\")+\"queue\",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||\"fx\";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};\"inprogress\"===e&&(e=c.shift(),d--),e&&(\"fx\"===b&&c.unshift(\"inprogress\"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+\"queueHooks\";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks(\"once memory\").add(function(){V.remove(a,[b+\"queue\",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return\"string\"!=typeof a&&(b=a,a=\"fx\",c--),arguments.length\\x20\\t\\r\\n\\f]+)/i,ka=/^$|\\/(?:java|ecma)script/i,la={option:[1,\"\"],thead:[1,\"\",\"
\"],col:[2,\"\",\"
\"],tr:[2,\"\",\"
\"],td:[3,\"\",\"
\"],_default:[0,\"\",\"\"]};la.optgroup=la.option,la.tbody=la.tfoot=la.colgroup=la.caption=la.thead,la.th=la.td;function ma(a,b){var c;return c=\"undefined\"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||\"*\"):\"undefined\"!=typeof a.querySelectorAll?a.querySelectorAll(b||\"*\"):[],void 0===b||b&&r.nodeName(a,b)?r.merge([a],c):c}function na(a,b){for(var c=0,d=a.length;c-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=ma(l.appendChild(f),\"script\"),j&&na(g),c){k=0;while(f=g[k++])ka.test(f.type||\"\")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement(\"div\")),c=d.createElement(\"input\");c.setAttribute(\"type\",\"radio\"),c.setAttribute(\"checked\",\"checked\"),c.setAttribute(\"name\",\"t\"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML=\"\",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var qa=d.documentElement,ra=/^key/,sa=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ta=/^([^.]*)(?:\\.(.+)|)/;function ua(){return!0}function va(){return!1}function wa(){try{return d.activeElement}catch(a){}}function xa(a,b,c,d,e,f){var g,h;if(\"object\"==typeof b){\"string\"!=typeof c&&(d=d||c,c=void 0);for(h in b)xa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&(\"string\"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=va;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(qa,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return\"undefined\"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||\"\").match(K)||[\"\"],j=b.length;while(j--)h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||\"\").split(\".\").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(\".\")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.hasData(a)&&V.get(a);if(q&&(i=q.events)){b=(b||\"\").match(K)||[\"\"],j=b.length;while(j--)if(h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||\"\").split(\".\").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp(\"(^|\\\\.)\"+o.join(\"\\\\.(?:.*\\\\.|)\")+\"(\\\\.|$)\"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&(\"**\"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&V.remove(a,\"handle events\")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(V.get(this,\"events\")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&(\"click\"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i\\x20\\t\\r\\n\\f]*)[^>]*)\\/>/gi,za=/\\s*$/g;function Da(a,b){return r.nodeName(a,\"table\")&&r.nodeName(11!==b.nodeType?b:b.firstChild,\"tr\")?a.getElementsByTagName(\"tbody\")[0]||a:a}function Ea(a){return a.type=(null!==a.getAttribute(\"type\"))+\"/\"+a.type,a}function Fa(a){var b=Ba.exec(a.type);return b?a.type=b[1]:a.removeAttribute(\"type\"),a}function Ga(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(V.hasData(a)&&(f=V.access(a),g=V.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c1&&\"string\"==typeof q&&!o.checkClone&&Aa.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ia(f,b,c,d)});if(m&&(e=pa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(ma(e,\"script\"),Ea),i=h.length;l\")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=ma(h),f=ma(a),d=0,e=f.length;d0&&na(g,!i&&ma(a,\"script\")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(T(c)){if(b=c[V.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[V.expando]=void 0}c[W.expando]&&(c[W.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ja(this,a,!0)},remove:function(a){return Ja(this,a)},text:function(a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.appendChild(a)}})},prepend:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(ma(a,!1)),a.textContent=\"\");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return S(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if(\"string\"==typeof a&&!za.test(a)&&!la[(ja.exec(a)||[\"\",\"\"])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c1)}});function Ya(a,b,c,d,e){return new Ya.prototype.init(a,b,c,d,e)}r.Tween=Ya,Ya.prototype={constructor:Ya,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?\"\":\"px\")},cur:function(){var a=Ya.propHooks[this.prop];return a&&a.get?a.get(this):Ya.propHooks._default.get(this)},run:function(a){var b,c=Ya.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ya.propHooks._default.set(this),this}},Ya.prototype.init.prototype=Ya.prototype,Ya.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,\"\"),b&&\"auto\"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},Ya.propHooks.scrollTop=Ya.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:\"swing\"},r.fx=Ya.prototype.init,r.fx.step={};var Za,$a,_a=/^(?:toggle|show|hide)$/,ab=/queueHooks$/;function bb(){$a&&(a.requestAnimationFrame(bb),r.fx.tick())}function cb(){return a.setTimeout(function(){Za=void 0}),Za=r.now()}function db(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ba[d],e[\"margin\"+c]=e[\"padding\"+c]=a;return b&&(e.opacity=e.width=a),e}function eb(a,b,c){for(var d,e=(hb.tweeners[b]||[]).concat(hb.tweeners[\"*\"]),f=0,g=e.length;f1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return\"undefined\"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?ib:void 0)),\nvoid 0!==c?null===c?void r.removeAttr(a,b):e&&\"set\"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+\"\"),c):e&&\"get\"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&\"radio\"===b&&r.nodeName(a,\"input\")){var c=a.value;return a.setAttribute(\"type\",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),ib={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\\w+/g),function(a,b){var c=jb[b]||r.find.attr;jb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=jb[g],jb[g]=e,e=null!=c(a,b,d)?g:null,jb[g]=f),e}});var kb=/^(?:input|select|textarea|button)$/i,lb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&\"set\"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&\"get\"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,\"tabindex\");return b?parseInt(b,10):kb.test(a.nodeName)||lb.test(a.nodeName)&&a.href?0:-1}}},propFix:{\"for\":\"htmlFor\",\"class\":\"className\"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each([\"tabIndex\",\"readOnly\",\"maxLength\",\"cellSpacing\",\"cellPadding\",\"rowSpan\",\"colSpan\",\"useMap\",\"frameBorder\",\"contentEditable\"],function(){r.propFix[this.toLowerCase()]=this});function mb(a){var b=a.match(K)||[];return b.join(\" \")}function nb(a){return a.getAttribute&&a.getAttribute(\"class\")||\"\"}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,nb(this)))});if(\"string\"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&\" \"+mb(e)+\" \"){g=0;while(f=b[g++])d.indexOf(\" \"+f+\" \")<0&&(d+=f+\" \");h=mb(d),e!==h&&c.setAttribute(\"class\",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,nb(this)))});if(!arguments.length)return this.attr(\"class\",\"\");if(\"string\"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&\" \"+mb(e)+\" \"){g=0;while(f=b[g++])while(d.indexOf(\" \"+f+\" \")>-1)d=d.replace(\" \"+f+\" \",\" \");h=mb(d),e!==h&&c.setAttribute(\"class\",h)}}return this},toggleClass:function(a,b){var c=typeof a;return\"boolean\"==typeof b&&\"string\"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,nb(this),b),b)}):this.each(function(){var b,d,e,f;if(\"string\"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&\"boolean\"!==c||(b=nb(this),b&&V.set(this,\"__className__\",b),this.setAttribute&&this.setAttribute(\"class\",b||a===!1?\"\":V.get(this,\"__className__\")||\"\"))})},hasClass:function(a){var b,c,d=0;b=\" \"+a+\" \";while(c=this[d++])if(1===c.nodeType&&(\" \"+mb(nb(c))+\" \").indexOf(b)>-1)return!0;return!1}});var ob=/\\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e=\"\":\"number\"==typeof e?e+=\"\":r.isArray(e)&&(e=r.map(e,function(a){return null==a?\"\":a+\"\"})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&\"set\"in b&&void 0!==b.set(this,e,\"value\")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&\"get\"in b&&void 0!==(c=b.get(e,\"value\"))?c:(c=e.value,\"string\"==typeof c?c.replace(ob,\"\"):null==c?\"\":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,\"value\");return null!=b?b:mb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g=\"select-one\"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each([\"radio\",\"checkbox\"],function(){r.valHooks[this]={set:function(a,b){if(r.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute(\"value\")?\"on\":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,\"type\")?b.type:b,q=l.call(b,\"namespace\")?b.namespace.split(\".\"):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!pb.test(p+r.event.triggered)&&(p.indexOf(\".\")>-1&&(q=p.split(\".\"),p=q.shift(),q.sort()),k=p.indexOf(\":\")<0&&\"on\"+p,b=b[r.expando]?b:new r.Event(p,\"object\"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join(\".\"),b.rnamespace=b.namespace?new RegExp(\"(^|\\\\.)\"+q.join(\"\\\\.(?:.*\\\\.|)\")+\"(\\\\.|$)\"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,pb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(V.get(h,\"events\")||{})[b.type]&&V.get(h,\"handle\"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&T(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!T(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each(\"blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu\".split(\" \"),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin=\"onfocusin\"in a,o.focusin||r.each({focus:\"focusin\",blur:\"focusout\"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=V.access(d,b);e||d.addEventListener(a,c,!0),V.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=V.access(d,b)-1;e?V.access(d,b,e):(d.removeEventListener(a,c,!0),V.remove(d,b))}}});var qb=a.location,rb=r.now(),sb=/\\?/;r.parseXML=function(b){var c;if(!b||\"string\"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,\"text/xml\")}catch(d){c=void 0}return c&&!c.getElementsByTagName(\"parsererror\").length||r.error(\"Invalid XML: \"+b),c};var tb=/\\[\\]$/,ub=/\\r?\\n/g,vb=/^(?:submit|button|image|reset|file)$/i,wb=/^(?:input|select|textarea|keygen)/i;function xb(a,b,c,d){var e;if(r.isArray(b))r.each(b,function(b,e){c||tb.test(a)?d(a,e):xb(a+\"[\"+(\"object\"==typeof e&&null!=e?b:\"\")+\"]\",e,c,d)});else if(c||\"object\"!==r.type(b))d(a,b);else for(e in b)xb(a+\"[\"+e+\"]\",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+\"=\"+encodeURIComponent(null==c?\"\":c)};if(r.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)xb(c,a[c],b,e);return d.join(\"&\")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,\"elements\");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(\":disabled\")&&wb.test(this.nodeName)&&!vb.test(a)&&(this.checked||!ia.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:r.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(ub,\"\\r\\n\")}}):{name:b.name,value:c.replace(ub,\"\\r\\n\")}}).get()}});var yb=/%20/g,zb=/#.*$/,Ab=/([?&])_=[^&]*/,Bb=/^(.*?):[ \\t]*([^\\r\\n]*)$/gm,Cb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Db=/^(?:GET|HEAD)$/,Eb=/^\\/\\//,Fb={},Gb={},Hb=\"*/\".concat(\"*\"),Ib=d.createElement(\"a\");Ib.href=qb.href;function Jb(a){return function(b,c){\"string\"!=typeof b&&(c=b,b=\"*\");var d,e=0,f=b.toLowerCase().match(K)||[];if(r.isFunction(c))while(d=f[e++])\"+\"===d[0]?(d=d.slice(1)||\"*\",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Kb(a,b,c,d){var e={},f=a===Gb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return\"string\"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e[\"*\"]&&g(\"*\")}function Lb(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Mb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while(\"*\"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader(\"Content-Type\"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+\" \"+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Nb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if(\"*\"===f)f=i;else if(\"*\"!==i&&i!==f){if(g=j[i+\" \"+f]||j[\"* \"+f],!g)for(e in j)if(h=e.split(\" \"),h[1]===f&&(g=j[i+\" \"+h[0]]||j[\"* \"+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a[\"throws\"])b=g(b);else try{b=g(b)}catch(l){return{state:\"parsererror\",error:g?l:\"No conversion from \"+i+\" to \"+f}}}return{state:\"success\",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qb.href,type:\"GET\",isLocal:Cb.test(qb.protocol),global:!0,processData:!0,async:!0,contentType:\"application/x-www-form-urlencoded; charset=UTF-8\",accepts:{\"*\":Hb,text:\"text/plain\",html:\"text/html\",xml:\"application/xml, text/xml\",json:\"application/json, text/javascript\"},contents:{xml:/\\bxml\\b/,html:/\\bhtml/,json:/\\bjson\\b/},responseFields:{xml:\"responseXML\",text:\"responseText\",json:\"responseJSON\"},converters:{\"* text\":String,\"text html\":!0,\"text json\":JSON.parse,\"text xml\":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Lb(Lb(a,r.ajaxSettings),b):Lb(r.ajaxSettings,a)},ajaxPrefilter:Jb(Fb),ajaxTransport:Jb(Gb),ajax:function(b,c){\"object\"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks(\"once memory\"),u=o.statusCode||{},v={},w={},x=\"canceled\",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Bb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||qb.href)+\"\").replace(Eb,qb.protocol+\"//\"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||\"*\").toLowerCase().match(K)||[\"\"],null==o.crossDomain){j=d.createElement(\"a\");try{j.href=o.url,j.href=j.href,o.crossDomain=Ib.protocol+\"//\"+Ib.host!=j.protocol+\"//\"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&\"string\"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Kb(Fb,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger(\"ajaxStart\"),o.type=o.type.toUpperCase(),o.hasContent=!Db.test(o.type),f=o.url.replace(zb,\"\"),o.hasContent?o.data&&o.processData&&0===(o.contentType||\"\").indexOf(\"application/x-www-form-urlencoded\")&&(o.data=o.data.replace(yb,\"+\")):(n=o.url.slice(f.length),o.data&&(f+=(sb.test(f)?\"&\":\"?\")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Ab,\"$1\"),n=(sb.test(f)?\"&\":\"?\")+\"_=\"+rb++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader(\"If-Modified-Since\",r.lastModified[f]),r.etag[f]&&y.setRequestHeader(\"If-None-Match\",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader(\"Content-Type\",o.contentType),y.setRequestHeader(\"Accept\",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+(\"*\"!==o.dataTypes[0]?\", \"+Hb+\"; q=0.01\":\"\"):o.accepts[\"*\"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x=\"abort\",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Kb(Gb,o,c,y)){if(y.readyState=1,l&&q.trigger(\"ajaxSend\",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort(\"timeout\")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,\"No Transport\");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||\"\",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Mb(o,y,d)),v=Nb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader(\"Last-Modified\"),w&&(r.lastModified[f]=w),w=y.getResponseHeader(\"etag\"),w&&(r.etag[f]=w)),204===b||\"HEAD\"===o.type?x=\"nocontent\":304===b?x=\"notmodified\":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x=\"error\",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+\"\",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?\"ajaxSuccess\":\"ajaxError\",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger(\"ajaxComplete\",[y,o]),--r.active||r.event.trigger(\"ajaxStop\")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,\"json\")},getScript:function(a,b){return r.get(a,void 0,b,\"script\")}}),r.each([\"get\",\"post\"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:\"GET\",dataType:\"script\",cache:!0,async:!1,global:!1,\"throws\":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not(\"body\").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Ob={0:200,1223:204},Pb=r.ajaxSettings.xhr();o.cors=!!Pb&&\"withCredentials\"in Pb,o.ajax=Pb=!!Pb,r.ajaxTransport(function(b){var c,d;if(o.cors||Pb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e[\"X-Requested-With\"]||(e[\"X-Requested-With\"]=\"XMLHttpRequest\");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,\"abort\"===a?h.abort():\"error\"===a?\"number\"!=typeof h.status?f(0,\"error\"):f(h.status,h.statusText):f(Ob[h.status]||h.status,h.statusText,\"text\"!==(h.responseType||\"text\")||\"string\"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c(\"error\"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c(\"abort\");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:\"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript\"},contents:{script:/\\b(?:java|ecma)script\\b/},converters:{\"text script\":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter(\"script\",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type=\"GET\")}),r.ajaxTransport(\"script\",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r(\"