No case for some selector values как исправить

Счет числительными (ошибка)

Аватара пользователя

Alexwall

interested
interested
Сообщения: 4
Зарегистрирован: 27 дек 2013, 15:24
Версия LabVIEW: 2012
Контактная информация:


Счет числительными (ошибка)

Суть задания такова:

Напишите программу, которая записывает введенное двухзначное число
строкой соответствующих числительных.

Изображение
Указание: обратите внимание, что числительные от 21 до 99
получаются написанием перед числительным для чисел от 1 до 9 слова,
обозначающего десятки – двадцать, тридцать, …, девяносто.
Исключение составляет 0 и числа от 10 до 19.
Поэтому имеет смысл анализировать цифры двузначного числа по
отдельности.
Выбор числительных организуйте при помощи структуры Case Structure.
Если к терминалу условия подключить данные типа целое число, то
станет возможно создавать случаи, соответствующие различным
значениям этого числа, или даже диапазонам значений. Новые случаи
создаются из контекстного меню структуры Add Case After или Add Case
Before.
Проверку состояния элементов управления организуйте, используя цикл
While Loop с задержкой 100 мс.

Как понял так сделал…как сделать чтобы ошибку не выдавало? И правильно ли это?

Вложения
1.vi
Как понял так сделал…
(9.05 КБ) 152 скачивания

Аватара пользователя

dadreamer

professor
professor
Сообщения: 3871
Зарегистрирован: 17 фев 2013, 16:33
Награды: 4
Версия LabVIEW: 2.5 — 2022
Благодарил (а): 10 раз
Поблагодарили: 97 раз
Контактная информация:

Re: Счет числительными (ошибка)

Сообщение

dadreamer » 27 дек 2013, 16:19

Alexwall писал(а):как сделать чтобы ошибку не выдавало?

No case for some selector values
A Case structure must have a case corresponding to every possible value of the selector. An easy way to fill this requirement is to specify a default case or cases whose selector values include ranges to or from infinity.

Если подали число на Case, то нужно определить все варианты (случаи) для этого числа, либо определить критичные для вас случаи, а для остальных сделать один вариант и назначить его Default (по умолчанию).

Аватара пользователя

IvanLis

guru
guru
Сообщения: 5405
Зарегистрирован: 02 дек 2009, 17:44
Награды: 7
Версия LabVIEW: 2015, 2016
Откуда: СССР
Благодарил (а): 25 раз
Поблагодарили: 75 раз

Re: Счет числительными (ошибка)

Сообщение

IvanLis » 27 дек 2013, 16:21

Alexwall писал(а):Как понял так сделал…как сделать чтобы ошибку не выдавало? И правильно ли это?

Во первых, необходимо указать “значение по умолчанию” в Case структуре.
Во вторых, как может получится при целочисленном делении на 10, остаток 12 и т.д. (больше 10)?

Аватара пользователя

Alexwall

interested
interested
Сообщения: 4
Зарегистрирован: 27 дек 2013, 15:24
Версия LabVIEW: 2012
Контактная информация:

Re: Счет числительными (ошибка)

Сообщение

Alexwall » 27 дек 2013, 18:18

IvanLis писал(а):

Alexwall писал(а):Как понял так сделал…как сделать чтобы ошибку не выдавало? И правильно ли это?

Во первых, необходимо указать “значение по умолчанию” в Case структуре.
Во вторых, как может получится при целочисленном делении на 10, остаток 12 и т.д. (больше 10)?

А как сделать “значение по умолчанию?”. Я просто только не давно начал изучать LabView не все знаю.

Вот я тоже долго думал, никак не могу сделать.

Аватара пользователя

dadreamer

professor
professor
Сообщения: 3871
Зарегистрирован: 17 фев 2013, 16:33
Награды: 4
Версия LabVIEW: 2.5 — 2022
Благодарил (а): 10 раз
Поблагодарили: 97 раз
Контактная информация:

Аватара пользователя

Alexwall

interested
interested
Сообщения: 4
Зарегистрирован: 27 дек 2013, 15:24
Версия LabVIEW: 2012
Контактная информация:

Re: Счет числительными (ошибка)

Сообщение

Alexwall » 27 дек 2013, 19:23

dadreamer писал(а):ПКМ на Case:

Спасибо.

Я вот никак додумать не могу, с помощью какой функции выделить значения от 10 до 19

Аватара пользователя

Alexwall

interested
interested
Сообщения: 4
Зарегистрирован: 27 дек 2013, 15:24
Версия LabVIEW: 2012
Контактная информация:

Re: Счет числительными (ошибка)

Сообщение

Alexwall » 27 дек 2013, 22:53

IvanLis писал(а):

Alexwall писал(а):Я вот никак додумать не могу, с помощью какой функции выделить значения от 10 до 19

Прежде чем “городить огород” посмотрели бы как это уже реализовано в других языках и отталкивались от этого.
Например здесь: http://www.num2word.ru/?
Исходники: [url]view-source:http://www.num2word.ru/?[/url]

