How to utilize if/else condition for JSON column formatting in SharePoint?

I am trying to format the color of a column based on the selection of another column in the same View. But, I am having trouble writing the JSON to check for multiple values in the other column. Here is my code so far that only checks for one selection, “Red”. I want it to check for the other possible options, which are “Green”, “Blue”, “Amber”, and “Gray”.

{   "$  schema": "",   "elmType": "div",   "txtContent": "@currentField",   "style": {     "background-color": "=if([$  OtherColumn] == 'Red', 'red', '')"   } } 

SQL Server estrutura IF/ELSE

Estou tentando criar uma procedure que verifique se uma tabela esta vazia, caso esteja vazia, a procedure deve retornar “Empty”, caso não esteja vazia, retornar o valor referente ao maior timestamp.

Minha procedure :

ALTER PROCEDURE [dbo].[spAVL_Ignition] AS BEGIN     IF @@ROWCOUNT = 0         select 'Empty'     ELSE         SELECT CONVERT (int,Value)         FROM AVL_Ignition         WHERE TimeStamp = (SELECT MAX(TimeStamp) FROM AVL_Ignition) END 

O problema que estou tendo é que independente da tabela estar ou não vazia a procedure sempre retorna “Empty”. Gostaria de saber onde esta o erro na minha procedure.

Adding RSpec coverage for a method with if/else logic

So I am fairly new to RSpec and Rails and I’ve been trying to learn RSpec as much as possible and I am really struggling with implementing coverage for methods that contain logic in them.

The app that I am practicing with uses coverage percentages to make sure I am properly covering the code I am implementing and I am missing coverage on the following method:

def initialize_business   businesses.each do |business|     if business.type == 'Restaurant'       @business_type = 'restaurant.json')     elsif business.type = 'Bar'       @business_type = 'bar.json')     else       @business_type = 'other_business.json')     end   end   business_type = @business_type   initialize_business_creator(business_type) end 

My initial attempt at providing coverage (left out the other unrelated specs) but I struggled to even implement any coverage as I’m too new to RSpec:

describe '#initialize_business' do     subject do[business], business_sample_file).       initialize_business_creator     end      it 'assigns a value to @business_type' do       expect(assigns(@business_type)).to_not be_nil     end   end end 

I’m just looking for some help and/or guidance on how to implement specs for a method like this and I appreciate any and all help. Thank you!

Конструкция if..else с отрицательным условием

Помогите, пожалуйста, прояснить ситуацию. Есть конструкция вида:

var status = 'medium';  if(status != 'strong' || status != 'medium'){     console.log('легкий пароль'); } 

Мне нужно вывести пользователю предупреждение, если он указал легкий пароль.

Я дословно читаю ее: “Если переменная status НЕ равна strong, либо НЕ равна medium, то вывести в консоль сообщение”. В данном случае, при том, что переменная равна одному из условий, все равно выводится сообщение в консоль. Я не знаю почему, ведь конструкция в скобках представляется собой одно целое выражение. По крайней мере status != 'medium' должен возвращать false.

Вот то, как для меня это должно работать:

if(status == 'strong' || status == 'medium'){  }else{     console.log('легкий пароль'); } 

Как переписать это выражение с одним условием без else, где status не должен быть равен либо strong, либо medium?

Why are my if/else statements in page.html.twig ignored?

