Best JavaScript code snippet using wpt
userpicker.js
Source:userpicker.js
1/*2 * Userpicker3 * Version 1.0.04 * Written by: Andreas Strobel5 *6 * @property String $inputId is the ID of the input HTML Element7 * @property Int $maxUsers the maximum of users in this dropdown8 * @property String $userSearchUrl the url of the search, to find the users9 * @property String $currentValue is the current value of the parent field.10 *11 */12var userCount = 0;13$.fn.userpicker = function (options) {14 // set standard options15 options = $.extend({16 inputId: "",17 maxUsers: 0,18 searchUrl: "",19 currentValue: "",20 renderType: "normal", // possible values are "normal", "partial"21 focus: false,22 userGuid: "",23 data: {},24 placeholderText: 'Add a user'25 }, options);26 var chosen = "";27 var uniqueID = "";28 init();29 function init() {30 uniqueID = options.inputId.substr(1);31 var _template = '<div class="' + uniqueID + '_user_picker_container"><ul class="tag_input" id="' + uniqueID + '_invite_tags"><li id="' + uniqueID + '_tag_input"><input type="text" id="' + uniqueID + '_tag_input_field" class="tag_input_field" value="" autocomplete="off"></li></ul><ul class="dropdown-menu" id="' + uniqueID + '_userpicker" role="menu" aria-labelledby="dropdownMenu"></ul></div>';32 // remove picker if existing33 $('.'+uniqueID+'_user_picker_container').remove();34 if ($('.' + uniqueID + '_user_picker_container').length == 0) {35 // insert the new input structure after the original input element36 $(options.inputId).after(_template);37 }38 // hide original input element39 $(options.inputId).hide();40 if (options.currentValue != "") {41 // restore data from database42 restoreUserTags(options.currentValue);43 }44 // add placeholder text to input field45 $('#' + uniqueID + '_tag_input_field').attr('placeholder', options.placeholderText);46 if (options.focus == true) {47 // set focus to input48 $('#' + uniqueID + '_tag_input_field').focus();49 $('#' + uniqueID + '_invite_tags').addClass('focus');50 }51 // simulate focus in52 $('#' + uniqueID + '_tag_input_field').focusin(function () {53 $('#' + uniqueID + '_invite_tags').addClass('focus');54 })55 // simulate focus out56 $('#' + uniqueID + '_tag_input_field').focusout(function () {57 $('#' + uniqueID + '_invite_tags').removeClass('focus');58 })59 }60 function restoreUserTags(html) {61 // add html structure for input element62 $('#' + uniqueID + '_invite_tags .userInput').remove();63 $('#' + uniqueID + '_invite_tags').prepend(html);64 // create function for every user tag to remove the element65 $('#' + uniqueID + '_invite_tags .userInput i').each(function () {66 $(this).click(function () {67 // remove user tag68 $(this).parent().remove();69 // reduce the count of added user70 userCount--;71 })72 // raise the count of added user73 userCount++;74 })75 }76 // Set focus on the input field, by clicking the <ul> construct77 jQuery('#' + uniqueID + '_invite_tags').click(function () {78 // set focus79 $('#' + uniqueID + '_tag_input_field').focus();80 });81 $('#' + uniqueID + '_tag_input_field').keydown(function (event) {82 // by pressing the tab key an the input is empty83 if ($(this).val() == "" && event.keyCode == 9) {84 //do nothing85 // by pressing enter, tab, up or down arrow86 } else if (event.keyCode == 40 || event.keyCode == 38 || event.keyCode == 13 || event.keyCode == 9) {87 // ... disable the default behavior to hold the cursor at the end of the string88 event.preventDefault();89 }90 // if there is a user limit and the user didn't press the tab key91 if (options.maxUsers != 0 && event.keyCode != 9) {92 // if the max user count is reached93 if (userCount == options.maxUsers) {94 // show hint95 showHintUser();96 // block input events97 event.preventDefault();98 }99 }100 });101 $('#' + uniqueID + '_tag_input_field').keyup(function (event) {102 // start search after a specific count of characters103 if ($('#' + uniqueID + '_tag_input_field').val().length >= 3) {104 // set userpicker position in bottom of the user input105 $('#' + uniqueID + '_userpicker').css({106 position: "absolute",107 top: $('#' + uniqueID + '_tag_input_field').position().top + 30,108 left: $('#' + uniqueID + '_tag_input_field').position().left + 0109 })110 if (event.keyCode == 40) {111 // select next <li> element112 if (chosen === "") {113 chosen = 1;114 } else if ((chosen + 1) < $('#' + uniqueID + '_userpicker li').length) {115 chosen++;116 }117 $('#' + uniqueID + '_userpicker li').removeClass('selected');118 $('#' + uniqueID + '_userpicker li:eq(' + chosen + ')').addClass('selected');119 return false;120 } else if (event.keyCode == 38) {121 // select previous <li> element122 if (chosen === "") {123 chosen = 1;124 } else if (chosen > 0) {125 chosen--;126 }127 $('#' + uniqueID + '_userpicker li').removeClass('selected');128 $('#' + uniqueID + '_userpicker li:eq(' + chosen + ')').addClass('selected');129 return false;130 } else if (event.keyCode == 13 || event.keyCode == 9) {131 var href = $('#' + uniqueID + '_userpicker .selected a').attr('href');132 // simulate click event when href is not undefined.133 if (href !== undefined) {134 window.location.href = href;135 }136 } else {137 // save the search string to variable138 var str = $('#' + uniqueID + '_tag_input_field').val();139 // show userpicker with the results140 $('#' + uniqueID + '_userpicker').show();141 // load users142 loadUser(str);143 }144 } else {145 // hide userpicker146 $('#' + uniqueID + '_userpicker').hide();147 }148 });149 $('#' + uniqueID + '_tag_input_field').focusout(function () {150 // set the plain text including user guids to the original input or textarea element151 $(options.inputId).val($.fn.userpicker.parseUserInput(uniqueID));152 });153 function loadUser(keyword) {154 // remove existings entries155 $('#' + uniqueID + '_userpicker li').remove();156 // show loader while loading157 $('#' + uniqueID + '_userpicker').html('<li><div class="loader"><div class="sk-spinner sk-spinner-three-bounce"><div class="sk-bounce1"></div><div class="sk-bounce2"></div><div class="sk-bounce3"></div></div></div></li>');158 // build data object159 var data = options['data'] || {};160 161 //This is the preferred way of adding the keyword162 if(options['searchUrl'].indexOf('-keywordPlaceholder-') < 0) {163 data['keyword'] = keyword;164 }165 166 //Set the user role filter167 if(options['userRole']) {168 data['userRole'] = options['userRole'];169 }170 jQuery.getJSON(options.searchUrl.replace('-keywordPlaceholder-', keyword), data, function (json) {171 // remove existings entries172 $('#' + uniqueID + '_userpicker li').remove();173 // sort by disabled/enabled and contains keyword174 json.sort(function(a,b) {175 if(a.disabled !== b.disabled) {176 return (a.disabled < b.disabled) ? -1 : 1;177 } else if(a.priority !== b.priority) {178 return (a.priority > b.priority) ? -1 : 1;179 } else if(a.displayName.indexOf(keyword) >= 0 && b.displayName.indexOf(keyword) < 0) {180 return -1;181 } else if(a.displayName.indexOf(keyword) < 0 && b.displayName.indexOf(keyword) >= 0) {182 return 1;183 }184 185 return 0;186 });187 if (json.length > 0) {188 for (var i = 0; i < json.length; i++) {189 var _takenStyle = "";190 var _takenData = false;191 192 // set options to link, that this entry is already taken or not available193 if (json[i].disabled == true || $('#' + uniqueID + '_' + json[i].guid).length || $('#'+json[i].guid).length || json[i].isMember == true || json[i].guid == options.userGuid) {194 _takenStyle = "opacity: 0.4;"195 _takenData = true;196 }197 // build <li> entry198 var str = '<li id="user_' + json[i].guid + '"><a style="' + _takenStyle + '" data-taken="' + _takenData + '" tabindex="-1" href="javascript:$.fn.userpicker.addUserTag(\'' + json[i].guid + '\', \'' + json[i].image + '\', \'' + json[i].displayName.replace(/'/g, "\\'") + '\', \'' + uniqueID + '\');"><img class="img-rounded" src="' + json[i].image + '" height="20" width="20" alt=""/> ' + json[i].displayName + '</a></li>';199 // append the entry to the <ul> list200 $('#' + uniqueID + '_userpicker').append(str);201 }202 // check if the list is empty203 if ($('#' + uniqueID + '_userpicker').children().length == 0) {204 // hide userpicker, if it is205 $('#' + uniqueID + '_userpicker').hide();206 }207 // reset the variable for arrows keys208 chosen = "";209 } else {210 // hide userpicker, if no user was found211 $('#' + uniqueID + '_userpicker').hide();212 }213 // remove hightlight214 $('#' + uniqueID + '_userpicker li').removeHighlight();215 // add new highlight matching strings216 $('#' + uniqueID + '_userpicker li').highlight(keyword);217 // add selection to the first space entry218 $('#' + uniqueID + '_userpicker li:eq(0)').addClass('selected');219 })220 }221 function showHintUser() {222 // remove hint, if exists223 $('#maxUsersHint').remove();224 // build html structure225 var _html = '<div id="maxUsersHint" style="display: none;" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button><strong>Sorry!</strong> You can add a maximum of ' + options.maxUsers + ' users as admin for this group.</div>';226 // add hint to DOM227 $('#' + uniqueID + '_invite_tags').after(_html);228 // fadein hint229 $('#maxUsersHint').fadeIn('fast');230 }231}232// Add an usertag for invitation233$.fn.userpicker.addUserTag = function (guid, image_url, name, id) {234 235 if ($('#user_' + guid + ' a').attr('data-taken') != "true") {236 237 // Building a new <li> entry238 var _tagcode = '<li class="userInput" id="' + id + '_' + guid + '"><img class="img-rounded" alt="24x24" data-src="holder.js/24x24" style="width: 24px; height: 24px;" src="' + image_url + '" alt="' + name + '" width="24" height="24" />' + name + '<i class="fa fa-times-circle"></i></li>';239 // insert the new created <li> entry into the <ul> construct240 $('#' + id + '_tag_input').before(_tagcode);241 // remove tag, by clicking the close icon242 $('#' + id + '_' + guid + " i").click(function () {243 // remove user tag244 $('#' + id + '_' + guid).remove();245 // reduce the count of added user246 userCount--;247 })248 // hide user results249 $('#' + id + '_userpicker').hide();250 // set focus to the input element251 $('#' + id + '_tag_input_field').focus();252 // Clear the textinput253 $('#' + id + '_tag_input_field').val('');254 }255}256$.fn.userpicker.parseUserInput = function (id) {257 // create and insert a dummy <div> element to work with258 $('#' + id + '_invite_tags').after('<div id="' + id + '_inputResult"></div>')259 // set html form input element to the new <div> element260 $('#' + id + '_inputResult').html($('#' + id + '_invite_tags').html());261 $('#' + id + '_inputResult .userInput').each(function () {262 // get user guid without unique userpicker id263 var pureID = this.id.replace(id + '_', '');264 // add the user guid as plain text265 $(this).after(pureID + ",");266 // remove the link267 $(this).remove();268 })269 // save the plain text270 var result = $('#' + id + '_inputResult').text();271 // remove the dummy <div> element272 $('#' + id + '_inputResult').remove();273 // return the plain text274 return result;...
test_unique.py
Source:test_unique.py
...55 checks, _ = M()._get_unique_checks()56 for t in normalized:57 check = (M, t)58 self.assertIn(check, checks)59 def test_primary_key_is_considered_unique(self):60 m = CustomPKModel()61 self.assertEqual(([(CustomPKModel, ('my_pk_field',))], []), m._get_unique_checks())62 def test_unique_for_date_gets_picked_up(self):63 m = UniqueForDateModel()64 self.assertEqual((65 [(UniqueForDateModel, ('id',))],66 [(UniqueForDateModel, 'date', 'count', 'start_date'),67 (UniqueForDateModel, 'year', 'count', 'end_date'),68 (UniqueForDateModel, 'month', 'order', 'end_date')]69 ), m._get_unique_checks()70 )71 def test_unique_for_date_exclusion(self):72 m = UniqueForDateModel()73 self.assertEqual((...
models.py
Source:models.py
1from sqlalchemy.ext.declarative import declarative_base2from sqlalchemy import Table, MetaData, create_engine, Column, Integer, String, Float, BigInteger, Date3Base = declarative_base()4class BLS_Unemployment(Base):5 __tablename__ = "BLS_Unemployment"6 Geo_ID = Column(String(10), unique=False, primary_key=True)7 Geo_Name = Column(String(150), unique=False)8 Geo_Type = Column(String(50), unique=False)9 Year = Column(Integer, unique=False)10 Month = Column(String(5), unique=False)11 UnemploymentRate = Column(Float, unique=False)12class ESRI_Unemployment_Adjustments(Base):13 __tablename__ = "ESRI_Unemployment_Adjustments"14 Geo_ID = Column(String(10), unique=False, primary_key=True)15 Geo_Name = Column(String(150), unique=False)16 Geo_Type = Column(String(50), unique=False)17 UnemploymentRate_BLS = Column(Float, unique=False)18 UnemploymentRate_ESRI = Column(Float, unique=False)19 Unemployment_Adjustment = Column(Float, unique=False)20class ZIP_MacroData_Update(Base):21 __tablename__ = "ZIP_MacroData_Update"22 ZIP = Column(String(5), unique=False, primary_key=True)23 MSAID = Column(String(5), unique=False)24 COUNTYID = Column(String(5), unique=False)25 STATEID = Column(String(2), unique=False)26 ZIP_PriceChange = Column(Float, unique=False)27 COUNTY_PriceChange = Column(Float, unique=False)28 MSA_PriceChange = Column(Float, unique=False)29 USA_PriceChange = Column(Float, unique=False)30 COUNTY_UnemploymentRate = Column(Float, unique=False)31 MSA_UnemploymentRate = Column(Float, unique=False)32 USA_UnemploymentRate = Column(Float, unique=False)33 MSA_Unemployment_Adjustment = Column(Float, unique=False)34 STATE_Unemployment_Adjustment = Column(Float, unique=False)35 County_Unemployment_Adjustment = Column(Float, unique=False)36class HomeValue_PriceChange(Base):37 __tablename__ = "HomeValue_PriceChange"38 Geo_ID = Column(String(5), unique=False, primary_key=True)39 Geo_Type = Column(String(50), unique=False)40 PriceChange = Column(Float, unique=False)41class Zillow_MSAID_Lookup(Base):42 __tablename__ = "Zillow_MSAID_Lookup"43 Zillow_Id = Column(String(10), unique=False, primary_key=True)44 Zillow_MSA_Name = Column(String(150), unique=False)45 Geo_ID = Column(String(10), unique=False)46 MSA_Name = Column(String(150), unique=False)47class GeoMapping_Zipcode_to_CountyMSAState(Base):48 __tablename__ = "GeoMapping_Zipcode_to_CountyMSAState"49 ZIP = Column(String(5), unique=False, primary_key=True)50 COUNTYID = Column(String(5), unique=False)51 MSAID = Column(String(5), unique=False)52 STATEID = Column(String(2), unique=False)53class GeoMapping_MSA_to_CountyState(Base):54 __tablename__ = "GeoMapping_MSA_to_CountyState"55 ID = Column(String(10), unique=False, primary_key=True)56 MSAID = Column(String(5), unique=False)57 COUNTYID = Column(String(5), unique=False)58 STATEID = Column(String(2), unique=False)59# class HUD_CensusTractsData(Base):60# __tablename__ = "HUD_CensusTractsData"61#62# Geo_ID = Column(String(13), unique=False, primary_key=True)63# Date = Column(Date, unique=False)64# NinetyDaysDefault = Column(Integer, unique=False)65# Foreclosures = Column(Integer, unique=False)66# PctSectionEight = Column(Float, unique=False)67#68# class pct_section_eight_tracts(Base):69# __tablename__ = "pct_section_eight_tracts"70#71# Geo_ID = Column(String(13), unique=False, primary_key=True)72# PctSectionEight = Column(Float, unique=False)73#########################74### Backup Tables75#########################76class BACKUP_BLS_Unemployment(Base):77 __tablename__ = "BACKUP_BLS_Unemployment"78 ID = Column(Integer, unique=False, primary_key=True, autoincrement=True)79 Geo_ID = Column(String(5), unique=False)80 Geo_Name = Column(String(150), unique=False)81 Geo_Type = Column(String(50), unique=False)82 Year = Column(Integer, unique=False)83 Month = Column(String(5), unique=False)84 UnemploymentRate = Column(Float, unique=False)85 Backup_Date = Column(Date, unique=False)86class BACKUP_ESRI_Unemployment_Adjustments(Base):87 __tablename__ = "BACKUP_ESRI_Unemployment_Adjustments"88 ID = Column(Integer, unique=False, primary_key=True, autoincrement=True)89 Geo_ID = Column(String(5), unique=False)90 Geo_Name = Column(String(150), unique=False)91 Geo_Type = Column(String(50), unique=False)92 UnemploymentRate_BLS = Column(Float, unique=False)93 UnemploymentRate_ESRI = Column(Float, unique=False)94 Unemployment_Adjustment = Column(Float, unique=False)95 Backup_Date = Column(Date, unique=False)96class BACKUP_ZIP_MacroData_Update(Base):97 __tablename__ = "BACKUP_ZIP_MacroData_Update"98 ID = Column(Integer, unique=False, primary_key=True, autoincrement=True)99 ZIP = Column(String(5), unique=False)100 MSAID = Column(String(5), unique=False)101 COUNTYID = Column(String(5), unique=False)102 STATEID = Column(String(2), unique=False)103 ZIP_PriceChange = Column(Float, unique=False)104 COUNTY_PriceChange = Column(Float, unique=False)105 MSA_PriceChange = Column(Float, unique=False)106 USA_PriceChange = Column(Float, unique=False)107 COUNTY_UnemploymentRate = Column(Float, unique=False)108 MSA_UnemploymentRate = Column(Float, unique=False)109 USA_UnemploymentRate = Column(Float, unique=False)110 MSA_Unemployment_Adjustment = Column(Float, unique=False)111 STATE_Unemployment_Adjustment = Column(Float, unique=False)112 County_Unemployment_Adjustment = Column(Float, unique=False)113 Backup_Date = Column(Date, unique=False)114class BACKUP_HomeValue_PriceChange(Base):115 __tablename__ = "BACKUP_HomeValue_PriceChange"116 ID = Column(Integer, unique=False, primary_key=True, autoincrement=True)117 Geo_ID = Column(String(5), unique=False)118 Geo_Type = Column(String(50), unique=False)119 PriceChange = Column(Float, unique=False)120 Backup_Date = Column(Date, unique=False)121class TEST_ZIP_IMPORT(Base):122 __tablename__ = "TEST_ZIP_IMPORT"123 Geo_ID = Column(String(5), unique=False, primary_key=True)124 Geo_Type = Column(String(5), unique=False)125 Geo_Name = Column(String(150), unique=False)126 MedianHomeValue = Column(Integer, unique=False)127class InitiateDeclaratives():128 @staticmethod129 def create_tables(engine_string):130 engine = create_engine(engine_string)...
jstree.unique.js
Source:jstree.unique.js
1/**2 * ### Unique plugin3 *4 * Enforces that no nodes with the same name can coexist as siblings.5 */6/*globals jQuery, define, exports, require */7(function (factory) {8 "use strict";9 if (typeof define === 'function' && define.amd) {10 define('jstree.unique', ['jquery','jstree'], factory);11 }12 else if(typeof exports === 'object') {13 factory(require('jquery'), require('jstree'));14 }15 else {16 factory(jQuery, jQuery.jstree);17 }18}(function ($, jstree, undefined) {19 "use strict";20 if($.jstree.plugins.unique) { return; }21 /**22 * stores all defaults for the unique plugin23 * @name $.jstree.defaults.unique24 * @plugin unique25 */26 $.jstree.defaults.unique = {27 /**28 * Indicates if the comparison should be case sensitive. Default is `false`.29 * @name $.jstree.defaults.unique.case_sensitive30 * @plugin unique31 */32 case_sensitive : false,33 /**34 * Indicates if white space should be trimmed before the comparison. Default is `false`.35 * @name $.jstree.defaults.unique.trim_whitespace36 * @plugin unique37 */38 trim_whitespace : false,39 /**40 * A callback executed in the instance's scope when a new node is created and the name is already taken, the two arguments are the conflicting name and the counter. The default will produce results like `New node (2)`.41 * @name $.jstree.defaults.unique.duplicate42 * @plugin unique43 */44 duplicate : function (name, counter) {45 return name + ' (' + counter + ')';46 }47 };48 $.jstree.plugins.unique = function (options, parent) {49 this.check = function (chk, obj, par, pos, more) {50 if(parent.check.call(this, chk, obj, par, pos, more) === false) { return false; }51 obj = obj && obj.id ? obj : this.get_node(obj);52 par = par && par.id ? par : this.get_node(par);53 if(!par || !par.children) { return true; }54 var n = chk === "rename_node" ? pos : obj.text,55 c = [],56 s = this.settings.unique.case_sensitive,57 w = this.settings.unique.trim_whitespace,58 m = this._model.data, i, j, t;59 for(i = 0, j = par.children.length; i < j; i++) {60 t = m[par.children[i]].text;61 if (!s) {62 t = t.toLowerCase();63 }64 if (w) {65 t = t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');66 }67 c.push(t);68 }69 if(!s) { n = n.toLowerCase(); }70 if (w) { n = n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }71 switch(chk) {72 case "delete_node":73 return true;74 case "rename_node":75 t = obj.text || '';76 if (!s) {77 t = t.toLowerCase();78 }79 if (w) {80 t = t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');81 }82 i = ($.inArray(n, c) === -1 || (obj.text && t === n));83 if(!i) {84 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_01', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };85 }86 return i;87 case "create_node":88 i = ($.inArray(n, c) === -1);89 if(!i) {90 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_04', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };91 }92 return i;93 case "copy_node":94 i = ($.inArray(n, c) === -1);95 if(!i) {96 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_02', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };97 }98 return i;99 case "move_node":100 i = ( (obj.parent === par.id && (!more || !more.is_multi)) || $.inArray(n, c) === -1);101 if(!i) {102 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_03', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };103 }104 return i;105 }106 return true;107 };108 this.create_node = function (par, node, pos, callback, is_loaded) {109 if(!node || node.text === undefined) {110 if(par === null) {111 par = $.jstree.root;112 }113 par = this.get_node(par);114 if(!par) {115 return parent.create_node.call(this, par, node, pos, callback, is_loaded);116 }117 pos = pos === undefined ? "last" : pos;118 if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {119 return parent.create_node.call(this, par, node, pos, callback, is_loaded);120 }121 if(!node) { node = {}; }122 var tmp, n, dpc, i, j, m = this._model.data, s = this.settings.unique.case_sensitive, w = this.settings.unique.trim_whitespace, cb = this.settings.unique.duplicate, t;123 n = tmp = this.get_string('New node');124 dpc = [];125 for(i = 0, j = par.children.length; i < j; i++) {126 t = m[par.children[i]].text;127 if (!s) {128 t = t.toLowerCase();129 }130 if (w) {131 t = t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');132 }133 dpc.push(t);134 }135 i = 1;136 t = n;137 if (!s) {138 t = t.toLowerCase();139 }140 if (w) {141 t = t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');142 }143 while($.inArray(t, dpc) !== -1) {144 n = cb.call(this, tmp, (++i)).toString();145 t = n;146 if (!s) {147 t = t.toLowerCase();148 }149 if (w) {150 t = t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');151 }152 }153 node.text = n;154 }155 return parent.create_node.call(this, par, node, pos, callback, is_loaded);156 };157 };158 // include the unique plugin by default159 // $.jstree.defaults.plugins.push("unique");...
game-question-list-item.components.jsx
Source:game-question-list-item.components.jsx
1import React, { useState, useEffect } from 'react';2import { useTranslation } from 'react-i18next';3import { useSelector, useDispatch } from 'react-redux';4import { addRoundPoints, setQuestionAnswer } from '../../redux/round/round.actions';5import './game-question-list-item.styles.scss';6export default function GameQuestionListItem({ question }) {7 const { t } = useTranslation();8 const { categoryUniqueName, userAnswer, pointsForAnswer, confirmed } = question;9 const currQuestion = useSelector((state) => state.round.questions.find((element) => element.categoryUniqueName === categoryUniqueName));10 const { status } = useSelector((state) => state.round);11 const currCategory = useSelector((state) => state.category.categories.find((category) => category.uniqueName === categoryUniqueName));12 const dispatch = useDispatch();13 const [questionData, setQuestionData] = useState({14 [`answer-${categoryUniqueName}`]: userAnswer,15 [`point-${categoryUniqueName}`]: pointsForAnswer,16 confirmed,17 });18 const handleChange = (event) => {19 if (!confirmed) {20 setQuestionData({21 ...questionData,22 [event.target.name]: event.target.value,23 });24 }25 };26 const handleClickConfirm = () => {27 if ((questionData[`point-${categoryUniqueName}`] !== '') && !questionData.confirmed) {28 const confirmedQuestion = {29 categoryUniqueName,30 userAnswer: questionData[`answer-${categoryUniqueName}`],31 pointsForAnswer: questionData[`point-${categoryUniqueName}`],32 confirmed: true,33 };34 setQuestionData({35 ...questionData,36 confirmed: true,37 });38 dispatch(setQuestionAnswer(confirmedQuestion));39 dispatch(addRoundPoints(Number(questionData[`point-${categoryUniqueName}`])));40 }41 };42 useEffect(() => {43 setQuestionData({44 [`answer-${categoryUniqueName}`]: currQuestion.userAnswer,45 [`point-${categoryUniqueName}`]: currQuestion.pointsForAnswer,46 confirmed: currQuestion.confirmed,47 });48 }, [question]);49 return (50 <div className="gameCategoryListItem">51 <div className="gameCategoryListItem__content">52 <button53 className={`gameCategoryListItem__content-confirmButton ${confirmed ? 'confirmed' : ''} ${status.name === 'progress' ? 'inactive' : ''}`}54 onClick={handleClickConfirm}55 >56 <i className={currCategory.displayIcon}></i>57 </button>58 <div className="gameCategoryListItem__content-text">59 <p className="gameCategoryListItem__content-text-categoryName">{t(`category_${currCategory.uniqueName}`)}</p>60 <input61 className="gameCategoryListItem__content-text-input"62 type="text"63 name={`answer-${categoryUniqueName}`}64 placeholder={t('question_input_text_placeholder')}65 value={questionData[`answer-${categoryUniqueName}`]}66 onChange={handleChange}67 disabled={status.name !== 'progress'}68 autoComplete="off"69 />70 </div>71 </div>72 {status.name !== 'progress' && (73 <div className="gameCategoryListItem__checker">74 <label className={`gameCategoryListItem__checker-label ${questionData[`point-${categoryUniqueName}`] === '10' ? 'checked' : ''} ${(questionData[`point-${categoryUniqueName}`] !== '10' && confirmed) ? 'inactive' : ''}`}>75 <input76 className="gameCategoryListItem__checker-label-input"77 type="radio"78 name={`point-${categoryUniqueName}`}79 value={10}80 onChange={handleChange}81 />82 <p className="gameCategoryListItem__checker-label-value">10</p>83 </label>84 <label85 className={`gameCategoryListItem__checker-label ${questionData[`point-${categoryUniqueName}`] === '5' ? 'checked' : ''} ${(questionData[`point-${categoryUniqueName}`] !== '5' && confirmed) ? 'inactive' : ''}`}86 >87 <input88 className="gameCategoryListItem__checker-label-input"89 type="radio"90 name={`point-${categoryUniqueName}`}91 value={5}92 onChange={handleChange}93 />94 <p className="gameCategoryListItem__checker-label-value">5</p>95 </label>96 <label className={`gameCategoryListItem__checker-label ${questionData[`point-${categoryUniqueName}`] === '0' ? 'checked' : ''} ${(questionData[`point-${categoryUniqueName}`] !== '0' && confirmed) ? 'inactive' : ''}`}>97 <input98 className="gameCategoryListItem__checker-label-input"99 type="radio"100 name={`point-${categoryUniqueName}`}101 value={0}102 onChange={handleChange}103 />104 <p className="gameCategoryListItem__checker-label-value">0</p>105 </label>106 </div>107 )}108 </div>109 );...
std_unique_ptr_test.py
Source:std_unique_ptr_test.py
1#!/usr/bin/env python2# Copyright (C) 2022 The Qt Company Ltd.3# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.04import gc5import os6import sys7import unittest8from pathlib import Path9sys.path.append(os.fspath(Path(__file__).resolve().parents[1]))10from shiboken_paths import init_paths11init_paths()12from smart import Integer, Integer2, StdUniquePtrTestBench, StdUniquePtrVirtualMethodTester, std13def call_func_on_ptr(ptr):14 ptr.printInteger()15class VirtualTester(StdUniquePtrVirtualMethodTester):16 def doCreateInteger(self, v):17 iv = Integer() # Construct from pointee18 iv.setValue(2 * v)19 return std.unique_ptr_Integer(iv)20 def doModifyIntegerByRef(self, p):21 return 2 * p.value()22 def doModifyIntegerByValue(self, p):23 return 2 * p.value()24class StdUniquePtrTests(unittest.TestCase):25 def testInteger(self):26 p = StdUniquePtrTestBench.createInteger()27 StdUniquePtrTestBench.printInteger(p) # unique_ptr by ref28 self.assertTrue(p)29 call_func_on_ptr(p)30 self.assertTrue(p)31 StdUniquePtrTestBench.takeInteger(p) # unique_ptr by value, takes pointee32 self.assertFalse(p)33 np = StdUniquePtrTestBench.createNullInteger()34 StdUniquePtrTestBench.printInteger(np)35 self.assertFalse(np)36 self.assertRaises(AttributeError, call_func_on_ptr, np)37 iv = Integer() # Construct from pointee38 iv.setValue(42)39 np = std.unique_ptr_Integer(iv)40 self.assertEqual(np.value(), 42)41 def test_derived(self):42 iv2 = Integer2() # Construct from pointee43 iv2.setValue(42)44 p = std.unique_ptr_Smart_Integer2(iv2)45 self.assertEqual(p.value(), 42)46 StdUniquePtrTestBench.printInteger2(p) # unique_ptr by ref47 self.assertTrue(p)48 StdUniquePtrTestBench.printInteger(p) # conversion49 # FIXME: This fails, pointer is moved in value conversion50 # self.assertTrue(p)51 def testInt(self):52 p = StdUniquePtrTestBench.createInt() # unique_ptr by ref53 StdUniquePtrTestBench.printInt(p)54 StdUniquePtrTestBench.takeInt(p) # unique_ptr by value, takes pointee55 self.assertFalse(p)56 np = StdUniquePtrTestBench.createNullInt()57 StdUniquePtrTestBench.printInt(np)58 self.assertFalse(np)59 def testVirtuals(self):60 """Test whether code generating virtual function overrides is generated61 correctly."""62 p = StdUniquePtrTestBench.createInteger()63 p.setValue(42)64 v = StdUniquePtrVirtualMethodTester()65 self.assertTrue(v.testCreateInteger(42, 42))66 self.assertTrue(v.testModifyIntegerByRef(42, 43)) # Default implementation increments67 self.assertTrue(v.testModifyIntegerValue(42, 43))68 v = VirtualTester() # Reimplemented methods double values69 self.assertTrue(v.testCreateInteger(42, 84))70 self.assertTrue(v.testModifyIntegerByRef(42, 84))71 self.assertTrue(v.testModifyIntegerValue(42, 84))72if __name__ == '__main__':...
Using AI Code Generation
1var wptools = require('wptools');2var unique = require('array-unique');3var array = ['a', 'b', 'a', 'c', 'a', 'b'];4console.log(unique(array));5var _ = require('underscore');6var array = ['a', 'b', 'a', 'c', 'a', 'b'];7console.log(_.uniq(array));8var _ = require('lodash');9var array = ['a', 'b', 'a', 'c', 'a', 'b'];10console.log(_.uniq(array));11var unique = require('array-unique');12var array = ['a', 'b', 'a', 'c', 'a', 'b'];13console.log(unique(array));14var uniq = require('uniq');15var array = ['a', 'b', 'a', 'c', 'a', 'b'];16console.log(uniq(array));17var uniq = require('uniq');18var array = ['a', 'b', 'a', 'c', 'a', 'b'];19console.log(uniq(array));20var unique = require('unique');21var array = ['a', 'b', 'a', 'c', 'a', 'b'];22console.log(unique(array));23var unique = require('unique-array');24var array = ['a', 'b', 'a', 'c', 'a', 'b'];25console.log(unique(array));26var unique = require('unique-array');27var array = ['a', 'b', 'a', 'c', 'a', 'b'];28console.log(unique(array));
Using AI Code Generation
1const wptools = require('wptools') 2const fs = require('fs')3const page = wptools.page('Barack_Obama', { format: 'json' })4page.get((err, info) => {5 if (err) {6 console.log(err)7 } else {8 console.log(info)9 }10})11const wptools = require('wptools') 12const fs = require('fs')13const page = wptools.page('Barack_Obama', { format: 'json' })14page.get((err, info) => {15 if (err) {16 console.log(err)17 } else {18 console.log(info)19 }20})21const wptools = require('wptools') 22const fs = require('fs')23const page = wptools.page('Barack_Obama', { format: 'json' })24page.get((err, info) => {25 if (err) {26 console.log(err)27 } else {28 console.log(info)29 }30})31const wptools = require('wptools') 32const fs = require('fs')33const page = wptools.page('Barack_Obama', { format: 'json' })34page.get((err, info) => {35 if (err) {36 console.log(err)37 } else {38 console.log(info)39 }40})41const wptools = require('wptools') 42const fs = require('fs')43const page = wptools.page('Barack_Obama', { format: 'json' })44page.get((err, info) => {45 if (err) {46 console.log(err)47 } else {48 console.log(info)49 }50})
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.0e2c7f9d9f9b7e1f1a6c7d6b5d6b7a6');3var options = {4};5 if (err) return console.error(err);6 console.log('Test status:', data.statusText);7 wpt.getTestResults(data.data.testId, function(err, data) {8 if (err) return console.error(err);9 console.log('First View:', data.data.average.firstView);10 console.log('Repeat View:', data.data.average.repeatView);11 console.log('Speed Index:', data.data.average.firstView.SpeedIndex);12 });13});
Using AI Code Generation
1var wpt = require('webpagetest');2var webPageTest = new wpt('www.webpagetest.org', 'A.0e6a9f6e4ad6c0e4b4f6c4d8f8c6b0e1');3var options = {4 videoParams: {5 }6};7webPageTest.runTest(url, options, function (err, data) {8 if (err) {9 console.log('Error: ' + err);10 } else {11 console.log('Test Finished');12 console.log('Test ID: ' + data.data.testId);13 console.log('Test URL: ' + data.data.summary);14 console.log('Test Results: ' + data.data.userUrl);15 console.log('Test Video: ' + data.data.videoUrl);16 console.log('Test Thumbnails: ' + data.data.thumbnailUrl);17 console.log('Test Screenshots: ' + data.data.jsonUrl);18 }19});20var wpt = require('webpagetest');21var webPageTest = new wpt('www.webpagetest.org', 'A.0e6a9f6e4ad6c0e4b4f6c4d8f8c6b0e1');22var options = {23 videoParams: {
Using AI Code Generation
1var wpt = require('webpagetest');2var test = new wpt('www.webpagetest.org', 'A.0e8c3f3b3d3c9b0a4b8d4c4f0d4c0d4');3test.runTest(url, {location: 'Dulles:Chrome'}, function(err, data) {4 if (err) return console.error(err);5 console.log(data);6 test.getTestStatus(data.data.testId, function(err, data) {7 if (err) return console.error(err);8 console.log(data);9 });10});11var wpt = require('webpagetest');12var test = new wpt('www.webpagetest.org', 'A.0e8c3f3b3d3c9b0a4b8d4c4f0d4c0d4');13test.runTest(url, {location: 'Dulles:Chrome'}, function(err, data) {14 if (err) return console.error(err);15 console.log(data);16 test.getTestStatus(data.data.testId, function(err, data) {17 if (err) return console.error(err);18 console.log(data);19 });20});21var wpt = require('webpagetest');22var test = new wpt('www.webpagetest.org', 'A.0e8c3f3b3d3c9b0a4b8d4c4f0d4c0d4');23test.runTest(url, {location: 'Dulles:Chrome'}, function(err, data) {24 if (err) return console.error(err);25 console.log(data);26 test.getTestStatus(data.data.testId, function(err, data) {27 if (err) return console.error(err);28 console.log(data);29 });30});31var wpt = require('webpagetest');32var test = new wpt('www.webpagetest.org', 'A.0e8c3f3
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!