Все равно ничего не понимаю…с 0 до 9 и с 20 по 99 выводит…а с 10 до 19 вообще никак. Не понимаю.

  • 3 Ответы
    718 Просмотры
    Последнее сообщение Artem.spb

    17 сен 2022, 18:38

  • 1 Ответы
    623 Просмотры
    Последнее сообщение alerm

    16 ноя 2022, 23:42

  • 3 Ответы
    259 Просмотры
    Последнее сообщение rsv

    30 мар 2023, 14:51

  • “Could not open file for some reason any.” Error message since then reinstall it.

    I have recently restored OS X from a backup, the same (current) version of the numbers and I use the same files (one document, different versions tried), but since I only get the error message “… cannot be opened for some reason any.”

    I found absolutely no fix or solution floating around the web this fix in my case. I tried 3 machines, different, another user account fresh installation, conversion/dissemination/export the file, number in iOS and iCloud – nothing.

    This document contains the data value of several MONTHS of work and is encrypted password. It’s just an unacceptable loss.

    Does anyone know another way to recover the data?

    If not, please give it a try, here’s the document mentioned:

    https://www.dropbox.com/s/9dezibbcjvtw9sj/document.numbers.zip?DL=0

    So says “… cannot be opened for some reason any ‘, I’m having a very bad time…

    But If you are asked to enter the password – thank God – contact me

    There is nothing on the face of the planet to open a document from v3.6.1 numbers once you get ‘Document.numbers’ cannot be opened for a dialogue of reason. Be it password protected, or not makes no difference. Your only hope is to get a copy of older backup and restore. The same thing happens in the current versions of Pages v5.6.n also.

    Any other spreadsheet application would have not done this for you.

  • In any case for the value Compenent of the list is NOT anti-aliased text?

    As you may know, pixel fonts are tiny size, specially created for NOT being anti-aliasing. Use you the size of 8, with anti-aliasing pixels, the value “bitmap (no anti-alias) ‘.

    But I can’t find how to specify this parameter for a list item type. I can incorporate the police and get to use the police, but he alias against it. Any ideas? Thank you

    Nevermind, it seems that the clip that the List component was inside was not aligned to pixels the same.

  • Update statement conditioned to two columns, but for some values only

    Hi This is my my sample data:

    with Table_1        
    as
    (
          select '20:00' incident_time, 'WEDNESDAY' Day, 'N' Weekend,  '' Weekend_Alt   from dual
          union all
          select '18:00' incident_time, 'SATURDAY' Day, 'Y' Weekend,  '' Weekend_Alt from dual
          union all
          select '19:00' incident_time, 'FRIDAY' Day, 'N' Weekend, '' Weekend_Alt from dual
          union all
          select '11:00' incident_time, 'FRIDAY' Day, 'N' Weekend, '' Weekend_Alt from dual
    )
    select *
      from Table_1

    I want to perform an update as shown below

    Update Table_1 tt
      
     SET Weekend_Alt = (CASE WHEN TO_CHAR(tt.day,'fmDAY') IN ('FRIDAY AND TIME >= 19:00','SATURDAY','SUNDAY') THEN 'Y' ELSE 'N' END)
    
    I realize the syntax is wrong but just want to give you an idea of what I want to achieve.

    Final result should look like this:

    with Table_1        
    as
    (
          select '20:00' incident_time, 'WEDNESDAY' Day, 'N' Weekend,  'N' Weekend_Alt   from dual
          union all
          select '18:00' incident_time, 'SATURDAY' Day, 'Y' Weekend,  'Y' Weekend_Alt from dual
          union all
          select '19:00' incident_time, 'FRIDAY' Day, 'N' Weekend, 'Y' Weekend_Alt from dual
          union all
          select '11:00' incident_time, 'FRIDAY' Day, 'N' Weekend, 'N' Weekend_Alt from dual
    )
    select *
      from Table_1

    Thanks in advance!

    Banner:
    Oracle Database 11 g Release 11.2.0.2.0 – 64 bit Production
    PL/SQL Release 11.2.0.2.0 – Production
    “CORE 11.2.0.2.0 Production.”
    AMT for Linux: Version 11.2.0.2.0 – Production
    NLSRTL Version 11.2.0.2.0 – Production

    with Table_1
    as
    (
          select to_date('01-JUL-2009 20:10','DD-MON-YYYY HH24:MI') incident_date    from dual
          union all
          select to_date('23-MAR-2010 12:12','DD-MON-YYYY HH24:MI') incident_date from dual
          union all
          select to_date('25-JUL-2010 23:30','DD-MON-YYYY HH24:MI') incident_datet from dual
          union all
          select to_date('09-JAN-2010 08:30','DD-MON-YYYY HH24:MI') incident_date from dual
          union all
          select to_date('08-JAN-2010 08:30','DD-MON-YYYY HH24:MI') incident_date from dual
          union all
          select to_date('08-JAN-2010 20:30','DD-MON-YYYY HH24:MI') incident_date from dual
          union all
          select to_date('26-JUL-2010 00:00','DD-MON-YYYY HH24:MI') incident_datet from dual
    )
    select incident_date, to_char(incident_date,'Day'),
        case
            when incident_date between trunc(incident_date,'IW') + 4 + 19/24
                                   and trunc(incident_date,'IW') + 7
            then 'Y' else 'N'
        end
    from Table_1 t;
    

    So your update

    update table_1 tt
    set weekend_alt =
        case
            when incident_date between trunc(incident_date,'IW') + 4 + 19/24
                                   and trunc(incident_date,'IW') + 7
            then 'Y' else 'N'
        end;
    

    But it begs the question if it’s a good idea to store these derived data

    Published by: 3360 November 8, 2011 10:14

  • Need help for some objects Flash weird error… Please!

    I have a bit of a problem to my page in Dreamweaver CS4, I don’t know why I can’t see my flash animations in internet explorer, but in another browser I can do! My page is www.jmelectric.com.mx and the error I have her:

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618)
    Timestamp: Tuesday, December 29, 2009 22:12:48 UTC

    Message: Object doesn’t support this property or method
    Online: 452
    Char: 19
    Code: 0
    URI: http://www.jmelectric.com.mx/Scripts/swfobject_modified.js

    and the code of this JS code is…

    /*! SWFObject v2.0 <http://code.google.com/p/swfobject/>
    Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
    This software is distributed under the license MIT <http://www.opensource.org/licenses/mit-license.php>
    */

    SWFObject var = function() {}

    var UNDEF = “undefined.”
    OBJECT =”object”, “.
    SHOCKWAVE_FLASH = “Shockwave Flash”,
    SHOCKWAVE_FLASH_AX = “ShockwaveFlash.ShockwaveFlash.”
    FLASH_MIME_TYPE = application/x-shockwave-flash”.”
    EXPRESS_INSTALL_ID = “SWFObjectExprInst”

    Win: a window,
    doc = document,
    NAV = navigator,

    domLoadFnArr = [],
    regObjArr = [],
    Timer = null,
    storedAltContent = null,
    storedAltContentId = null,
    isDomLoaded = false,
    isExpressInstallActive = false;

    / * Centralized function for browser detection
    -Owners (conditional compilation) detection is used to detect features of Internet Explorer
    -Detection of string user agent is used only when no alternative is possible
    -Is executed directly for optimal performance
    */
    var ua = function() {}
    var w3cdom = typeof doc.getElementById! = UNDEF & & typeof doc.getElementsByTagName! = UNDEF & & typeof doc.createElement! = UNDEF & & typeof doc.appendChild! = UNDEF & & typeof doc.replaceChild! = UNDEF & & typeof doc.removeChild! = UNDEF & & typeof doc.cloneNode! = UNDEF,
    playerVersion = [0,0,0],
    d = null;
    If (typeof nav.plugins! = UNDEF & & typeof nav.plugins [SHOCKWAVE_FLASH] == OBJECT) {}
    d = nav.plugins [SHOCKWAVE_FLASH] .description;
    If (d) {}
    (d = d.replace(/^.*s+(S+s+S+$) /, ‘$1’);
    playerVersion [0] = parseInt (d (/ ^(.*)——… * $/, “$1”), 10);
    playerVersion [1] = parseInt (d (/ ^. * .)) (. *)s.*$/, “$1”), 10);
    playerVersion [2] = /r/.test(d)? parseInt(d.replace(/^.*r(.*)$ /, ‘$1’), 10): 0;
    }
    }
    else if (typeof win. ActiveXObject! = UNDEF) {}
    var a = null, fp6Crash = false;
    try {}
    a = new ActiveXObject (SHOCKWAVE_FLASH_AX + “.”) 7″) ;
    }
    {catch (e)}
    try {}
    a = new ActiveXObject (SHOCKWAVE_FLASH_AX + “.”) 6 ») ;
    playerVersion = [6,0,21];
    a.AllowScriptAccess = “always”;  Introduced in fp6.0.47
    }
    {catch (e)}
    If (playerVersion [0] == 6) {}
    fp6Crash = true;
    }
    }
    If (! fp6Crash) {}
    try {}
    a = new ActiveXObject (SHOCKWAVE_FLASH_AX);
    }
    {catch (e)}
    }
    }
    If (! fp6Crash & & a) {/ / a will return NULL when ActiveX is disabled}
    try {}
    d = a.GetVariable (“$version”);  Crash fp6.0.21/23/29
    If (d) {}
    d = d.split(“”) [1].split(“,”);
    playerVersion = [parseInt (d [0], 10), parseInt (d [1], 10), parseInt (d [2], 10)];
    }
    }
    {catch (e)}
    }
    }
    var u = nav.userAgent.toLowerCase (),
    p = nav.platform.toLowerCase (),
    WebKit = /webkit/.test(u)? ((parseFloat(u.replace(/^.*webkit/(d+(.d+)?). * $/, ‘$1’)): false, / / returns the version of webkit or false otherwise webkit
    IE = false,
    Windows = p? (/Win/.test(p): /win/.test(u).
    Mac = p? (/Mac/.test(p): /mac/.test(u);
    /*@cc_on
    IE = true;
    @if (@_win32)
    Windows = true;
    @elif (@_mac)
    Mac = true;
    @end
    @*/
    return {w3cdom:w3cdom, pv:playerVersion, webkit:webkit, IE: IE, win: windows, mac: mac};
    }();

    / * OnDomLoad Cross-browser
    -Based on the solution of Dean Edwards: http://dean.edwards.name/weblog/2006/06/again/
    -Triggers an event as soon as the DOM of a page is loaded (supported by browsers based on Gecko based – like Firefox – IE, Opera9 +, Safari)
    */
    var onDomLoad = function() {}
    If (! ua.w3cdom) {}
    return;
    }
    addDomLoadEvent (hand);
    If (ua.ie & & ua.win) {}
    try {/ / avoid a possible abandoned operation error}
    doc. Write (“< scr” + “ipt id = __ie_ondomload reporter = true src = / /: > < / scr” + “ipt >”); String is split into pieces to prevent Norton AV to add code that can lead to errors
    var s = getElementById (“__ie_ondomload”);
    If (s) {}
    s.onreadystatechange = function() {}
    If (this.readyState == ‘complete’) {}
    this.parentNode.removeChild (this);
    callDomLoadFunctions();
    }
    };
    }
    }
    {catch (e)}
    }
    If (ua.webkit & & typeof doc.readyState! = UNDEF) {}
    Timer = setInterval (function () {if (/ loaded|complete/.test(doc.readyState)}) {callDomLoadFunctions() ;}}, 10);
    }
    If (typeof doc.addEventListener! = UNDEF) {}
    doc.addEventListener (“DOMContentLoaded”, callDomLoadFunctions, null);
    }
    addLoadEvent (callDomLoadFunctions);
    }();

    function callDomLoadFunctions() {}
    If {(isDomLoaded)
    return;
    }
    If (ua.ie & & ua.win) {/ / check if we can really add to the DOM model; we do not want the fire too soon}
    var s = createElement (‘span’);
    try {/ / avoid a possible abandoned operation error}
    var t = doc.getElementsByTagName (“body”) [0] .appendChild (s);
    t.parentNode.removeChild (t);
    }
    {} catch (e)
    return;
    }
    }
    isDomLoaded = true;
    If {(timer)
    clearInterval (timer);
    Timer = null;
    }
    DL var = domLoadFnArr.length;
    for (var i = 0; i < dl; i ++) {}
    domLoadFnArr [i] ();
    }
    }

    function addDomLoadEvent (fn) {}
    If {(isDomLoaded)
    FN();
    }
    else {}
    domLoadFnArr [domLoadFnArr.length] = fn; Array.push () is only available in Internet Explorer 5.5 +.
    }
    }

    / * Cross-browser onload
    -Based on the solution of James Edwards: http://brothercake.com/site/resources/scripts/onload/
    -Triggers an event as soon as a web page, including all of its assets are loaded
    */
    function addLoadEvent (fn) {}
    If (typeof win.addEventListener! = UNDEF) {}
    win.addEventListener (“load”, fn, false);
    }
    else if (typeof doc.addEventListener! = UNDEF) {}
    doc.addEventListener (“load”, fn, false);
    }
    else if (typeof win.attachEvent! = UNDEF) {}
    win.attachEvent (“onload”, fn);
    }
    else if (typeof win.onload == ‘function’) {}
    var fnOld = win.onload;
    Win.OnLoad = function() {}
    fnOld();
    FN();
    };
    }
    else {}
    Win.OnLoad = fn;
    }
    }

    / * Main function
    -Will preferably run onDomLoad, onload otherwise (as a backup)
    */
    int main() {/ / static publishing only}
    RL var = regObjArr.length;
    for (var i = 0; i < rl; i ++) {/ / for each element of the registered object}
    var id = user.user regObjArr [i];
    If (ua.pv [0] > 0) {}
    var obj = getElementById (id);
    If (obj) {}
    regObjArr [i] .width = obj.getAttribute (“width”)? obj.getAttribute (“width”): “0”;
    regObjArr [i] = obj.getAttribute (“height”) .height? obj.getAttribute (“height”): “0”;
    If (hasPlayerVersion (regObjArr [i], .swfVersion)) {/ / Flash plugin version > = version of Flash content: Houston, we have a match!}
    If (ua.webkit & & ua.webkit < 312) {/ / older webkit engines ignore elements nested in the element of the object param}
    fixParams (obj);
    }
    setVisibility (id, true);
    }
    ElseIf (regObjArr [i] .expressInstall & &! isExpressInstallActive & & hasPlayerVersion (“6.0.65”) & & (ua.win | ua.mac)) {/ / display the Adobe quick installation dialog box if defined by the author of the page web and if supported (fp6.0.65 + on Win/Mac OS only)}
    showExpressInstall (regObjArr [i]);
    }
    else {/ / invalid plugin Flash and Flash version content: display the alternative content instead of Flash content}
    displayAltContent (obj);
    }
    }
    }
    else {/ / if no fp is installed, we let the object element do its work (show alternative content)}
    setVisibility (id, true);
    }
    }
    }

    / * Difficulty nested, param elements that are ignored by older webkit engines
    -This includes Safari until and including version 1.2.2 on Mac OS 10.3
    -Fall back to the property include element
    */
    function fixParams (obj) {}
    var nestedObj = obj.getElementsByTagName (OBJECT) [0];
    If {(nestedObj)
    e var is createElement (“embed”), a = nestedObj.attributes;.
    If (a) {}
    var al is. Length;
    for (var i = 0; i < al; i ++) {}
    If (a [i].nodeName.toLowerCase () == ‘data’) {}
    e.setAttribute (“src”, a [i] .nodeValue);
    }
    else {}
    e.setAttribute (a [i] .nodeName, a [i] .nodeValue);
    }
    }
    }
    var c = nestedObj.childNodes;
    If {(c)
    CL var = c.length;
    for (var j = 0; j < cl; j ++) {}
    If (c [j] .nodeType == 1 & & c [j].nodeName.toLowerCase () == ‘param’) {}
    e.setAttribute (c [j] .getAttribute (“name”), c [j] .getAttribute (“value”));
    }
    }
    }
    obj.parentNode.replaceChild (e, obj);
    }
    }

    / * Difficulty suspended discussions audio/video and force open sockets and NetConnections disconnect
    -Occurs when unloading a web page in Internet Explorer using FP8 + and innerHTML/outerHTML
    -Dynamics of publication only
    */
    function fixObjectLeaks (id) {}
    If (ua.ie & & ua.win & & hasPlayerVersion (“8.0.0”)) {}
    win.attachEvent (“onunload”, function () {}
    var obj = getElementById (id);
    If (obj) {}
    for (var i in obj) {}
    If (typeof obj [i] == ‘function’) {}
    obj [i] = function() {};
    }
    }
    obj.parentNode.removeChild (obj);
    }
    });
    }
    }

    / * Display the Adobe quick installation dialog box
    -Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
    */
    function showExpressInstall (regObj) {}
    isExpressInstallActive = true;
    var obj = getElementById (regObj.id);
    If (obj) {}
    If {(regObj.altContentId)
    var ac = getElementById (regObj.altContentId);
    If {(ac)
    storedAltContent = ac;
    storedAltContentId = regObj.altContentId;
    }
    }
    else {}
    storedAltContent = abstractAltContent (obj);
    }
    If (!) () / %$/.test(regObj.width)) & & parseInt (regObj.width, 10) < 310) {}
    regObj.width = “310”;
    }
    If (!) () / %$/.test(regObj.height)) & & parseInt (regObj.height, 10) < 137) {}
    regObj.height = “137”;
    }
    doc.title = doc.title.slice (0, 47) + “-Flash Player Installation”;
    var pt = ua.ie & & ua.win? “ActiveX”: “PlugIn.”
    DT = doc.title,
    FV = “MMredirectURL =” + win.location + “& MMplayerType =” + pt + “& MMdoctitle =” + dt.
    replaceId = regObj.id;
    For IE when a SWF file is loading (AND: not available in the cache) wait for the onload event to remove the original object element
    In IE you can not properly cancel a loading SWF file without breaking the browser load references, also does not work obj.onreadystatechange
    If (ua.ie & & ua.win & & obj.readyState! = 4) {}
    var newObj = createElement (“div”);
    replaceId += “SWFObjectNew”;
    newObj.setAttribute (“id”, replaceId);
    obj.parentNode.insertBefore (newObj, obj); Insert the placeholder div will be replaced by the object element that loads expressinstall.swf
    obj.style.display = ‘none ‘;
    win.attachEvent (“onload”, function() {obj.parentNode.removeChild (obj) ;});
    }
    createSWF ({data: regObj.expressInstall id: EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height}, {flashvars:fv}, replaceId);
    }
    }

    / * Functions of abstraction and display alternative content
    */
    function displayAltContent (obj) {}
    If (ua.ie & & ua.win & & obj.readyState! = 4) {}
    For IE when a SWF file is loading (AND: not available in the cache) wait for the onload event to remove the original object element
    In IE you can not properly cancel a loading SWF file without breaking the browser load references, also does not work obj.onreadystatechange
    var El = createElement (“div”);
    obj.parentNode.insertBefore (el, obj); Insert the placeholder div will be replaced by alternative content
    el.parentNode.replaceChild (abstractAltContent (obj), el);
    obj.style.display = ‘none ‘;
    win.attachEvent (“onload”, function() {obj.parentNode.removeChild (obj) ;});
    }
    else {}
    obj.parentNode.replaceChild (abstractAltContent (obj), obj);
    }
    }

    function abstractAltContent (obj) {}
    var ac = createElement (“div”);
    If (ua.win & & ua.ie) {}
    ac.innerHTML = obj.innerHTML;
    }
    else {}
    var nestedObj = obj.getElementsByTagName (OBJECT) [0];
    If {(nestedObj)
    var c = nestedObj.childNodes;
    If {(c)
    CL var = c.length;
    for (var i = 0; i < cl; i ++) {}
    If (!) () c [i] .nodeType == 1 & & c [i].nodeName.toLowerCase () == ‘param’) & &! (c [i] .nodeType is 8)) {
    ac.appendChild (c [i] .cloneNode (true));
    }
    }
    }
    }
    }
    return ac;
    }

    / * Creation of dynamic Cross-browser SWF
    */
    function createSWF (attObj, parObj, id) {}
    var r, el is getElementById (id);
    If (typeof attObj.id == UNDEF) {/ / If no ‘id’ is defined for the object element, it will inherit the ‘id’ of alternative content}
    attObj.id = id;
    }
    If (ua.ie & & ua.win) {/ / do not combine the IE, the purpose and methods of the W3C DOM element: return to outerHTML}
    att var = “”;
    for (var i in attObj) {}
    If (attObj [i]! = Object.prototype [i]) {/ / filter out other potential libraries prototype additions, like Object.prototype.toJSONString = function() {}
    If (I == ‘data’) {}
    parObj.movie = attObj [i];
    }
    ElseIf (i.toLowerCase () == “styleclass”) {/ / ‘class’ is an ECMA4 reserved keyword}
    att += “class =” “+ attObj [i] ‘ + ‘” ‘; “
    }
    Else if (I! = “classid”) {}
    att += ‘ ‘ + i + “=” “+ attObj [i] ‘ + ‘” ‘; “
    }
    }
    }
    by var = “”;
    for {(var j in parObj)
    If (parObj [j]! = Object.prototype [j]) {/ / filter additions of other potential libraries prototype}
    “by += ‘ < param name =” “‘ + j + ‘” value = “” + parObj [j] + “” / > ‘;
    }
    }
    el.outerHTML = ‘ < object classid = “clsid:D27CDB6E-AE6D-11cf-96B8-444553540000” ‘ + att + ‘ > ‘ + by + ‘ < / object > “;
    fixObjectLeaks (attObj.id); This bug only affects dynamic publishing
    r = getElementById (attObj.id);
    }
    ElseIf (ua.webkit & & ua.webkit < 312) {/ / older webkit engines ignore elements nested in the element of the object param: fall to property incorporate element}
    var e = createElement (“embed”);
    e.setAttribute (“type”, FLASH_MIME_TYPE);
    for (var attObj k) {}
    If (attObj [k]! = Object.prototype [k]) {/ / filter additions of other potential libraries prototype}
    If (k == ‘data’) {}
    e.setAttribute (“src”, attObj [k]);
    }
    ElseIf (k.toLowerCase () == “styleclass”) {/ / ‘class’ is an ECMA4 reserved keyword}
    e.setAttribute (“class”, attObj [k]);
    }
    ElseIf (k! = “classid”) {/ / filter the specific attribute IE}
    e.setAttribute (k, attObj [k]);
    }
    }
    }
    for {(var l parObj)
    If (parObj [l]! = Object.prototype [l]) {/ / filter additions of other potential libraries prototype}
    If (l! = ‘movie’) {/ / filter the IE specific param elements}
    e.setAttribute (l, parObj [t]);
    }
    }
    }
    el.parentNode.replaceChild (e, el);
    r = e;
    }
    else {/ / good browsers behave}
    var o = createElement (OBJECT);
    o.setAttribute (“type”, FLASH_MIME_TYPE);
    for {(var m in attObj)
    If (attObj [m]! = Object.prototype [m]) {/ / filter additions of other potential libraries prototype}
    If (m.toLowerCase () == “styleclass”) {/ / ‘class’ is an ECMA4 reserved keyword}
    o.setAttribute (‘class’, attObj [m]);
    }
    Else if (m! = “classid”) {/ / filter the specific attribute IE}
    o.setAttribute (m, attObj [m]);
    }
    }
    }
    for {(var n in parObj)
    If (parObj [n]! = Object.prototype [n] & & n! = ‘movie’) {/ / filter additions of other potential libraries prototype and the IE specific param element}
    createObjParam (o, n, parObj [n]);
    }
    }
    el.parentNode.replaceChild (o, el);
    r = o;
    }
    Return r;
    }

    function createObjParam (el, pName, pValue) {}
    var p = createElement (“param”);
    p.setAttribute (“name”, pName);
    p.setAttribute (“value”, pValue);
    el.appendChild (p);
    }

    function getElementById (id) {}
    Return doc.getElementById (id);
    }

    function createElement (el) {}
    Doc.createElement (el) return;
    }

    function hasPlayerVersion (rv) {}
    var pv = ua.pv, v is rv.split(“.”);.
    v [0] = parseInt (v [0], 10);
    v [1] = parseInt (v [1], 10);
    v [2] = parseInt (v [2], 10);
    return (pv [0] > v [0] |) (pv [0] == v [0] & & pv [1] > v [1]) | (pv [0] == v [0] & & pv [1] == v [1] & & pv [2] > = v[2])) ? true: false;
    }

    / * Creation of dynamic Cross-browser CSS
    -Based on the solution of Bobby van der Sluis: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
    */
    function createCSS (salt, VAT statement) {}
    If (ua.ie & & ua.mac) {}
    return;
    }
    var h = doc.getElementsByTagName (“head”) [0], s = createElement (“style”);
    s.setAttribute (“type”, “text/css”);
    s.setAttribute (“media”, “screen”);
    If (!) () UA.ie & & ua.win) & & typeof doc.createTextNode! = UNDEF) {}
    s.appendChild (doc.createTextNode (salt + “{” + VAT statement + “}”));
    }
    h.appendChild (s);
    If (ua.ie & & ua.win & & typeof doc.styleSheets! = UNDEF & & doc.styleSheets.length > 0) {}
    ls = doc.styleSheets var [doc.styleSheets.length – 1];
    If (typeof ls.addRule == OBJECT) {}
    ls.addRule (salt, VAT statement);
    }
    }
    }

    function setVisibility (id, isVisible) {}
    var v = isVisible? “visible”: “hidden”;
    If {(isDomLoaded)
    getElementById (id).style.visibility = v;
    }
    else {}
    createCSS (“#” + id, “visibility:” + v);
    }
    }

    function getTargetVersion (obj) {}
    If (! obj)
    return 0;
    var c = obj.childNodes;
    CL var = c.length;
    for (var i = 0; i < cl; i ++) {}
    If (c [i] .nodeType == 1 & & c [i].nodeName.toLowerCase () ==’ object ‘ ‘) {}
    c = c [i] Sublst.ChildNodes(1).ChildNodes(0);
    cl = c.length;
    i = 0;
    }
    If (c [i] .nodeType == 1 & & c [i].nodeName.toLowerCase () == ‘param’ & & c [i] .getAttribute (“name”) == ‘swfversion’) {}
    Return c [i] .getAttribute (“value”);
    }
    }
    return 0;
    }

    function getExpressInstall (obj) {}
    If (! obj)
    Return ‘ ‘;
    var c = obj.childNodes;
    CL var = c.length;
    for (var i = 0; i < cl; i ++) {}
    If (c [i] .nodeType == 1 & & c [i].nodeName.toLowerCase () ==’ object ‘ ‘) {}
    c = c [i] Sublst.ChildNodes(1).ChildNodes(0);
    cl = c.length;
    i = 0;
    }
    If (c [i] .nodeType == 1 & & c [i].nodeName.toLowerCase () == ‘param’ & & c [i] .getAttribute (“name”) == “expressinstall”) {}
    Return c [i] .getAttribute (“value”);
    }
    }
    Return ‘ ‘;
    }

    return {}
    / * Public API
    -Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
    */
    registerObject: {function (objectIdStr, swfVersionStr, xiSwfUrlStr)
    If (! ua.w3cdom:! objectIdStr) {}
    return;
    }
    var obj = document.getElementById (objectIdStr);
    XI var = getExpressInstall (obj);
    var regObj = {};
    regObj.id = objectIdStr;
    regObj.swfVersion = swfVersionStr? swfVersionStr: getTargetVersion (obj);
    regObj.expressInstall = xiSwfUrlStr? xiSwfUrlStr: ((xi! = “”)?) XI: false);
    regObjArr [regObjArr.length] = regObj;
    setVisibility (objectIdStr, false);
    },

    getObjectById: {function (objectIdStr)}
    var r = null;
    If (ua.w3cdom & & isDomLoaded) {}
    var o = getElementById (objectIdStr);
    If (o) {}
    var n = o.getElementsByTagName (OBJECT) [0];
    If (! n |) (n & & typeof o.SetVariable! = UNDEF)) {
    r = o;
    }
    else if (typeof n.SetVariable! = UNDEF) {}
    r = n;
    }
    }
    }
    Return r;
    },

    embedSWF: function (swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {}
    If (! ua.w3cdom:! swfUrlStr |! replaceElemIdStr |! widthStr:! heightStr |! swfVersionStr) {}
    return;
    }
    widthStr += “”; Automatic conversion of string to be stupid
    heightStr += “”;
    If (hasPlayerVersion (swfVersionStr)) {}
    setVisibility (replaceElemIdStr, false);
    var att = (typeof attObj == OBJECT)? attObj: {};
    att. Data = swfUrlStr;
    att. Width = widthStr;
    att. Height = heightStr;
    by var = (typeof parObj is OBJECT)? parObj: {};
    If (typeof flashvarsObj == OBJECT) {}
    for (var i in flashvarsObj) {}
    If (flashvarsObj [i]! = Object.prototype [i]) {/ / filter additions of other potential libraries prototype}
    If (typeof par.flashvars! = UNDEF) {}
    by. FlashVars += “&” + i + “=” + flashvarsObj [i];
    }
    else {}
    by. FlashVars = i + “=” + flashvarsObj [i];
    }
    }
    }
    }
    {addDomLoadEvent (function ()}
    createSWF (att, par, replaceElemIdStr);
    If (att.id == replaceElemIdStr) {}
    setVisibility (replaceElemIdStr, true);
    }
    });
    }
    ElseIf (xiSwfUrlStr & &! isExpressInstallActive & & hasPlayerVersion (“6.0.65”) & & (ua.win | ua.mac)) {}
    setVisibility (replaceElemIdStr, false);
    {addDomLoadEvent (function ()}
    var regObj = {};
    regObj.id = regObj.altContentId = replaceElemIdStr;
    regObj.width = widthStr;
    regObj.height = heightStr;
    regObj.expressInstall = xiSwfUrlStr;
    showExpressInstall (regObj);
    });
    }
    },

    getFlashPlayerVersion: function() {}
    return {major: ua.pv [0], minor:ua.pv [1], release: ua.pv [2]};
    },

    hasFlashPlayerVersion:hasPlayerVersion,

    createSWF: {function (attObj, parObj, replaceElemIdStr)
    If (ua.w3cdom & & isDomLoaded) {}
    Return createSWF (attObj, parObj, replaceElemIdStr);
    }
    else {}
    return undefined;
    }
    },

    createCSS: function (salt, VAT statement) {}
    If {(ua.w3cdom)
    createCSS (salt, VAT statement);
    }
    },

    addDomLoadEvent:addDomLoadEvent,

    addLoadEvent:addLoadEvent,

    getQueryParamValue: {function (param)}
    var q = doc.location.search | doc. Location.Hash;
    If (param == null) {}
    Return to q;
    }
    {if (q)}
    var pairs = q.substring (1) .split (“&”);
    for (var i = 0; i < pairs.length; i ++) {}
    If (pairs [i] .substring (0, peers [i] .indexOf (“=”)) == param) {}
    peers return [i] .substring ((peers [i] .indexOf (“=”) + 1));
    }
    }
    }
    Return ‘ ‘;
    },

    For internal use only
    expressInstallCallback: function() {}
    If (isExpressInstallActive & & storedAltContent) {}
    var obj = getElementById (EXPRESS_INSTALL_ID);
    If (obj) {}
    obj.parentNode.replaceChild (storedAltContent, obj);
    If {(storedAltContentId)
    setVisibility (storedAltContentId, true);
    If (ua.ie & & ua.win) {}
    storedAltContent.style.display = ‘block ‘;
    }
    }
    storedAltContent = null;
    storedAltContentId = null;
    isExpressInstallActive = false;
    }
    }
    }

    };

    }();

    Hello

    It is a problem with the code you are using, to remove the lines marked in red and check if it works then. Or move the code of swfobjects, (6 off) above any other javascript code you have at the bottom of your page.

    
    

    PZ

  • For some reason, I can’t get a case number.

    For some reason I can’t get a case number. (https://helpx.adobe.com/contact.html?step=PSE) is it possible to send me a?

    Unfortunately, no. You have wandered in a user forum to and we are just other customers like you, not Adobe. You will need to contact them directly about this.

  • Case held (not gel) for some time

    So I got 2 analog input via NiMyrio and I got a deal of true/false because if the two signals larger than the trigger point as I put, it will enter in the case of true.

    The problem because both signals is put in correspondence with the comparison to very fast time, this means that the real case will happen after this date that is too fast. After that it will change to cuz case misstep signals of time corresponding to the comparison more.

    If the case don’t give me enough time to fulfill the function inside the housing. (example I want number 5 decremented to number 1 in 5 sec but it could not be done because of the case will turn to false cases like the true case happening very quickly)

    There is nothing to do with signals, their charesteristics who behave so

    I wonder is anyway I can hold the case for time to complete the function inside as the true case happening too quickly according to the signal.

    “I tried” delay “and” wait until the next multiple. They can hold, but at the same time to freeze the program as well which is meaningless cuz she also only freeze function inside I want to perform.

    IN summary, I want to keep (no gel) the true case and don’t function inside at the time of the operation, as described in the pictures

    Thanks for your help

    Here’s what happens:

    -Once the case is entered, the delay time say you keep of 100ms

    -If the remaining part of the code runs at scenario1:50ms and scenario2: 150ms

    -In scenario 1: because of the delay, the case held for 100 ms-50ms = 50ms

    -In scenario 2, the code moves after completing its code.

    -Until the delay time provides is the case will take minimum of 100 ms.

    -Timer is just pointer to the clock and during this time also code runs.

  • structure of cases with a string as a selector of case

    Hello everyone!
    I have little problem with the structure of matter
    location:
    I created the structure of case and case selection is made by the chain.
    According to the selection of respected cases led should light up

    the structure of the case is as follows:

    case 1 [when the string is ‘abc’]

    {

    LED 1 = true

    LED 2 = false

    }

    case 2 [when the string is “pqr”]

    {

    LED 1 = false

    LED 2 = true

    }

    case3 [when the string is “‘, by default]

    {

    LED 1 = false

    LED 2 = false

    }

    now what is happening:
    I clicked on the “continuous run”

    now when I type one chain that nothing happens!

    my observation:
    When I type abc/pqr in the entrance of the channel, it actually flashes the led for a fraction of the time that I can’t see, and the value in the default case.

    what I expect of this code!
    When I put “abc’ the entry in the chain,”led 1″should be lights up and stays on until I put pqr in the input string
    even when I put pqr in the input string, 2 LEDs should be lights up and remains lit until I put abc in the input string.

    Thanks in advance!

  • Structure (2 cases)

    Hello

    Im a new user of labview.  Can anyone help me design a case where the structure if TI Gets a 0, let say the action takes place, and if it receives any other number, B action occurs?

    In terms of code…

    If x == 0,

    A share

    On the other

    Action B

    Hi saranam16,

    This is an excerpt for 2012 SP1 (you can save the PNG on your computer and then drag and drop it on your block diagram into code).

    If wire you your X value for the selector of case for the structure of the case, by default, you will have a case which is 0, and the other case it is 1. If you right-click the border of the 1 case, you can make this default case, which means that it will run when all other cases are not met.

    To start using with LabVIEW, there are also a number of good resources here:http://www.ni.com/gettingstarted/labviewbasics/ and NOR offer of many training courses for users new to LabVIEW. If you have a SSP, training is available for free online.

    Hope that helps!

    Jeff Peacock

    Product Support Engineer | LabVIEW R & D | National Instruments

  • Set a style different cases for the same placeholder (data fusion) used two times in the same text

    Hello.

    I have a document with some parties updated with the fusion of data (via placeholders). Is it possible to set a style of different cases for the same placeholder in the same text. See the example:

    Mike runs its < < vehicule_placeholder > > in the city. But its < < VEHICULE_PLACEHOLDER > > is meant to be shared.

    If the value of this placeholder in the file merger is ‘bike’, the sentence should be:

    Mike runs his bike in the city. But his BIKE is meant to be shared.

    Is this possible? How?

    Thank you.

    You can do it. A character style for this configuration placeholder text, set in all caps.

  • Tips on how to make a business case for partitioning

    Hello world

    I am the architect of a team of business intelligence/data warehouse. We have grown to the point where I think that we need database partitioning. I believe that we are at approximately 1.5 TB of data. Our larger tables are the counts of 100 million lines with relatively large lengths Records (~ 100 columns). Our just a sort of large tables are of the order of 10 million to 50 million, however, they have very long line lengths (~ 300 columns). Based on the plans of our future source system, our data will become even more granular, and it is always necessary to maintain our historical data.

    Those who are not the only reasons, but are some conduct issues that make most of our team members think it’s time we purchased database partitioning. Our team is fairly unanimous for partitioning, many of our partners from the source system also deem an ‘evidence’, however, we get a push back of our CIO saying that 1.5 TB and 100 million records is not only the large amount of data compared to other ‘big Data’ businesses and that it requires no partitioning.

    Anyone has any advice on how to make a business case for the purchase of partitioning? Is there a good way to demonstrate the value of profitability-vs?

    Thanks for your comments.

    -= Joe

    The best cost c. analysis of benefits is that you put together based on points regardless of the pain you feel.

    For example, you have pain around your evening of meeting load ALS? If you do, you can watch how (and if) partitioning would allow you to streamline your loading process and how much time you would save probably every night. If you have no problem hitting your evening load ALS today, however, this probably isn’t something you want to focus on.

    You have pain around query response time? If Yes, you can watch how (and if) partitioning would improve some of the queries and most important reports. Or, perhaps, he would have you to allow users to do an ad hoc analysis more than you can’t afford today because the cost would be prohibitive.

    Although you will find no doubt generic cost v. benefit whitepapers, it tends to make a much better case if you focus on what causes the pain of the company and what you as the application developers are willing to commit to. It is easy for a CIO watch a generic white paper saying “partitioning reduces ETL time up to 99%” and the question of what improvements he or she would have actually see and how this is marketing hype. It is much more difficult to look at a document put in place by the data warehouse team saying “partitioning would allow us to reduce the load of X of Y hours on Z hours every night. “That would allow us to hit our SLA w % more often without adding hardware / additional treatment for A project that we have been postpone / let Department B start to work with the data more early every morning / what causes the pain of the IOC. Of course, this means that he must be willing to make such commitments (and, of course, to meet).

    Justin

  • What case for a Satellite U840 – 10 X?

    Hello

    I just bought a Satellite U840 – 10 X, and I can’t find a case that stops the laptop firmly without adding too much height.

    I found some cases for computers laptops 14 “but they have all 4cm of space on the inside, allowing him to move inside.
    The size of the U840 is 34.2 x 23.2 x 1.99 cm.

    Someone at – he found a good one?

    Thank you!

    Hello

    I found a few compatible cases for Satellite U840 / U845

    Advantage for computer laptop backpack Outdoor 40.6 cm (16-Zoll) PX1783E-1NCA
    Advantage, case 40.6 cm (16-Zoll) laptop PX1784E-1NCA
    Advantage Laptop Case Pro 40.6 cm (16) PX1785E-1NCA
    Advantage portable Trolley 43.9 cm (17.3 inch) PX1786E-1NCA

  • Aspire 7250-0209-case for hard drive

    Last spring, my Aspire 7250-0209, which I would do it only had a year and a half or two, ended up with a bottle of water that leak as I was toting it to a horse show where I was going to use for some scoring. After it dried, I could get it to power upward, go light on the DVD player, I could hear the hard disc spins, but nothing happened with the screen. I tried to plug it into an external monitor and nothing happens, so I presume that the video card is fried.

    Therefore, it is time to open things and reap the hard drive. I have done before with the help of a few friends knowledgeable and was able to put the hard drive in an inexpensive case that I bought online and it works more or less like an external hard drive. What I was asking is what are the physical dimensions of the hard drive for this machine and what kind of cable should I? I would buy the case ahead until I open things and started fussing with it. My other alternative is to take to a local computer shop where a friend just to have done similar work, but this guy charged $80 to do, and it’s money that I prefer to use for something else.

    Thanks for any advice you may have.

    Thank you! Exactly what I needed to know. The last time I did, the first case that I bought was wrong and I would rather not replay error. I appreciate your help.

  • I have a HP Pavilion Elite m9280f PC, I replaced the case for a larger, having connection problems

    I have a HP Pavilion Elite m9280f PC, S # [personal information deleted], Windows Vista 64-Bit. I replaced the case for a larger, having connection problems. Lost manual, downloaded manuals, I can not find a diagram of the wires hanging in the motherboard. Help please Tom

    Tomahawk, welcome to the forum.

    This is the page for Specifications of the motherboard of the computer.  You should be able to enlarge the diagram of the motherboard to locate most of the connections.  The only place you may have a problem is with the power button connector.  Some cases are not compatible with HP moterboards.

    Please let us know if this solved your problem or not.

  • new case for hp m9450f

    Hey I wanted to get a new case for my m9450f anyone know if:

    1 card mother using stand offs or is it directly bolted to the rear of the case?

    2. the I/O plate comes off or is it attached to the case?

    BTW I plan to get the corsair 600t, the plate of I/O is not a big problem, but if the Board is screwed into the case is anyway I can transfer the motherboard for a new case.

    Motherboards generally use spacers though some cases have accumulated mounting plate for the motherboard and spacers are not necessary.

    The I/O plate if I understand you well is part of the motherboard.  Most mATX cases should not be a problem.

  • I would suggest looking for values have something besides a space and adding the country code to those values. Something like this:

    (case when phonenr like '%[^ ]%' then '+46' + PHONENR 
          else ''
     end)
    

    That is, if the phone number contains a non-space character, then append the country code.

    You could even take this a step further, and append the country code only when the phone number has at least one digit:

    (case when phonenr like '%[0-9]%' then '+46' + PHONENR 
          else ''
     end)
    

    Let me go a step further. You can use check constraints to validate the data when it is put into the database. I would suggest a check constraint that validates the structure of the phone number — say, it only contains a set of characters or a NULL value:

    alter table add constraint chk_phonenr check (phonenr not like '%[^-0-9()+ ]%' and phonenr like '%[0-9]%')
    

    This would ensure that the field has reasonable values or NULL. If you had this constraint, your original query would work.

    New issue

    Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

    By clicking “Sign up for GitHub”, you agree to our terms of service and
    privacy statement. We’ll occasionally send you account related emails.

    Already on GitHub?
    Sign in
    to your account

    Closed

    roubaobaozi opened this issue

    Jun 12, 2018

    · 5 comments

    Comments

    @roubaobaozi

    What is the problem?

    selector-type-case has no customisation settings, and so fails with styled-components’ $dummyValue

    eg.

    ✖ Expected "$dummyValue" to be "$dummyvalue" selector-type-case

    What solution would you like to see?

    an ignore setting akin to selector-type-no-unknown: 'selector-type-no-unknown': [true, {ignoreTypes: ['$dummyValue']}],

    eg.

    'selector-type-case': ['lower', {ignoreTypes: ['/dummyValue/']}],

    Thanks!

    @jeddy3

    @sekek Thanks for the request and for using the template.

    I think the rule should ignore variables by default as variables are not type selectors.

    I assume this hasn’t come up before as variables are, unlike in styled-components, seldom used within selectors in preprocessors like Sass and Less.

    As the rule already makes use of the isStandardSyntaxTypeSelector util, it should just be the case of:

    1. Adding a condition to that util to return early for variables.
    2. Adding a “This rule ignores variables.” to the rule description.

    This will also fix the behaviour of selector-type-no-unknown.

    As the issue has been labelled “help wanted”, please consider contributing a fix.

    @jeddy3
    jeddy3

    changed the title
    ignore setting for selector-type-case

    False positives for variables in selector-type-case

    Jun 12, 2018

    @jeddy3
    jeddy3

    changed the title
    False positives for variables in selector-type-case

    Fix false positives for variables in selector-type-case

    Jun 18, 2018

    @XhmikosR

    I’m hitting this too…

    41:24 × Expected “The” to be “the” selector-type-case

    .alert-dismissable, // The misspelled .alert-dismissable was deprecated in 3.2.0.
    .alert-dismissible {
      padding-right: (@alert-padding + 20);
    
      // Adjust close link position
      .close {
        position: relative;
        top: -2px;
        right: -21px;
        color: inherit;
      }
    }

    @jeddy3

    @XhmikosR That looks like a different issue, perhaps related to comments and the Less parser. Can you please create a new issue, following the “Report a bug” template, so that we can better help resolve the issue for you.

    @niksajanjic

    I’m using these 2 rules to fix the problem:

    {
      rules: {
        'selector-type-case': [true, {
          ignoreTypes: ['/^\$\w+/'],
        }],
        'selector-type-no-unknown': [true, {
          ignoreTypes: ['/^\$\w+/'],
        }],
      }
    }

    This ignores variables starting with $.

    @Sowed

    I came here battling stylelint errors with styled-components custom elements. Thank you @niksajanjic , your solution was super helpful except for the selector-type-case option. It kept throwing the following warning with stylelint: ^13.2.0 and linting failed for those rules.

    Invalid Option: Invalid option value “true” for rule “selector-type-case”

    Changing the option to either lower or upper fixes the warning. This is my modified version of your rule.

        "selector-type-case": [
          "lower",
          {
            "ignoreTypes": [
              "/^\$\w+/"
            ]
          }
        ],
        "selector-type-no-unknown": [
          true,
          {
            "ignoreTypes": [
              "/^\$\w+/"
            ]
          }
        ]

    Время на прочтение
    11 мин

    Количество просмотров 52K

    Старый добрый switch был в Java с первого дня. Мы все используем его и привыкли к нему — особенно к его причудам (кого-нибудь еще раздражает break?). Но начиная с Java 12, ситуация начала меняться: switch вместо оператора стал выражением:

    boolean result = switch(ternaryBool) {
        case TRUE -> true;
        case FALSE -> false;
        case FILE_NOT_FOUND -> throw new UncheckedIOException(
            "This is ridiculous!",
            new FileNotFoundException());
        default -> throw new IllegalArgumentException("Seriously?!");
    };

    Результат работы switch-выражения теперь можно сохранять в переменную; ушла необходимость использовать break в каждой ветке case благодаря лямбда-синтаксису и многое другое.

    Когда дело доходит до switch после Java 14, необходимо выбрать стиль его использования:

    • оператор или выражение (с Java 14)
    • двоеточия или стрелки (с Java 14)
    • метки или шаблоны (3-й превью в Java 19)
      В этом руководстве я расскажу обо всем, что необходимо знать о switch-выражениях, и как их лучше всего использовать в современной Java.

    Недостатки оператора switch

    Прежде, чем мы перейдем к обзору нововведений, давайте рассмотрим один пример кода. Допустим, мы столкнулись с «ужасным» тернарным boolean и хотим преобразовать его в обычный boolean. Вот один из способов сделать это:

    boolean result;
    switch(ternaryBool) {
        case TRUE:
            result = true;
            break;
        case FALSE:
            result = false;
            break;
        case FILE_NOT_FOUND:
            // объявление переменной для демонстрации проблемы в default
            var ex = new UncheckedIOException("This is ridiculous!",
                 new FileNotFoundException());
            throw ex;
        default:
            // А вот и проблема: мы не можем объявить еще одну переменную с именем ex
            var ex2 = new IllegalArgumentException("Seriously?!");
            throw ex2;
    }

    Реализация данного кода хромает: наличие break в каждой ветке, которые легко забыть; можно не учесть все возможные значения ternaryBool (забыть реализовать какой-то case); с переменной result не все гладко — область видимости не соответствует ее использованию; нельзя объявить в разных ветках переменные с одинаковым именем. Согласитесь, что данное решение выглядит крайне громоздко и неудобно — тут явно есть, что улучшить.

    А вот пример попроще, демонстрирующий похожие проблемы:

    int result;
    switch (number) {
        case 1:
            result = callMethod("one");
            break;
        case 2:
            result = callMethod("two");
            break;
        default:
            result = callMethod("many");
            break;
    }

    Давайте попробуем устранить все недостатки, поместив switch в отдельный метод:

    private static boolean toBoolean(Bool ternaryBool) {
        switch(ternaryBool) {
            case TRUE: return true;
            case FALSE: return false;
            case FILE_NOT_FOUND:
                throw new UncheckedIOException("This is ridiculous!",
                      new FileNotFoundException());
            // без default метод не скомпилируется
            default:
                throw new IllegalArgumentException("Seriously?!");
          }
    }

    Так намного лучше: отсутствует фиктивная переменная result, нет break, загромождающих код и сообщений компилятора об отсутствии default (даже если в этом нет необходимости, как в данном случае).

    Но если подумать, то мы не обязаны создавать методы только для того, чтобы обойти неуклюжую особенность языка. И это даже без учёта, что такой рефакторинг не всегда возможен. Нет, нам нужно решение получше!

    Представляем switch-выражения!

    Начиная с Java 12 и выше, вы можете решить вышеуказанные проблемы следующим образом:

    boolean result = switch(ternaryBool) {
        case TRUE -> true;
        case FALSE -> false;
        case FILE_NOT_FOUND -> throw new UncheckedIOException(
            "This is ridiculous!",
            new FileNotFoundException());
        // в ветке `default` уже нет необходимости
        default -> throw new IllegalArgumentException("Seriously?!");
    };

    Я думаю, что это довольно очевидно: если ternartBool равен TRUE, то result будет присвоено true, а FALSE становится false.

    Сразу возникают две мысли:

    • switch теперь может иметь результат
    • какие возможности предоставляют стрелки?

    Прежде чем углубляться в детали новых возможностей, вначале я расскажу об этих двух аспектах.

    Выражение vs оператора

    Возможно, вы удивлены, что switch теперь является выражением. А чем же он был до этого? До Java 12 switch был оператором — императивной конструкцией, управляющей исполняющим потоком.

    Думайте о различиях старой и новой версии switch, как о разнице между if и тернарным оператором. Они оба проверяют логическое условие и выполняют ту или иную ветку в зависимости от его результата.

    Разница состоит в том, что if просто выполняет соответствующий блок, тогда как тернарный оператор возвращает какой-то результат:

    if(condition) {
        result = doThis();
    } else {
        result = doThat();
    }
    
    result = condition ? doThis() : doThat();

    То же самое и у switch: до Java 12, если вы хотели вычислить значение и сохранить результат, то должны были либо присвоить его переменной, либо вернуть из метода, созданного специально для оператора switch.

    Теперь же результат вычислений оператора switch может быть присвоен переменной.

    Еще одно отличие заключается в том, что поскольку выражение является частью оператора, то оно должно заканчиваться точкой с запятой, в отличие от классического оператора switch.

    Стрелка vs двоеточия

    В самом начале статьи использовался пример с новым синтаксисом в лямбда-стиле со стрелкой между меткой и выполняющейся частью. Эквивалентный ему код без лямбда-стиля можно записать так:

    boolean result = switch (ternaryBool) {
        case TRUE:
            yield true;
        case FALSE:
            yield false;
        case FILE_NOT_FOUND:
            throw new UncheckedIOException(
                "This is ridiculous!",
                new FileNotFoundException());
        default:
            throw new IllegalArgumentException("Seriously?!");
    };

    Обратите внимание, что вам нужно использовать новое ключевое слово yield, чтобы вернуть значение из ветки case (этот синтаксис появился в Java 13. В Java 12 вместо yield применялся break, т. е. break true вместо yield true, что выглядело странно).

    Исторически сложилось, что метки с двоеточием определяют точку входа в блок операторов. С этого места начинается выполнение всего кода ниже, даже когда встречается другая метка (при отсутствии break). Механизм такой работы известен, как сквозной переход к следующему case. Для его прерывания нужен break или return.

    Использование же стрелки позволяет выполнять только блок справа от нее. И никакого «проваливания».

    Подробнее об эволюции switch

    Несколько меток на case

    Отсутствие break в case часто используется для применения одинакового поведение к веткам с разными метками. При этом программа будет переходить к следующему case, пока не наткнется на break. Из этого можно сделать вывод, что оператор switch в каждом case поддерживает наличие только одной метки:

    switch (number) {
        case 1:
        case 2:
            callMethod("few");
            break;
        default:
            callMethod("many");
            break;
    }

    А в новом switch один case может соответствовать нескольким меткам:

    String result = switch(ternaryBool) {
        case TRUE, FALSE -> "sane";
        default -> "insane";
    };

    Поведение этого кода очевидно: TRUE и FALSE приводят к одному и тому же результату — вычисляется выражение “sane”.

    Подробнее о стрелке

    Начиная с Java 14, switch позволяет использовать лямбда-стрелку для “сопоставления” case с кодом:

    switch (number) {
        case 1 -> callMethod("one");
        case 2 -> callMethod("two");
        default -> callMethod("many");
    }

    Давайте рассмотрим два свойства, характерных для стрелочной формы записи разделителя:

    • отсутствие сквозного перехода к следующему case
    • блоки операторов

    Отсутствие сквозного перехода к следующему case

    Вот, что говорится в JEP 325 об этом:

    …Текущий дизайн оператора switch в Java тесно связан с такими языками, как C и C++ и по умолчанию поддерживает сквозную семантику. Хотя этот традиционный способ управления часто полезен для написания низкоуровневого кода (такого как парсеры для двоичного кодирования), поскольку switch используется в коде более высокого уровня, ошибки такого подхода начинают перевешивать его гибкость.

    Я полностью согласен и приветствую возможность использовать switch без поведения по умолчанию:

    switch(ternaryBool) {
        case TRUE, FALSE -> System.out.println("Bool was sane");
        default -> System.out.println("Bool was insane");
    };

    Стрелка позволяет вывести “Bool was sane” в единственном экземпляре, в то время, как с двоеточием это же сообщение отобразилось бы дважды.

    Блоки операторов

    Как и в случае с лямбдами, стрелка может указывать либо на один оператор (как выше), либо на блок, выделенный фигурными скобками:

    boolean result = switch (Bool.random()) {
        case TRUE -> {
            System.out.println("Bool true");
            yield true;
        }
        case FALSE -> {
            System.out.println("Bool false");
            yield false;
        }
        case FILE_NOT_FOUND -> {
            var ex = new UncheckedIOException(
                "This is ridiculous!",
                new FileNotFoundException());
                throw ex;
        }
        default -> {
            var ex = new IllegalArgumentException(
                "Seriously?!");
                throw ex;
        }
    };

    Блоки необходимы для использования более одной строки кода в case. При этом они имеют дополнительное преимущество — позволяют создавать одинаковые имена переменных в разных ветках за счет локальной области видимости для каждой ветки.

    Если вам показался необычным способ выхода из блоков с помощью yield, а не return, то это необходимо, чтобы избежать путаницы: return может быть неправильно истолкован, как выход из метода. Мы лишь завершаем работу switch, оставаясь в том же методе.

    Подробнее о выражениях switch

    И последнее, но не менее важное — особенности использования switch в качестве выражения:

    • множественные выражения
    • ранний возврат
    • охват всех значений (исчерпываемость)

    Множественные выражения

    Switch-выражения являются множественными выражениями. Это означает, что они не имеют своего собственного типа, но могут быть одним из нескольких типов. Наиболее часто в качестве таких выражений используются лямбда-выражения: s -> s + ” “, могут быть и Function<String, String>, и Function<Serializable, и Object> или UnaryOperator.

    Тип switch-выражения определяется исходя из типов его веток, а также из места его использования. Если результат работы switch-выражения присваивается типизированной переменной, передается в качестве аргумента или используется в контексте, где известен точный тип (целевой тип), то все его ветки должны соответствовать этому типу. Вот, что мы делали до сих пор:

    String result = switch (ternaryBool) {
        case TRUE, FALSE -> "sane";
        default -> "insane";
    };

    Как итог — switch присваивается переменной String result. Следовательно, String является целевым типом, и все ветки должны возвращать результат этого типа.

    То же самое происходит и здесь:

    Serializable serializableMessage = switch (bool) {
        case TRUE, FALSE -> "sane";
        // note that we don't throw the exception!
        // but it's `Serializable`, so it matches the target type
        default -> new IllegalArgumentException("insane");
    };

    А что произойдет сейчас?

    // compiler infers super type of `String` and
    // `IllegalArgumentException` ~> `Serializable`
    var serializableMessage = switch (bool) {
        case TRUE, FALSE -> "sane";
        // note that we don't throw the exception!
        default -> new IllegalArgumentException("insane");
    };

    Про применение типа var можно прочитать в статье: “26 рекомендаций по использованию типа var в Java”.

    Если целевой тип неизвестен из-за использования var, то он вычисляется путем нахождения наиболее конкретного супертипа из типов, создаваемых ветками.

    Ранний возврат

    Следствием различия между выражением и оператором switch является то, что вы можете использовать return для выхода из оператора switch:

    public String sanity(Bool ternaryBool) {
        switch (ternaryBool) {
            // `return` is only possible from block
            case TRUE, FALSE -> { return "sane"; }
            default -> { return "This is ridiculous!"; }
        };
    }

    А вот внутри выражения использовать return уже не получится:

    public String sanity(Bool ternaryBool) {
        String result = switch (ternaryBool) {
            // this does not compile - error:
            // "return outside of enclosing switch expression"
            case TRUE, FALSE -> { return "sane"; }
            default -> { return "This is ridiculous!"; }
        };
    }

    Это имеет смысл независимо от того, используете ли вы стрелку или двоеточие.

    Охват всех значений (исчерпываемость)

    Если вы используете switch в качестве оператора, тогда не имеет значения, охвачены все варианты или нет. Конечно, вы можете случайно пропустить case, и код будет работать неправильно, но компилятору все равно — вы, ваша IDE и ваши инструменты анализа кода останетесь с этим наедине.

    Switch-выражения усугубляют эту проблему. Куда следует перейти switch, если нужная метка отсутствует? Единственный ответ, который может дать Java — это возвращать null для ссылочных типов и значение по умолчанию для примитивов. Это породило бы множество ошибок в основном коде.

    Чтобы предотвратить такой исход, компилятор может помочь вам. Для switch-выражений компилятор будет настаивать, чтобы все возможные варианты были охвачены. Для каждого возможного значения переменной switch должна быть ветвь — это называется исчерпываемостью. Давайте посмотрим на пример, который может привести к ошибке компиляции:

    // compile error:
    // "the switch expression does not cover all possible input values"
    boolean result = switch (ternaryBool) {
        case TRUE -> true;
        // no case for `FALSE`
        case FILE_NOT_FOUND -> throw new UncheckedIOException(
            "This is ridiculous!",
            new FileNotFoundException());
    };

    Интересным является следующее решение: добавление ветки default, конечно, исправит ошибку, но это не является единственным решением — еще можно добавить case для FALSE.

    // compiles without `default` branch because
    // all cases for `ternaryBool` are covered
    boolean result = switch (ternaryBool) {
        case TRUE -> true;
        case FALSE -> false;
        case FILE_NOT_FOUND -> throw new UncheckedIOException(
            "This is ridiculous!",
            new FileNotFoundException());
    };

    Да, компилятор наконец-то сможет определить, охватываются ли все значения enum, что позволяет не использовать бесполезные значения в default!

    Что касается исчерпываемости, я стараюсь избегать ветвей по умолчанию, когда это возможно, предпочитая получать ошибки компиляции, когда что-то меняется.

    Хотя, это все же вызывает один вопрос. Что делать, если кто-то возьмет и превратит сумасшедший Bool в кватернионный (с четырьмя значениями) Boolean, добавив четвертое значение? Если вы перекомпилируете switch-выражение для расширенного Bool, то получите ошибку компиляции (т. к. выражение больше не будет исчерпывающим). Чтобы отловить эту проблему, компилятор переходит в ветку default, которая ведет себя так же, как та, которую мы использовали до сих пор, вызывая исключение.

    В настоящее время охват всех значений без ветки default работает только для enum, но когда switch в будущих версиях Java станет более мощным, он также сможет работать и с произвольными типами. Если метки case смогут не только проверять равенство, но и проводить сравнения (например _ < 5 -> …) — это позволит охватить все варианты для числовых типов.

    Как пользоваться switch в современной Java

    До этого мы рассматривали изменения, которые произошли до Java 14. Теперь обсудим то, что было реализовано после.

    Паттерны (шаблоны)

    Реализация сопоставления с образцом в switch все еще находится в процессе разработки, но есть три аспекта, которые особенно интересны по данной теме.

    Паттерны типов

    На момент написания статьи Java поддерживает только паттерны типов (Type Patterns) с паттернами деконструкции для записей (records), предложенными JEP 405. Их уже можно использовать в операторах if и switch:

    Object obj = // ...
    
    // работает с Java 16
    if (obj instanceof String str)
        callStringMethod(str);
    else if (obj instanceof Number no)
        callNumberMethod(no);
    else
        callObjectMethod(obj);
    
    // работает (как превью) с JDK 17+
    switch (obj) {
        case String str -> callStringMethod(str);
        case Number no -> callNumberMethod(no);
        default -> callObjectMethod(obj);
    }

    Я думаю, что с такими возможностями switch станет более функциональным и интуитивным за счет того, что:

    • более четко выражает намерение выполнить ровно одну ветвь на основе свойств obj
    • компилятор проверяет исчерпываемость
    • если необходимо вычислить значение, то использование switch в качестве выражения является более кратким

    Применение уточнений (Clauses)

    Уточнения (ранее — guarded patterns) расширяют возможности паттерна с помощью дополнительных логических проверок. Это может быть представлено следующим образом (синтаксис, придуманный мной):

    String str = // ...
    String length = switch (str) {
        case str.length() > 42 -> "long";
        case str.length() > 19 -> "medium";
        case str.length() > 1 -> "small";
        case null || str.length() == 0 -> "empty";
    };

    По мере того, как switch становится все более мощным, я предполагаю, что он начнет поглощать части кода, для реализации которых используется if-else-if.

    Выводы

    Из статьи мы узнали, что Java превращает switch в выражение, наделяя его новыми возможностями:

    • теперь один case может соответствовать нескольким меткам
    • новая стрелочная форма case … -> … следует синтаксису лямбда-выражений:
      • допускаются однострочные операторы или блоки
      • предотвращается сквозной переход к следующему case
    • теперь все выражение оценивается, как значение, которое затем может быть присвоено переменной или передано, как часть более крупного оператора
    • множественное выражение: если целевой тип известен, то все ветки должны ему соответствовать. В противном случае определяется конкретный тип, который соответствует всем веткам
    • yield возвращает значение из блока
    • для выражения switch, использующее enum, компилятор проверяет охват всех его значений. Если default отсутствует, добавляется ветка, которая вызывает исключение
    • если шаблоны станут более функциональными, то они смогут сделать switch предпочтительнее if

    Добавить комментарий