in my theme template of page.html.twig (theme is a subtheme of classy core theme), my if statements to render a region or not are completely ignored by twig template engine. The regions (e.g. the first sidebar are always rendered.

Code of my page.html.twig:

  <header role="banner">     {{ page.header }}   </header>    {{ page.primary_menu }}   {{ page.secondary_menu }}        {% if page.navigation %}       <nav class="layout-navigation" role="navigation">         {{ page.navigation }}       </nav>     {% endif %}    {{ page.breadcrumb }}    {% if page.system_messages_area %}      {{ page.system_messages_area }}    {% endif %}    {{ page.highlighted }}    {{ }}     <div id="main-wrapper">     <main role="main">       <a id="main-content" tabindex="-1"></a>{# link is in html.html.twig #}        <div class="layout-content">         {{ page.content }}       </div>{# /.layout-content #}        {% if page.sidebar_first %}         <aside class="layout-sidebar-first sidebar" role="complementary">           {{ page.sidebar_first }}         </aside>       {% endif %}        {% if page.sidebar_second %}         <aside class="layout-sidebar-second sidebar" role="complementary">           {{ page.sidebar_second }}         </aside>       {% endif %}      </main>   </div>        {% if page.footer %}     <footer role="contentinfo">       {{ page.footer }}     </footer>   {% endif %} 

Code of my

name: mytheme type: theme description: Based on classy core base theme. core: 8.x # Defines the base theme base theme: classy # Defines libraries group in which we can add css/js. logo: logo.png libraries:   - mytheme/global-styling # Regions regions:   header: Header   navigation: Navigation and Menus   system_messages_area: Area for system messages    highlighted: Featured   help: Help   content: Content   sidebar_first: First sidebar   sidebar_second: Second sidebar   footer: Footer 

Maybe someone could help me to find the mistake, as far as I can see everything is at it’s right place.

Thanks in advance

Best regards phil

Python 3 – Controle de Fluxo inesperado ao executar IF/IF NOT ou IF/ELSE

Eu sou novo em Python, mas já tenho costume programa em Java.

Gostaria de entender melhor o porquê ao tentar programar um controle de fluxo usando IF/ELSE ou IF/IF NOT o bloco todo é executado.

Código Python 3.7

luz_acessa = False def interruptor():     global luz_acessa     if luz_acessa:         print("True: Luz acessa")         luz_acessa = False     if not luz_acessa: // Mesma coisa com 'else' ao invés de 'if not'         print("False: Luz apagada")         luz_acessa = True  

Console Python 3.7

interruptor() False: Luz apagada interruptor() True: Luz acessa False: Luz apagada interruptor() True: Luz acessa False: Luz apagada interruptor() True: Luz acessa False: Luz apagada 

Por exemplo em Java, se eu quiser inverter um boolean faço algo simples assim:

Código Java:

private boolean luz_ligada;     private void interruptor(){         if(luz_ligada){             System.out.println("Luz acessa");             luz_ligada = false;         } else {             System.out.println("Luz apagada");             luz_ligada = true;         }     } 

Log Java em um simples loop:

Luz apagada Luz acessa Luz apagada Luz acessa Luz apagada  Process finished with exit code 0 

Repetição de if/else como reduzir e melhorar o código?

Estou iniciando na programação e me surgiu uma dúvida durante as minhas condições. Eu faço uma verificação de quantas vezes deu verdadeiro o resultado, e quantas vezes deu falso. Problema é que não está me dando o resultado de verdade.

A única forma que encontrei para funcionar é a seguinte:

   if (Lstr_Resultado1 == "Verdadeiro")             {                 Lint_TotalVerdadeiro++;             }             else             {                 Lint_TotalFalso++;             }             if (Lstr_Resultado2 == "Verdadeiro")             {                 Lint_TotalVerdadeiro++;             }             else             {                 Lint_TotalFalso++;             }             if (Lstr_Resultado3 == "Verdadeiro")             {                 Lint_TotalVerdadeiro++;             }             else             {                 Lint_TotalFalso++;             } 

Acredito que exista uma forma mais performática para se fazer isso. Sei que estou iniciando e a aplicação é simples mas procuro reduzir o uso de processamento da máquina. Qual seria a melhor forma de resolver essa quantia de if / else?

Evaluating expressions in “case” vs using “if/else if”

I was just tempted to write a similar piece of code to the one presented in this answer on SO (posted below). The problem is having to discriminate between different cases where exactly one case is true.

In my experience switch statements are usually use to match the value of an expression against various constants. But in this case we use a switch statement to decide which of the conditions is true. To do this I would actually prefer using if/else if because switch(true) feels a little bit like an abuse of switch, but this is just a gut feeling. On the other hand I think this piece of code is still prefectly readable even with its seemingly unconventional use of a switch statement.

Are there any objective reasons why one would prefer switch over if/else if or vice versa when it comes to code quality, performance and readability?

switch (true) {   case (amount >= 7500 && amount < 10000):     //code     break;   case (amount >= 10000 && amount < 15000):     //code     break;    //etc... 

Use if/else if and each function together

I tried to write a code using each function and if statement. The problem I am having is when the condition is true, it stays that condition and doesn’t read else if condition.

Current code

$  ('.a_class').each(function() { #assume it iterates 3 times  if ( === "student_1"){   $  ('#a_student1').append('A');  }   else if ( === "student_2"){   $  ('#a_student2').append('B');  } else {   $  ('#a_student3').append('C');  } }); 

so basically, when the class id is 1, I would like to append A to the div named a_student1 and I don’t want to A to the other div such as a_student2 and a_student3 but when a_class‘s id is student_2, I only want to append B to a_student2 not others. But currently, once the first condition is true, every div has A. Any help?

django use html button as if/else selection in views

thanks in advance

I’m new to web development and I’m task to do this Django project.

I had Selection the user will select one and tells the views which chose to use (if & else if)

then the view Query the data from DB and will return to HTML

I try using this following this answer: Django – How to do an if statement if button is clicked

but run into this error:

Environment:   Request Method: GET Request URL:  Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin',  'django.contrib.auth',  'django.contrib.contenttypes',  'django.contrib.sessions',  'django.contrib.messages',  'django.contrib.staticfiles',  'rest_framework',  'zigview'] Installed Middleware: ['',  'django.contrib.sessions.middleware.SessionMiddleware',  'django.middleware.common.CommonMiddleware',  'django.middleware.csrf.CsrfViewMiddleware',  'django.contrib.auth.middleware.AuthenticationMiddleware',  'django.contrib.messages.middleware.MessageMiddleware',  'django.middleware.clickjacking.XFrameOptionsMiddleware']    Traceback:  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\" in inner   34.             response = get_response(request)  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\" in _get_response   126.                 response = self.process_exception_by_middleware(e, request)  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\" in _get_response   124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\" in _wrapped_view   21.                 return view_func(request, *args, **kwargs)  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\" in view   68.             return self.dispatch(request, *args, **kwargs)  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\" in dispatch   88.         return handler(request, *args, **kwargs)  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\" in get   157.         context = self.get_context_data()  File "C:\Users\user\Desktop\Frouniter\FrounterWeb- postgreDB\zigview\" in get_context_data   46.             if request.GET.get('Week') == 'Week':  Exception Type: NameError at /ph-data/ Exception Value: name 'request' is not defined 

I move to seconds solution which is to use ajax, but the more Look at ajax the more lost i’m am.

Questions Summary:

  1. Need to send get request to back end
  2. Request got to back end and it will see which data should go out
  3. return the selected/filter data (week, day etc etc)