text:
Q: How to inherit from an exception to create a more specific Error? I'm using a third party API which emits an HttpError.
By catching this error I can inspect the http response status and narrow down the problem.  So now I would like to emit a more specific HttpError which I'll dub BackendError and RatelimitError. The latter has context variables to be added.
How do I create a custom exception which inherits from HttpError and can be created without losing the original exception?
The question is actually polymorphism 101 but my head is fuzzy today:
class BackendError(HttpError):
    """The Google API is having it's own issues"""
    def __init__(self, ex):
        # super doesn't seem right because I already have
        # the exception. Surely I don't need to extract the
        # relevant bits from ex and call __init__ again?!
        # self = ex   # doesn't feel right either

try:
     stuff()
except HttpError as ex:
     if ex.resp.status == 500:
         raise BackendError(ex)

How do we catch the original HttpError and encapsulate it so it is still recognisable as both an HttpError and a BackendError?

A: If you look at the actual definition of googleapiclient.errors.HttpError,
__init__(self, resp, content, uri=None)

So, after inheriting you need to initialize the base class with all those values.
class BackendError(HttpError):
    """The Google API is having it's own issues"""
    def __init__(self, resp, content, uri=None):
        # Invoke the super class's __init__
        super(BackendError, self).__init__(resp, content, uri)

        # Customization can be done here

And then when you catch the Error,
except HttpError as ex:
     if ex.resp.status == 500:
         raise BackendError(ex.resp, ex.content, ex.uri)

If you don't want the client to explicitly unpack the contents, you can accept the HTTPError object in the BackendError's __init__ and then you can do the unpacking, like this
class BackendError(HttpError):
    """The Google API is having it's own issues"""
    def __init__(self, ex):
        # Invoke the super class's __init__
        super(BackendError, self).__init__(ex.resp, ex.content, ex.uri)

        # Customization can be done here

and then you can simply do
except HttpError as ex:
     if ex.resp.status == 500:
         raise BackendError(ex)


text:
Q: What is the maximum number of persons that may have shaken hands with everyone?
A number $n\ge3$ of persons meet at a party, and some of them shake hands. It is known that at least one person does not shake hands with everybody (that is, maybe he/she shakes hands with someone, but not with everyone). What is the maximum number of persons that may have shaken hands with everyone?

*

*$n/2$

*$n-1$

*$n-2$

*None of the above

Hi. I am unsure about this question - I have answered $n - 1$, as we know one of the person doesn't shake hands.

A: There's at least one other person that the not-shaking-all person did not shake hands with, so $n-1$ cannot be reached. However, $n-2$ indeed can be reached: Pick two persons $A,B$ and let everybody shake all hands except that $A,B$ do not shake hands.

A: If N-1 is correct, then there's just that one guy that didn't shake everyone's hand. But if he missed even 1 person, the minimum to "not shake everyone's" than that person didn't shake everyone's either.
So we drop to N-2 to satisfy the statement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Will a PC keep a WCF service open after restart if not shut down correctly? We are seeing an issue with a WPF application that opens a WCF service that listens to accept data on a port. We had a shortcut that would automatically start this WPF on startup and it worked fine, but we have started restarting the PC through RDP and now when the computer restarts, we get a TCP error in the WPF "The Requested address is not valid in its context" while listening on the correct IP. When we close out of the app and open it back up, it works fine. Is it possible that when we restart without closing this application, it does not quit this connection so on startup when it tries to open this application and start a new service, there is a conflict? I'm new to WCF services and don't know a lot about the inner workings like this, but it seems to me like when we get this error then close out the app we are correctly shutting down this service as well so there is no conflict when we start again.
EDIT: The answer was that networking was not up yet when the app was started. We added a 10 second delay in the batch file to allow for networking to start before running the app:
choice /C X /T 10 /D X > nul

A: With each new Windows version the user can earlier interact with his session but not everything has completely started up. That makes you feel the new system is much more faster than the old as it really is.
Applications that will run on session startup will have to deal with that when the session starts right after a system restart.
So check the system state before starting the service or just retry starting the service until it gets up.


text:
Q: Exact sequences of $\mathcal{O}_X$-modules and splitting Let $X$ be a scheme (a curve over a field for example). Exactness of a sequence $\mathcal{F}\to \mathcal{G}\to \mathcal{H}$ of $\mathcal{O}_X$-modules can be checked on stalks : it is exact if and only if $\mathcal{F}_x\to \mathcal{G}_x\to \mathcal{H}_x$ is exact for every $x\in X$.
If $0\to \mathcal{F}\to\mathcal{G}\to\mathcal{H}\to 0$ is split exact, then so are each of the $0\to \mathcal{F}_x\to \mathcal{G}_x\to \mathcal{H}_x\to 0$, but the converse isn't necessarily true I think.
My question is this : are there useful ``local'' or other criteria (or maybe an obstruction theory of some sort) for checking split exactness of sequences of $\mathcal{O}_X$-modules?

A: I don't think local is way to go here, because being split on the level of the whole sheaf tautologically requires the existence of a global section to the surjection.
However that's exactly what $Ext^1 (\mathcal{H}, \mathcal{F})$ is for (your obstruction theory if you wish). Split exact sequence corresponds to $0$ element in the Ext group. You can use full force of homological algebra to check it. In particular, since you were interested in the possibility of the local answer, often you can utilize the local-to-global spectral sequence: $$H^q(X, \mathcal{Ext}^p (\mathcal{H}, \mathcal{F})) \implies Ext^{p+q}(\mathcal{H},\mathcal{F}).$$

A: Just to parrot off the @Bananeen, I think the answer is "Yes, if $X$ is affine".      Here's a proof along the lines of the last answer.
$H^i(Hom_{O_X}(H,F))=0$, $i>0$ because the higher cohomology of any coherent sheaf is 0 (see here(Hartshorne III.3.5)) for an easy proof.  Use this in the local to global spectral sequence as follows.
The relevant part of the exact sequence of low order terms is
$H^1( \mathcal{Ext^0(H,F)}) \to Ext^1(\mathcal{H,F}) \to H^0(\mathcal{Ext^1(H,F)}) \to H^2(\mathcal{Ext^0(H,F)})$
By the above, the first and last terms are zero so
$Ext^1(\mathcal{H,F}) \cong H^0(\mathcal{Ext^1(H,F)})$
To understand what this means, lets recall what the global sections of the sheafification of a presheaf are.  They are essentially local sections of a presheaf that are compatible.  Usually all you have is a map from global sections of the presheaf to global sections of the sheafification and one cannot know if its injective or surjective.
Now, consider the presheaf $U \to Ext^1(H(U),F(U))$.  Its sheafification is $\mathcal{Ext^1(H,F)}$.  The global sections of the presheaf make up the LHS of the above iso.  The global sections of the sheafification make up the RHS of the iso. Hence sheafification commutes with global sections in our case!
Our extension maps to zero in $Ext^1_{\mathcal{O(U)}}(\mathcal{H}(U),\mathcal{F}(U))$ for all sufficiently small $U$ by hypothesis. Hence it maps to the 0 global section of $H^0(\mathcal{Ext^1(H,F)})$.  And therefore it maps to $0$ in $Ext^1(H,F)$. So the extension splits.
(Also if anyone knows a simpler way of showing this fact, I'd appreciate a comment :) )


text:
Q: Create JSON from XML - JSON_AGG OUTPUT PROBLEM I have a problem with converting XML content to JSON format (with plain oracle select statement), where more then 1 sub level of data is present in the original XML - with my code the result of level 2+ is presented as string and not as JSON_OBJECT. Please, could someone tell me, where is fault in my code or what I'm doing wrong:
source:
<envelope>
  <sender>
    <name>IZS</name>
    <country>SU</country>
    <address>LOCATION 10B</address>
    <address>1000 CITY</address>
    <sender_identifier>SU46794093</sender_identifier>
    <sender_address>
      <sender_agent>SKWWSI20XXX</sender_agent>
      <sender_mailbox>SI56031098765414228</sender_mailbox>
    </sender_address>
  </sender>
</envelope>

transformation select statement:
WITH SAMPLE AS (SELECT XMLTYPE ('
<envelope>
  <sender>
    <name>IZS</name>
    <country>SU</country>
    <address>LOCATION 10B</address>
    <address>1000 CITY</address>
    <sender_identifier>SU46794093</sender_identifier>
    <sender_address>
      <sender_agent>SKWWSI20XXX</sender_agent>
      <sender_mailbox>SI56031098765414228</sender_mailbox>
    </sender_address>
  </sender>
</envelope>') XMLDOC FROM DUAL)
         SELECT JSON_SERIALIZE (
                    JSON_OBJECT (
                        KEY 'envelope' VALUE
                            JSON_OBJECTAGG (
                                KEY ID_LEVEL1 VALUE
                                    CASE ID_LEVEL1
                                        WHEN 'sender' THEN
                                            (      SELECT JSON_OBJECTAGG (
                                                              KEY ID_LEVEL2 VALUE
                                                                  CASE ID_LEVEL2
                                                                      WHEN 'sender_address' THEN
                                                                          (      SELECT JSON_OBJECTagg (KEY ID_LEVEL22 VALUE TEXT_LEVEL22)
                                                                                FROM    XMLTABLE ('/sender/sender_address/*'
                                                                                PASSING  XML_LEVEL2
                                                                                COLUMNS  ID_LEVEL22 VARCHAR2 (128) PATH './name()',
                                                                                TEXT_LEVEL22 VARCHAR2 (128) PATH './text()'
                                                                                )
                                                                          )
                                                                      ELSE
                                                                          TEXT_LEVEL2
                                                                  END)
                                                     FROM   XMLTABLE    ('/sender/*'
                                                            PASSING     XML_LEVEL2
                                                            COLUMNS     ID_LEVEL2 VARCHAR2 (1024) PATH './name()',
                                                                        TEXT_LEVEL2 VARCHAR2 (1024) PATH './text()'
                                                                        )
                                            )
                                        ELSE
                                            '"' || TEXT_LEVEL1 || '"'
                                    END FORMAT JSON)
                                ) PRETTY
                               )JSON_DOC
           FROM SAMPLE, XMLTABLE ('/envelope/*'
                        PASSING XMLDOC
                        COLUMNS ID_LEVEL1 VARCHAR2 (1024) PATH './name()',
                                TEXT_LEVEL1 VARCHAR2 (1024) PATH './text()',
                                XML_LEVEL2 XMLTYPE PATH '.'
                                );

wrong result:
{
  "envelope" :
  {
    "sender" :
    {
      "name" : "IZS",
      "country" : "SU",
      "address" : "LOCATION 10B",
      "address" : "1000 CITY",
      "sender_identifier" : "SU46794093",
      "sender_address" : "{\"sender_agent\":\"SKWWSI20XXX\",\"sender_mailbox\":\"SI56031098765414228\"}"
    }
  }
}

wrong part:
      ***"sender_address" : "{\"sender_agent\":\"SKWWSI20XXX\",\"sender_mailbox\":\"SI56031098765414228\"}"***

A: The problem is that you need  kind of conditional "FORMAT JSON" in the "SELECT JSON_OBJECTAGG ( KEY ID_LEVEL2 VALUECASE ID_LEVEL2": when the ID_LEVEL2 is 'sender_address' but not in the ELSE part, but the syntax requires you put after the END of CASE, and of course this fails for the "ELSE TEXT_LEVEL2" part.

A: For the level 1 text you're wrapping the value in double-quotes and specifying format json; you aren't doing that for level 2. If you change:
ELSE
  TEXT_LEVEL2
END

to:
ELSE
  '"' || TEXT_LEVEL2 || '"'
END FORMAT JSON)

then the result is:
{
  "envelope" :
  {
    "sender" :
    {
      "name" : "IZS",
      "country" : "SU",
      "address" : "LOCATION 10B",
      "address" : "1000 CITY",
      "sender_identifier" : "SU46794093",
      "sender_address" :
      {
        "sender_agent" : "SKWWSI20XXX",
        "sender_mailbox" : "SI56031098765414228"
      }
    }
  }
}

fiddle


text:
Q: Deleting s3 file also deletes the folder python code I am trying to delete all the files inside a folder in S3 Bucket using the below python code but the folder is also getting deleted along with the file
import boto3
s3 = boto3.resource('s3')
old_bucket_name='new-bucket'
old_prefix='data/'
old_bucket = s3.Bucket(old_bucket_name)

old_bucket.objects.filter(Prefix=old_prefix).delete()

A: S3 does not have folders. Object names can contain / and the console will represent objects with common prefixes that contain a / as folders, but the folder does not actually exist. If you're looking to have that visual representation, you can create a zero-length object that ends with a / which is basically equivalent to what the console does if you create a folder via the UI.
Relevant docs can be found here


text:
Q: Probability of 1 and 2 are not among 5 cards chosen from 40 Suppose we have 40 cards numbered 1 through 40 and we want to pick 5 of them the at the same time.
a) Probability of 1 and 2 are not among those 5 cards
b) Probability of at least one of 10,11,12 are among the five
* How about picking cards with replacemnt?

A: (a)If we don't allow $1,2;$ we have to choose $5$ cards from the rest $(40-2)=38$ cards. SO, the required probability = the number favourable case/all the case = $$\frac{\binom {38}5}{\binom {40}5}$$
(b) Similarly, if we don't allow $10,11,12;$ we are left with $40-3=37$ cards.
So, the probability of choosing $5$ cards without $10,11,12$  is $$\frac{\binom {37}5}{\binom {40}5}$$
Hence, the required probability= $$1-\frac{\binom {37}5}{\binom {40}5}$$


text:
Q: Gitlab runner conditional run depending on commit message I have been using Gitlab for a while and now set up a build server. As I change machines (Notebook/PC) I often commit and push to save my work to my gitlab server as the contents are regularly backed up to the cloud.
The build server, works great but the complete project is build on every push. As its quite a big one, I would like to do something like this:

*

*Push commits with comment "release 1.2.3.4"  - >  Gitlab triggers the
build

*All other pushes of commits are ignored by the runner.

It is ok if only the head commit comment ist checked on build.
I searched the .gitlab.yml documentation but could not find anything helpful.

A: Based on your example message "release 1.2.3.4", the best approach is to restrict the build to tagged commits only.
In your exinsting gitlab-ci.yml file, add the "only" attribute to the end of the step you want to restrict.
job1:
  stage: build
script:
- echo "building..."
# - Your commands here
only:
- tags

Now, every time you need to build it, just tag the commit using:
git tag "release 1.2.3.4"

If you really need to see every commit the message you should look in the CI Variables, there's a way to get the current commit hash ref.


text:
Q: Integration Woocommerce with iOS App I am in search of tracking my app, that how many user visited on specific dates and which functions they are mostly visiting.
Some of fellow told me that go with WooCommerce. I'am exploring its docs WooCommer Docs for integration but I'm not able to find anyway in which integration with iOS(Objective-c) mentioned in Doc. So I have few questions.

*

*Is this the right thing which I am looking for my desired
requirement?

*I think this is mostly use for themes like I fount This
App which more likely for themes instead of tracking app.

Looking for help for initiating my task.


text:
Q: How to test a web page from my local machine after it is loaded in my browser I have a website that is running on some server, which is used by a few thousand people. It's built on Java and soy template. I need to test the fronted rendering/js files. Can I do this from my local machine after accessing the web page?
for example: say I need to run a few Javascript test files on facebook.com. I go to facebook.com in my browser, after it is loaded, I need to run a few js files to test it. Is it possible? if yes, should I use Mocha or jest or any other alternate framework?

A: Only you can do is E2E testing. E2E testing is an UI automation testing. Here are the e2e testing framework choices:

*

*puppeteer

*cypress

*casperjs

*protractor
You can use jestjs with puppeteer.

A: There are different test types that can be run against code: Unit, Integration, Functional, etc. Some types have different test methodologies: TDD, BDD, etc. In this instance it seems you are wanting Functional Tests usually using the BDD method. In regard to your post, you state Java but tag the post Javascript and mention the Mocha framework. I'm assuming you meant Javascript instead of Java, with that said Mocha does support Functional Tests:
https://mochajs.org/#retry-tests
You will need the Selenium Driver to be installed along with other specific web browser drivers: Chrome, Edge, Gecko. A quick search shows that there might be an easier path to get up and running:
https://www.npmjs.com/package/mocha-webdriver
I have no experience with that library but leave further investigation up to you.


text:
Q: C# - HTML Agility Pack - Node Collection - Loop table rows, selecting nth-child(2) I'm wokring with htmlAgilityPack, and am grabbing a table from a website.
How can I modify this to return values for each row, every second column only.
public static void SearchAnimal(string param)
        {
            string prm = param;
            string url = "http://xxx/xxx.action?name=";
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url+prm);
            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //StreamReader stream = new StreamReader(response.GetResponseStream());
            //string final_response = stream.ReadToEnd();
            var webGet = new HtmlWeb();
            var doc = webGet.Load(url + prm);

            HtmlNodeCollection tr = doc.DocumentNode.SelectNodes("//table[@id='animal']//tbody//tr//td");

                  for(int i = 0; i <= tr.Count; ++i){
                    var link = tr
                       .Descendants("a")
                       .First(x => x.Attributes["href"] != null);
                    string hrefValue = link.Attributes["href"].Value;
                    string name = link.InnerHtml;
                    Match match = Regex.Match(hrefValue, @"(\d+)$");
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    Console.WriteLine("Result " + tr + ":");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("Animal Name: " + name);
                    Console.WriteLine("Animal Key: " + match.Value);
                    Console.WriteLine("-------------------------");
                    Console.WriteLine("");

                       }

        }

A: You can use XPath position filter to get only 2nd <td> child from each <tr> :
//table[@id='animal']//tbody//tr/td[2]

It is actually equals to CSS :nth-of-type() selector, and shows the same output as :nth-child() only if all children are of the same type (means all children are <td> in this case).


text:
Q: Почему не работает height в %? Почему не работает стиль height: 50% для дочернего элемента ?
И как можно это исправить?

.parent {
  width: 50%;
  max-height: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border: 1px solid #000;

}
.child {
  background: white;
  height: 50%;
  width: 80%;
  margin: auto;
  overflow: auto;
}

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a rem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum book. It has survived not only five centuries, but also the leaularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.aker including versions of Lorem Ipsum.

A: height: 50% Работает, но проблема в том, что вы пытаетесь настроить высоту дочернему элементу, не имея настроенной высоты у родителя (.parent). Поэтому по-умолчанию класс parent принимает автоматическую высоту. Для работы height в % необходимо обозначить height для родительского элемента, например, вот так:

.parent {
  height: 50%;
  width: 50%;
  max-height: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border: 1px solid #000;

}
.child {
  background: white;
  height: 50%;
  width: 90%;
  margin: auto;
  overflow: auto;
  border: 1px solid red;
}

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a rem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum book. It has survived not only five centuries, but also the leaularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.aker including versions of Lorem Ipsum.

A: .parent {
  display: flex;
  align-items: stretch;
}

.child {
  height: auto;
}

Для тех кого интересует 100% почему не срабатывает.


text:
Q: Could a potential well be big and deep enough to cancel out the rest energy of a particle? Here's an example of what I mean. The the ground state of an electron in an atom with $n$ protons is roughly equal to the ground state of an electron in a hydrogen atom, -13.598 eV, times $n^2$. Therefore, a big enough nucleus should make a deep enough potential well to completely cancel out the rest energy of the electron. The potential energy needed to cancel out the mass-energy of an electron is $-m_ec^2$. When you do the math, you get $\sqrt{\frac{-m_e c^2}{-13.598 \space eV}}=193.85$. This means an atom with 194 or more protons should be able to cancel out an electron's rest energy. I'm aware that there may be relativistic effects at play that might make this particular example impossible, but it's a good demonstration of what I mean nevertheless. Would relativistic effects always intervene so that a particle can never lose more potential energy than its rest energy?
Also, if this is possible, does it do anything weird?

A: Suppose we consider a hydrogen atom. We start with an isolated proton and electron far apart from each other so the total mass is $m_p + m_e$. Now we bring the proton and electron together to form the hydrogen atom, and we can get $13.6$ eV of energy out e.g the energy could be emitted as a photon. This is what we mean when we say the binding energy is $13.6$ eV i.e. that energy of the bound system is $13.6$ eV less than the energy of the components. And since we have removed energy from the system the mass has been reduced to $m_p + m_e - 13.6~\textrm{eV}/c^2$. For more on this see Does the mass of an electron change with its "energy state"?
But this $13.6$ eV binding energy is not associated with the electron i.e. we haven't reduced the mass of the electron. We have reduced the mass of the bound system. Nothing has happened to the electron or the proton.
In the example you describe relativistic effects would indeed come into play, but suppose we ignore these and consider a nucleus with a mass $m_N$ and a charge of $+194e$ then if we bind a single electron to the nucleus we would get a bound system with a mass $m_N + m_e - m_e = m_N$ i.e. the mass of the bound system is indeed reduced by the mass of the electron. But this doesn't mean the electron has been somehow cancelled out because the binding energy is a property of the whole system, not of the electron or the nucleus.
So to answer your last question, yes it is possible but sadly it doesn't result in anything weird.
It isn't relevant to your question, but when we include relativity we do indeed get weird effects. It is possible to solve the relativistic equation for a one electron atom (with a point nucleus) and we find that the binding energy starts decreasing for very high nuclear charges and at some point the electron cannot be bound. For a point nucleus this happens for $Z > 119$, though real nuclei are not points and the maximum atomic number is significantly higher than this.

A: This is discussed in Itzykson & Zuber, QFT, p 27. The Schrödinger equation is not applicable and one should use the Dirac equation. I&Z be actually solve the squared Dirac equation. The result is that for the ground state no results are found for a single electron ion with $Z\gt 137 (1/\alpha)$. For a realistic, extended nucleus this limit goes up to above 180. In this limit the electron energy gies to zero, so the binding energy equals the rest mass. Both the kinetic and the potential energy likely diverge
From this point if view the answer is: yes, the potential energy can exceed rhe rest mass. However the total electron energy cannot become negative.

A: You are thinking that the rest mass energy of particles, in your example of the electron, can change.

The length of this 4-vector is the rest energy of the particle. The invariance is associated with the fact that the rest mass is the same in any inertial frame of reference.

The $m_0$ mass of the electron is the same in all frames, an axiomatic assumption in the standard model of particle physics. When discussing quantum mechanical entities and high energy ones one has to use the algebra of the relativistic four vectors.
In nuclear reactions, part of the rest mass of the sum of the four vectors of the interacting nuclei can turn into energy, but this again has to follow relativistic kinematics and cannot be simplistically defined with the concepts of classical forces and potentials.


text:
Q: onBeforeUpdate and onUpdate not triggering on Quasar Vue project I have a simple app with three things:

*

*counter

*button that increases counter

*onBeforeUpdate and onUpdate hooks

VERY IMPORTANT: I tried to replicate this on a pure Vue Vite project and I had NO problem there. The onBeforeUpdate and onUpdate hooks did trigger, so I must be Quasar specific or I must be missing something.
Project:

When I press the increase button the onBeforeUpdate and onUpdate hooks DON'T trigger (they should just do some console.log)
Reproduction URL
https://stackblitz.com/edit/quasarframework-aj9suk?file=src/pages/IndexPage.vue
How to reproduce?

*

*Go to link and wait until the project loads (you see text and btn)

*Open console (F12 or Right click and Inspect)

*Click the button, counter should increase, but the methods won't trigger

Relevant packages:

*

*NodeJs - 16.15.0

*NPM - 8.19.2

*quasar - 2.8.3

*@quasar/app-vite - 1.1.1

*vue - 3.2.39

*vue-router - 4.1.5

Code:
<template>
  <q-page class="flex flex-center">

      Open console, you will see that onBeforeUpdate and onUpdated are not being
      triggered when counter is being changed

{{ counter }}

    <button @click="counter++">Increase</button>
  </q-page>
</template>

A: Since you are rendering your variable inside the q-page component so the hook of the parent component will not be triggered.
Let's consider this example

<template>
  <Test>
    Counter 1: {{ counter1 }}

    Counter 2: {{ counter2 }}

  </Test>

  Counter 1: {{ counter1 }}

  <button @click="counter1++">Increase counter 1</button>
  <button @click="counter2++">Increase counter 2</button>
</template>

<template>

Test component

    <slot></slot>

</template>

When you click on the Increase counter 1 button the hook onUpdated will be triggered in both App.vue and Test.vue.
But when you click on the Increase counter 2 button, the hook onUpdated will be triggered in only the Test.vue component. Because the counter1 variable is rendered inside both App.vue and Test.vue components. And the counter2 variable is rendered only inside the Test.vue components


text:
Q: Do threads interrupt each other in Linux? I'm learning about critical section of multithreading. I have a general statement:

In a single CPU system, disable interrupt is a solution of race condition.

But I also learn from another site that

Threads generally don't interrupt each other.

So how can disable interrupt prevents race condition? Can this possible be explained in terms of Linux?

A: The first statement is true, but it is meaningless on Linux or on any systems. It is because most drivers or hardware handling is done by interrupts and it is impossible do it differently. For example, if a packet arrives from the network, the CPU will know it by an interrupt initiated by the network card.
But these interrupts are invisible for the user space processes, and it doesn't affect them.
Except rare, typically embedded scenarios, no Linux work without interrupt handling.
What can cause race condition, is the context switching, i.e. if the kernel gets away the CPU from a process and gives it to another one. It happens typically by an interrupt from the timer. If only a single process runs, or if the whole scheduler is somehow turned off (maybe it is possible in some embedded environment, but very atypical), then this doesn't happen, and you have a single-process system a'la DOS. It is true, that there is no possibility of a race condition because there is no multitasking.
In a multi-CPU system, if multiple CPUs are concurrently active, there is also the possibility for a race condition, because multiple threads can run concurrently even if there is no scheduler active. Note, also this scenario is very alien to Linux (or to any not embedded OS).

The second sentence, "threads are not interrupting each other" is mainly true. Threads are essentially processes, using the same address space. Multiple threads typically don't interrupt each other. Maybe they could send signals to each other, but that is all. This statement is independent from the previous one.


text:
Q: Dependent random variables converging to a density in mean Let $X$ be an absolutely continuous r.v. with density $f$ which is continuous on $(0,\infty)$. Fix $x>0$ and consider some a.s. decreasing sequence $Y_n$ bounded by $X$ such that $Y_n\searrow 0$ a.s. and such that $\mathbb{P}(x<X\leq x+Y_n)>0$. I stress that all variables are dependent (in a complicated way).
The (initial) question.
I would like to know if the sequence $1_{\{x<X\leq x+Y_n\}}/Y_n$ converges in mean to $f(x)$ (i.e., $\mathbb{E}(1_{\{x<X\leq x+Y_n\}}/Y_n)\to f(x)$) under mild conditions (e.g. $\mathbb{E}(1/Y_n)<\infty$ for all $n$ or $X$ having bounded support).
Special cases. The following examples are not what I am after, but I include them to provide some intuition and perhaps clarity.

*

*The independent case.
When $X$ and $Y_n$ are independent for each $n$, this is trivial. Indeed, the function $g_x:y\mapsto\mathbb{P}(x<X<x+y)/y$ is bounded and continuous on $[0,\infty)$ if we set $g_x(0)=g_x(0+)=f(x)$. Hence
$$\mathbb{E}(1_{\{x<X\leq x+Y_n\}}/Y_n)= \mathbb{E}(\mathbb{E}(1_{\{x<X\leq x+Y_n\}}/Y_n|Y_n))= \mathbb{E}(g_x(Y_n))\to f(x)$$
by the dominated convergence theorem (as $g_x(Y_n)\to f(x)$ a.s.).

*The quotient can be sandwiched. Assume that some random variables $0<L_n$ and $U_n<1$ are independent of $X$ and satisfy $L_n\leq Y_n/X\leq U_n$ for all sufficiently large (deterministic) $n\in\mathbb{N}$ and $U_n/L_n\overset{L^1}{\to} 1$. In this case, we clearly have $U_n,L_n\overset{\mathbb{P}}{\to}0$ and, for sufficiently large $n$
$$1_{\{x<X\leq x/(1-L_n)\}}/(U_nX)\leq
1_{\{x<X\leq x+Y_n\}}/Y_n\leq
1_{\{x<X\leq x/(1-U_n)\}}/(L_nX).$$
Moreover, we may bound
$$\mathbb{E}\left(\frac{1_{\{x<X\leq x/(1-L_n)\}}}{U_nX}\Big|U_n,L_n\right)
\geq \mathbb{E}\left(\frac{1_{\{x<X\leq x/(1-L_n)\}}}{U_nx/(1-L_n)}\Big|U_n,L_n\right)
=g_x\left(\frac{xL_n}{1-L_n}\right)\frac{L_n}{U_n}.$$
Since convergence in $L^1$ implies convergence in distribution, the continuous mapping theorem and the boundedness of $g_x$ imply that the last quantity converges in $L^1$ to $g_x(0)=f(x)$. Similarly, we bound
$$\mathbb{E}\left(\frac{1_{\{x<X\leq x/(1-U_n)\}}}{L_nX}\Big|U_n,L_n\right)
\leq \mathbb{E}\left(\frac{1_{\{x<X\leq x/(1-U_n)\}}}{L_nx}\Big|U_n,L_n\right)
=g_x\left(\frac{xU_n}{1-U_n}\right)\frac{U_n}{L_n}.$$
which again converges in $L^1$ to $g_x(0)=f(x)$. By sandwiching, we conclude that $\mathbb{E}(1_{\{x<X\leq x+Y_n\}}/Y_n)\to g_x(0)=f(x)$.

*Mateusz Kwaśnicki below provided a simple counterexample showing the necessity of some degree of independence between $Y_n$ and $X$.

The dependence between $X$ and $Y_n$ (additional assumptions).

*

*(Motivated by Special cases(3) above) We may additionally assume that, for each $n\in\mathbb{N}$, $(X,Y_n)$ has a joint and continuous density.

*I am particularly interested in the following case. There is a sequence $\{(\theta_n,\xi_n)\}_{n\in\mathbb{N}}$ such that (I) $\theta_n=\prod_{k=1}^n U_k$ for iid $U_k\sim U(0,1)$ (i.e. a stick-breaking process), (II) $\{\xi_n\}_{n\in\mathbb{N}}$ are nonnegative and absolutely continuous with continuous densities and $\sum_{n=1}^\infty \xi_n\in(0,\infty)$ a.s. and (III) conditional on $\theta_{n-1}-\theta_n$, $\xi_n$ is independent of $\{(\theta_{k-1}-\theta_k,\xi_k)\}_{k\neq n}$. Then we define $X=\sum_{k=1}^\infty \xi_k$ and $Y_n=\sum_{k=n}^\infty \xi_k$.
Flexibility of the result.
It is not necessary that this exact result holds (for me). For instance, it would help if we have sufficient (and mild) conditions for:
(I) $\mathbb{E}(1_{\{x<X\leq x+Y_n\}})/\mathbb{E}(Y_n)\to f(x)$ or
(II) $\mathbb{E}[\mathbb{E}(1_{\{x<X\leq x+Y_n\}}|X)/\mathbb{E}(Y_n|X)]\to f(x)$ or something similar. If you have such a result, a reference would be much appreciated. Counterexamples are also welcome.
(Originally asked in math.stackexchange.)

A: If I am not mistaken, your question has a negative answer. Consider $$Y_n = \begin{cases} \tfrac{1}{n} (X - x) & \text{if $X > x$,} \\ \tfrac{1}{n} X & \text{if $X \leqslant x$.} \end{cases} $$ Then $Y_n$ is strictly decreasing, $0 < Y_n < X$, but $x < X < x + Y_n$ never happens: if $X > x$, then $Y_n = \tfrac{1}{n} (X - x)$, and so $$x + Y_n = x + \tfrac{1}{n} (X - x) = \tfrac{1}{n} X + \tfrac{n - 1}{n} x < \tfrac{1}{n} X + \tfrac{n - 1}{n} X = X .$$ The expectation you are interested in is therefore zero, and it does not converge to the density function of $X$ at $x$ (unless the density is zero, of course).


text:
Q: Changing Alpha value on fly for a 3D RGBA texture I am using 3D textures for volume rendering of raw data. The raw data can be Luminance-Alpha or RGBA.
Currently, I read the raw data and set the alpha value such that the furthest row (or slice)would be opaque (Alpha = 1) and the nearest slice would be "transparent" (say alpha = 0.1) and and alpha values are interpolated.
Is there any way in opengl I can change these alpha values dynamically. i.e. based on events like rotation? Such that the furthest slice is always opaque?
I am using a scenegraph tool (www.openrm.org) for texture based volume rendering.
I guess I am not looking for code but any ideas I can do this efficiently in the GPU using OpenGL.

This one talks about "per slice alpha weight", which is what I intend to do (look at the pseudocode in the end)
http://www.ifi.uzh.ch/staff/stern/SciVis_WS2004/chstern/v100105/VolumeRendering/kulick/
Now, the trick is to re-compute per slice alpha weight as orientation changes.

A: Sounds like a perfect job for a shader...
However, if you are using axis aligned slices and create them on the CPU you could set a glColor4f with an alpha-component <= 1.0 and also set glTexEnv to GL_MODULATE. The color value will then be multiplied with the color value of your texture.


text:
Q: broken refreshed image when move crosshair on an imageview I'm try to implement a crosshair item on a imageview using pyqtgraph, it seems ok with the functions.
But, when I zoom in the image and move the crosshair, there are some broken points or lines on the boundary of pixel.
Any suggestions will be much appreciated.
completed code as below, could be run and replicate the problem.
# -*- coding: utf-8 -*-
"""
This example demonstrates the use of ImageView, which is a high-level widget for
displaying and analyzing 2D and 3D data. ImageView provides:

  1. A zoomable region (ViewBox) for displaying the image
  2. A combination histogram and gradient editor (HistogramLUTItem) for
     controlling the visual appearance of the image
  3. A timeline for selecting the currently displayed frame (for 3D data only).
  4. Tools for very basic analysis of image data (see ROI and Norm buttons)

"""
## Add path to library (just for examples; you do not need this)
#import initExample

import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg

from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *

# Interpret image data as row-major instead of col-major
pg.setConfigOptions(imageAxisOrder='row-major')

app = QtGui.QApplication([])

## Create window with ImageView widget
win = QtGui.QMainWindow()
win.resize(800,800)
plt=pg.PlotItem()
imv = pg.ImageView(view=plt)
label = pg.LabelItem(justify='right')
plt.addItem(label)
win.setCentralWidget(imv)
win.show()
win.setWindowTitle('pyqtgraph example: ImageView')

## Create random 3D data set with noisy signals
img = pg.gaussianFilter(np.random.normal(size=(200, 200)), (5, 5)) * 20 + 100
img = img[np.newaxis,:,:]
decay = np.exp(-np.linspace(0,0.3,100))[:,np.newaxis,np.newaxis]
data = np.random.normal(size=(100, 200, 200))
data += img * decay
data += 2

## Add time-varying signal
sig = np.zeros(data.shape[0])
sig[30:] += np.exp(-np.linspace(1,10, 70))
sig[40:] += np.exp(-np.linspace(1,10, 60))
sig[70:] += np.exp(-np.linspace(1,10, 30))

sig = sig[:,np.newaxis,np.newaxis] * 3
data[:,50:60,30:40] += sig

## Display the data and assign each frame a time value from 1.0 to 3.0
imv.setImage(data, xvals=np.linspace(1., 3., data.shape[0]))

## Set a custom color map
colors = [
    (0, 0, 0),
    (45, 5, 61),
    (84, 42, 55),
    (150, 87, 60),
    (208, 171, 141),
    (255, 255, 255)
]
cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors)
imv.setColorMap(cmap)

#cross hair
vLine = pg.InfiniteLine(angle=90, movable=False)
hLine = pg.InfiniteLine(angle=0, movable=False)
plt.addItem(vLine, ignoreBounds=True)
plt.addItem(hLine, ignoreBounds=True)

vb = plt.vb

def mouseMoved(evt):
    pos = evt[0]  ## using signal proxy turns original arguments into a tuple
    if plt.sceneBoundingRect().contains(pos):
        mousePoint = vb.mapSceneToView(pos)
#        index = int(mousePoint.x())
#        if index > 0 and index < len(data):
#            label.setText("x=%0.1f,   y1=%0.1f" % (mousePoint.x(), data[index, index]))
        vLine.setPos(mousePoint.x())
        hLine.setPos(mousePoint.y())

proxy = pg.SignalProxy(plt.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)

## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

I expect the image should be good at anytime, when I move the crosshair.
Thank you.


text:
Q: creating a simple rule engine in java I am exploring different ways to create a simple business rule engine in Java. I need to present the client with a simple webapp that lets him configure a bunch of rules. A sample of rule base might look like this :
Here's example:
 IF (PATIENT_TYPE = "A" AND ADMISSION_TYPE="O")
 SEND TO OUTPATIENT
 ELSE IF PATIENT_TYPE = "B"
 SEND TO INPATIENT

The rule engine is pretty simple, the final action could be just one of two actions, sending to inpatient or outpatient. The operators involved in an expression could be =,>,<,!= and logical operators between expressions are AND, OR and NOT.
I want to build a web application where user will write in a small script in a textarea, and I would evaluate the expression - this way, business rules are explained in simple English and business user has complete control on logic.
From the research I did so far, I came across, ANTLR and writing my own scripting language as possible options to solve this problem. I haven't explore options like Drools rules engine, because I have a feeling that it might be an overkill here. Have you had any experience in solving these kind of problems? If yes, how did you go about it?

A: From past experience, the "plain text" rule based solution is a VERY bad idea, it leaves to much room for error, also, as soon as you have to add multiple rules simple or complex, its going to become a nightmare to code/debug/maintain/modify...
What I did (and it works exceptionally well) is create strict/concrete classes that extend an abstract rule (1 for each type of rule).  Each implementation knows what information it requires and how to process that information to get you desired result.
On the web/front-end side, you will create a component (for each rule implementation) that strictly matches that rule.  You could then give the user the option of what rule they would like to use and update the interface accordingly (by page reload/javascript).
When the rule gets added/modified iterate over all rule implementations to get corresponding implementation and have that implementation parse the raw data (id recommend using json) from the front-end, then execute that rule.
public abstract class AbstractRule{
  public boolean canHandle(JSONObject rawRuleData){
    return StringUtils.equals(getClass().getSimpleName(), rawRuleData.getString("ruleClassName"));
  }
  public abstract void parseRawRuleDataIntoThis(JSONObject rawRuleData); //throw some validation exception
  public abstract RuleResult execute();
}

public class InOutPatientRule extends AbstractRule{
  private String patientType;
  private String admissionType;

  public void parseRawRuleDataIntoThis(JSONObject rawRuleData){
    this.patientType = rawRuleData.getString("patientType");
    this.admissionType= rawRuleData.getString("admissionType");
  }
  public RuleResultInOutPatientType execute(){
    if(StringUtils.equals("A",this.patientType) && StringUtils.equals("O",this.admissionType)){
      return //OUTPATIENT
    }
    return //INPATIENT
  }
}

A: You're setting yourself up for failure for two major reasons:

*

*Parsing free text from the user is HARD.

*Writing parsers in Java is somewhat cumbersome

Solving 1. is either going to push you into the fuzzy domain of NLP, for which you can use a tool like OpenNLP or something from that ecosystem. Because of the large amount of subtly different ways the user can write things down you will find your thinking skew towards a more formal grammar. Making this work will end you up in a DSL type solution, or you'll have to design your own programming language.
I've had reasonable results using Scala parser combinators to parse both natural language and  more formalised grammars. The problems are the same, but the code you have to write to solve them is more readable.
Bottom line, even if you're thinking of a very simple rule language, you're going to find you underestimate the amount of scenario's you have to test for. NeilA is right to advice you to reduce the complexity by creating a proper UI for each type of rule. Don't try to be too generic, or it will blow up in your face.

A: If you're looking for something lighter than drools but with similar functionality you can check http://smartparam.org/ project. It allows storing parameters in properties files as well as in database.

A: Basically... Don't do it
To understand why see:

*

*http://thedailywtf.com/Articles/The_Customer-Friendly_System.aspx

*http://thedailywtf.com/Articles/The-Mythical-Business-Layer.aspx

*http://thedailywtf.com/Articles/Soft_Coding.aspx
I know it looks like a great idea from afar, but the business rules engine will invariably end up being harder to maintain, deploy and debug then the programming language it was written in - don't make up your own programming languages if you can help it.
I've personally been down that road in an ex firm and I've seen where it goes after a couple years (giant undebuggable scripts sitting in a database written in a language that came straight from a parallel dimension where God hates us that in the end never meet 100% of customer expectation because they're not as powerful as a proper programming language and at the same time they're far too convoluted and evil for devs to handle (never mind the client)).
I know there's a certain kind of client that's enamoured with the idea that they won't pay programmer hours for "business rule adaptations" and little understand that they'll be worse off in the end and to attract this kind of client you'll have to make something in this direction - but whatever you do don't invent something of your own.
There's a plethora of decent scripting languages that come with good tools (that don't require compilation, so can be uploaded dynamically etc) out there that can be slickly interfaced and called from Java code and take advantage of your implemented Java apis that you make available, see http://www.slideshare.net/jazzman1980/j-ruby-injavapublic#btnNext for example, Jython possibly too,
and when the client gives up writing these scripts you will be left with the happy duty of maintaining his failed legacy - make sure that that legacy is as painless as it can be.

A: Instead of textArea, provide is as a choice box for fixed state(PATIENT_TYPE) and fixed operators() and you will be done with it.
Anyway you control how web app looks like.

A: A simple rule engine can be build upon closures, i.e in Groovy:
def sendToOutPatient = { ... };

def sendToInPatient = { ... };

def patientRule = { PATIENT_TYPE ->
    {'A': sendToOutPatient,
     'B': sendToInPatient}.get(PATIENT_TYPE)
}

static main(){
    (patientRule('A'))()
}

You could define your rules as closures, reuse/reassign them or even build a DSL over them.
And Groovy can be easily embedded into Java, example:
GroovyShell shell = new GroovyShell(binding);
binding.setVariable("foo", "World");
System.out.println(shell.evaluate("println 'Hello ${foo}!';));

A: This is what I would do. I create a set of regex variables, depending on the matching, I code the business logic. If the rule-set goes complex than this, I would go for apache commons CommandLineParser implementation on the server.
But you can use GUI / HTML and a set of dropdowns and sub dropdowns. That way you can make database queries clearly.

A: There's a rule engine for Clojure called Clara, which can be used from java as well as Clojure[Java]Script. I think it would be quite easy to create something usable from that.

A: Implementing a simple rule-based evaluation system in Java isn't that hard to achieve. Probably the parser for the expression is the most complicated stuff. The example code below uses a couple of patterns to achieve your desired functionality.
A singleton pattern is used to store each available operation in a member map. The operation itself use a command pattern to provide flexible extensibility while the respective action for a valid expression does make use of the dispatching pattern. Last bust not least, a interpreter pattern is used for validating each rule.
An expression like presented in your example above consists of operations, variables and values. In reference to a wiki-example everything that can be declared is an Expression. The interface therefore looks like this:
import java.util.Map;

public interface Expression
{
    public boolean interpret(final Map<String, ?> bindings);
}

While the example on the wiki-page returns an int (they implement a calculator), we only need a boolean return value here to decide if a expression should trigger an action if the expression evaluates to true.
An expression can, as stated above, be either an operation like =, AND, NOT, ... or a Variable or its Value. The definition of a Variable is enlisted below:
import java.util.Map;

public class Variable implements Expression
{
    private String name;

    public Variable(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return this.name;
    }

    @Override
    public boolean interpret(Map<String, ?> bindings)
    {
        return true;
    }
}

Validating a variable name does not make that much sense, therefore true is returned by default. The same holds true for a value of a variable which is kept as generic as possible on defining a BaseType only:
import java.util.Map;

public class BaseType<T> implements Expression
{
    public T value;
    public Class<T> type;

    public BaseType(T value, Class<T> type)
    {
        this.value = value;
        this.type = type;
    }

    public T getValue()
    {
        return this.value;
    }

    public Class<T> getType()
    {
        return this.type;
    }

    @Override
    public boolean interpret(Map<String, ?> bindings)
    {
        return true;
    }

    public static BaseType<?> getBaseType(String string)
    {
        if (string == null)
            throw new IllegalArgumentException("The provided string must not be null");

        if ("true".equals(string) || "false".equals(string))
            return new BaseType<>(Boolean.getBoolean(string), Boolean.class);
        else if (string.startsWith("'"))
            return new BaseType<>(string, String.class);
        else if (string.contains("."))
            return new BaseType<>(Float.parseFloat(string), Float.class);
        else
            return new BaseType<>(Integer.parseInt(string), Integer.class);
    }
}

The BaseType class contains a factory method to generate concrete value types for a specific Java type.
An Operation is now a special expression like AND, NOT, =, ... The abstract base class Operation does define a left and right operand as the operand can refer to more than one expression. F.e. NOT probably only refers to its right-hand expression and negates its validation-result, so true turn into false and vice versa. But AND on the other handside combines a left and right expression logically, forcing both expression to be true on validation.
import java.util.Stack;

public abstract class Operation implements Expression
{
    protected String symbol;

    protected Expression leftOperand = null;
    protected Expression rightOperand = null;

    public Operation(String symbol)
    {
        this.symbol = symbol;
    }

    public abstract Operation copy();

    public String getSymbol()
    {
        return this.symbol;
    }

    public abstract int parse(final String[] tokens, final int pos, final Stack<Expression> stack);

    protected Integer findNextExpression(String[] tokens, int pos, Stack<Expression> stack)
    {
        Operations operations = Operations.INSTANCE;

        for (int i = pos; i < tokens.length; i++)
        {
            Operation op = operations.getOperation(tokens[i]);
            if (op != null)
            {
                op = op.copy();
                // we found an operation
                i = op.parse(tokens, i, stack);

                return i;
            }
        }
        return null;
     }
}

Two operations probably jump into the eye. int parse(String[], int, Stack<Expression>); refactors the logic of parsing the concrete operation to the respective operation-class as it probably knows best what it needs to instantiate a valid operation. Integer findNextExpression(String[], int, stack); is used to find the right hand side of the operation while parsing the string into an expression. It might sound strange to return an int here instead of an expression but the expression is pushed onto the stack and the return value here just returns the position of the last token used by the created expression. So the int value is used to skip already processed tokens.
The AND operation does look like this:
import java.util.Map;
import java.util.Stack;

public class And extends Operation
{
    public And()
    {
        super("AND");
    }

    public And copy()
    {
        return new And();
    }

    @Override
    public int parse(String[] tokens, int pos, Stack<Expression> stack)
    {
        Expression left = stack.pop();
        int i = findNextExpression(tokens, pos+1, stack);
        Expression right = stack.pop();

        this.leftOperand = left;
        this.rightOperand = right;

        stack.push(this);

        return i;
    }

    @Override
    public boolean interpret(Map<String, ?> bindings)
    {
        return leftOperand.interpret(bindings) && rightOperand.interpret(bindings);
    }
}

In parse you probably see that the already generated expression from the left side is taken from the stack, then the right hand side is parsed and again taken from the stack to finally push the new AND operation containing both, the left and right hand expression, back onto the stack.
NOT is similar in that case but only sets the right hand side as described previously:
import java.util.Map;
import java.util.Stack;

public class Not extends Operation
{
    public Not()
    {
        super("NOT");
    }

    public Not copy()
    {
        return new Not();
    }

    @Override
    public int parse(String[] tokens, int pos, Stack<Expression> stack)
    {
        int i = findNextExpression(tokens, pos+1, stack);
        Expression right = stack.pop();

        this.rightOperand = right;
        stack.push(this);

        return i;
    }

    @Override
    public boolean interpret(final Map<String, ?> bindings)
    {
        return !this.rightOperand.interpret(bindings);
    }
}

The = operator is used to check the value of a variable if it actually equals a specific value in the bindings map provided as argument in the interpret method.
import java.util.Map;
import java.util.Stack;

public class Equals extends Operation
{
    public Equals()
    {
        super("=");
    }

    @Override
    public Equals copy()
    {
        return new Equals();
    }

    @Override
    public int parse(final String[] tokens, int pos, Stack<Expression> stack)
    {
        if (pos-1 >= 0 && tokens.length >= pos+1)
        {
            String var = tokens[pos-1];

            this.leftOperand = new Variable(var);
            this.rightOperand = BaseType.getBaseType(tokens[pos+1]);
            stack.push(this);

            return pos+1;
        }
        throw new IllegalArgumentException("Cannot assign value to variable");
    }

    @Override
    public boolean interpret(Map<String, ?> bindings)
    {
        Variable v = (Variable)this.leftOperand;
        Object obj = bindings.get(v.getName());
        if (obj == null)
            return false;

        BaseType<?> type = (BaseType<?>)this.rightOperand;
        if (type.getType().equals(obj.getClass()))
        {
            if (type.getValue().equals(obj))
                return true;
        }
        return false;
    }
}

As can be seen from the parse method a value is assigned to a variable with the variable being on the left side of the = symbol and the value on the right side.
Moreover the interpretation checks for the availability of the variable name in the variable bindings. If it is not available we know that this term can not evaluate to true so we can skip the evaluation process. If it is present, we extract the information from the right hand side (=Value part) and first check if the class type is equal and if so if the actual variable value matches the binding.
As the actual parsing of the expressions is refactored into the operations, the actual parser is rather slim:
import java.util.Stack;

public class ExpressionParser
{
    private static final Operations operations = Operations.INSTANCE;

    public static Expression fromString(String expr)
    {
        Stack<Expression> stack = new Stack<>();

        String[] tokens = expr.split("\\s");
        for (int i=0; i < tokens.length-1; i++)
        {
            Operation op = operations.getOperation(tokens[i]);
            if ( op != null )
            {
                // create a new instance
                op = op.copy();
                i = op.parse(tokens, i, stack);
            }
        }

        return stack.pop();
    }
}

Here the copy method is probably the most interesting thing. As the parsing is rather generic, we do not know in advance which operation is currently processed. On returning a found operation among the registered ones results in a modification of this object. If we only have one operation of that kind in our expression this does not matter - if we however have multiple operations (f.e. two or more equals-operations) the operation is reused and therefore updated with the new value. As this also changes previously created operations of that kind we need to create a new instance of the operation - copy() achieves this.
Operations is a container which holds previously registered operations and maps the operation to a specified symbol:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public enum Operations
{
    /** Application of the Singleton pattern using enum **/
    INSTANCE;

    private final Map<String, Operation> operations = new HashMap<>();

    public void registerOperation(Operation op, String symbol)
    {
        if (!operations.containsKey(symbol))
            operations.put(symbol, op);
    }

    public void registerOperation(Operation op)
    {
        if (!operations.containsKey(op.getSymbol()))
            operations.put(op.getSymbol(), op);
    }

    public Operation getOperation(String symbol)
    {
        return this.operations.get(symbol);
    }

    public Set<String> getDefinedSymbols()
    {
        return this.operations.keySet();
    }
}

Beside the enum singleton pattern nothing really fancy here.
A Rule now contains one or more expressions which on evaluation may trigger a certain action. The rule therefore needs to hold the previously parsed expressions and the action which should be triggered in success case.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Rule
{
    private List<Expression> expressions;
    private ActionDispatcher dispatcher;

    public static class Builder
    {
        private List<Expression> expressions = new ArrayList<>();
        private ActionDispatcher dispatcher = new NullActionDispatcher();

        public Builder withExpression(Expression expr)
        {
            expressions.add(expr);
            return this;
        }

        public Builder withDispatcher(ActionDispatcher dispatcher)
        {
            this.dispatcher = dispatcher;
            return this;
        }

        public Rule build()
        {
            return new Rule(expressions, dispatcher);
        }
    }

    private Rule(List<Expression> expressions, ActionDispatcher dispatcher)
    {
        this.expressions = expressions;
        this.dispatcher = dispatcher;
    }

    public boolean eval(Map<String, ?> bindings)
    {
        boolean eval = false;
        for (Expression expression : expressions)
        {
            eval = expression.interpret(bindings);
            if (eval)
                dispatcher.fire();
        }
        return eval;
    }
}

Here a building pattern is used just to be able to add multiple expression if desired for the same action. Furthermore, the Rule defines a NullActionDispatcher by default. If an expression is evaluated successfully, the dispatcher will trigger a fire() method, which will process the action which should be executed on successful validation. The null pattern is used here to avoid dealing with null values in case no action execution is required as only a true or false validation should be performed. The interface therefore is simple too:
public interface ActionDispatcher
{
    public void fire();
}

As I do not really know what your INPATIENT or OUTPATIENT actions should be, the fire() method only triggers a System.out.println(...); method invocation:
public class InPatientDispatcher implements ActionDispatcher
{
    @Override
    public void fire()
    {
        // send patient to in_patient
        System.out.println("Send patient to IN");
    }
}

Last but not least, a simple main method to test the behavior of the code:
import java.util.HashMap;
import java.util.Map;

public class Main
{
    public static void main( String[] args )
    {
        // create a singleton container for operations
        Operations operations = Operations.INSTANCE;

        // register new operations with the previously created container
        operations.registerOperation(new And());
        operations.registerOperation(new Equals());
        operations.registerOperation(new Not());

        // defines the triggers when a rule should fire
        Expression ex3 = ExpressionParser.fromString("PATIENT_TYPE = 'A' AND NOT ADMISSION_TYPE = 'O'");
        Expression ex1 = ExpressionParser.fromString("PATIENT_TYPE = 'A' AND ADMISSION_TYPE = 'O'");
        Expression ex2 = ExpressionParser.fromString("PATIENT_TYPE = 'B'");

        // define the possible actions for rules that fire
        ActionDispatcher inPatient = new InPatientDispatcher();
        ActionDispatcher outPatient = new OutPatientDispatcher();

        // create the rules and link them to the accoridng expression and action
        Rule rule1 = new Rule.Builder()
                            .withExpression(ex1)
                            .withDispatcher(outPatient)
                            .build();

        Rule rule2 = new Rule.Builder()
                            .withExpression(ex2)
                            .withExpression(ex3)
                            .withDispatcher(inPatient)
                            .build();

        // add all rules to a single container
        Rules rules = new Rules();
        rules.addRule(rule1);
        rules.addRule(rule2);

        // for test purpose define a variable binding ...
        Map<String, String> bindings = new HashMap<>();
        bindings.put("PATIENT_TYPE", "'A'");
        bindings.put("ADMISSION_TYPE", "'O'");
        // ... and evaluate the defined rules with the specified bindings
        boolean triggered = rules.eval(bindings);
        System.out.println("Action triggered: "+triggered);
    }
}

Rules here is just a simple container class for rules and propagates the eval(bindings); invocation to each defined rule.
I do not include other operations as the post here is already way to long, but it should not be too hard to implement them on your own if you desire so. I furthermore did not include my package structure as you probably will use your own one. Furhtermore, I didn't include any exception handling, I leave that to everyone who is going to copy & paste the code :)
One might argue that the parsing should obviously happen in the parser instead of the concrete classes. I'm aware of that, but on the other hand on adding new operations you have to modify the parser as well as the new operation instead of only having to touch one single class.
Instead of using a rule based system a petri net or even a BPMN in combination with the open source Activiti Engine would be possible to achieve this task. Here the operations are already defined within the language, you only need to define the concrete statements as tasks which can be executed automatically - and depending on the outcome of a task (i.e. the single statement) it will proceed its way through the "graph". The modeling therefore is usually done in a graphical editor or frontend to avoid dealing with the XML nature of the BPMN language.

A: I would suggest using something like Drools. Creating your own custom solution would be an overkill because you would  have to debug it, and still provide functionality certainly less than the one provided by a rule engine like Drools. I understand that Drools has a learning curve, but I would not compare it with creating a custom language, or a custom solution...
In my opinion, in order for a user to write rules, he/she would have to learn something. While I suppose you could provide for a language simpler than the drools rule language, you would never capture all of his/her needs. Drools rule language would be simple enough for  simple rules. Plus, you could provide him/her with a well formed documentation. If you plan to control the rules created by the end user and applied on the system, then perhaps it would be wiser to create a gui that would form the rules applied on drools.
Hope I helped!

A: Have a good talk with your users, asking them why this needs to be configurable, and what changes in the configuration they expect to be coming up. Find out what upcoming changes are certain, likely, remotely possible, outrageously unlikely. And how quickly they'd need to be implemented. For each change, would writing a small update release be acceptable or not?
With this amount of flexibility needed in mind, evaluate the option of rolling your own solution against that of incorporating a full engine. "Test" your simple solution against the upcoming change scenarios by briefly writing down how each change would be implemented. It is quite okay if some unlikely scenarios have big cost. If likely scenarios are costly too, however, you had better pick a more generic solution.
As for the options to consider, I like both drools and the suggestion to write your own. A third option: When implementing a financial registration package with yearly legal updates, we've had quite good success implementing the rules in code but leaving their settings configurable in sql tables. So in your case that might mean a table something like this:
patient_type | admission_type | inpatient_or_outpatient
-------------------------------------------------------
'A'          | 'O'            | 'Outpatient'
'B'          | NULL           | 'Inpatient'

(Our tables tend to have date-from and date-to validity columns which allow the user to stage changes)
If you end up writing a DSL, take a look at http://martinfowler.com/books/dsl.html which offers thorough descriptions of the several approaches.
As a caveat: in his Q and A section Martin Fowler writes:

So is this the hook - business people write the rules themselves?
In general I don't think so. It's a lot of work to make an environment
  that allows business people to write their own rules. You have to make
  a comfortable editing tool, debugging tools, testing tools, and so on.
  You get most of the benefit of business facing DSLs by doing enough to
  allow business people to be able to read the rules. They can then
  review them for accuracy, talk about them with the developers and
  draft changes for developers to implement properly. Getting DSLs to be
  business readable is far less effort than business writable, but
  yields most of the benefits. There are times where it's worth making
  the effort to make the DSLs business-writable, but it's a more
  advanced goal.

A: As parsing code with Java only is an implementation suicide, you may want to write a simple compiler using Jflex and CUP, which are the Java version of GNU FLEX and YACC. In this way you can generate simple tokens with Jflex (a token is a keyword like IF, ELSE etc) while CUP will consume those token in order to execute some code.

A: Implementing a rule engine is not trivial. A meaningful rule based system has an inference engine that supports both forward chaining and backward chaining, as well as breadth first and depth first search strategies. Easy Rules has none of this, it just executes all rules once and only once. Drools supports forward- and backward chaining, and afaik also supports depth first and breadth first. It's explained here.
From my experience, Drools is the only meaningful Rule Engine for java. It does have its limitations. I must say, I have used Drools 5+ years ago.

A: Another addition to this list is http://openl-tablets.org/ . It allows you to define rules in Excel, upload it to a Web based editor. It is very flexible and has built in ability to run tests against the rules with some data


text:
Q: Executing document element clicks in order in JavaScript I have bunch of document element clicks in my JavaScript code. Something like this:
document.getElementsByClassName("button1")[0].click();
document.getElementsByClassName("button2")[0].click();
document.getElementsByClassName("button3")[0].click();
document.getElementsByClassName("button4")[0].click();

But they don't execute in order. I want every next to wait for every previous button click complete. I couldn't pass callback to those click functions. Is there any way? I'm quite new to JavaScript ecosystem.
Thanks.


text:
Q: Why does $\int_a^b f(x)h'(x) \, \mathrm{d}x=0$ imply that $f$ is constant? As an assignment, I have to prove the following:

If $f(x)$ is a piecewise continuous function and $\int_a^b f(x)h'(x) \, \mathrm{d}x=0$ for all piecewise continuously differentiable $h(x)$ that satisfy $h(a)=h(b)=0$, then $f$ is constant on $[a,b]$.

The assignment also provides some hints:

Define $$c:=\frac{1}{b-a} \int_a^b f(x) \, \mathrm{d}x=\frac{1}{b-a} \sum_{i=1}^{m} \left ( \int_{x_{I-1}}^{x_i} f(x) \, \mathrm{d}x \right )$$ and use $$h(x)=\int_a^x f(s)-c \, \mathrm{d}s$$ Show that $$\int_a^b \left ( f(x)-c \right )h'(x) \, \mathrm{d}x=0$$ as well as $$\int_a^b \left ( f(x)-c \right )h'(x) \, \mathrm{d}x = \int_a^b \left ( f(x)-c \right )^2 \, \mathrm{d}x$$ and use this to conclude that $f(x)-c=0$ for all $x \in [a,b]$.

Now, from what I understand, $h(b)=0$:
$$h(x)=\int_a^b f(s)-c \, \mathrm{d}s=\int_a^b f(s) \, \mathrm{d}s-\left . cs \right |_{s=a}^b=(b-a)c-(cb-ca)=0$$
Obviously, $h(a)=0$ too.
What I don't understand, is how I'm supposed to manipulate $\int_a^b \left ( f(x)-c \right )h'(x) \, \mathrm{d}x$ to obtain $\int_a^b \left ( f(x)-c \right )^2 \, \mathrm{d}x$. I've tried numerous things (including integration by parts, which looks promising), but to no avail.

A: Seems to me like a step to prove later the Euler-Lagrange equation in the calculus of variation.
Now let us assume
$\int_a^b f(x)h'(x) \, \mathrm{d}x=0$ for all piecewise continuously differentiable $h(x)$ that satisfy $h(a)=h(b)=0$
We now choose a special $h$ (having the properties above) to show that $f$ must be a constant and set
$$h(x)=\int_a^x f(s)-c \, \mathrm{d}s$$
Let us first show that $h(a) =0$. This is trivial. Then let us show that $h(b)=0$ :
$$h(b)=\int_a^b f(s)-c \, \mathrm{d}s=\int_a^b f(s) \, \mathrm{d}s-\left . cs \right |_{s=a}^b=\int_a^bf(s)ds-(b-a)c=\\
\int_a^bf(s)ds-\int_a^bf(s)ds=0$$
Now let us show that $\int_a^b (f(x)-c)^2 dx =0$:
$$\int_a^b (f(x)-c)^2 dx =\int_a^b (f(x)-c)h'(x) dx =\\
 \int_a^b f(x)h'(x) dx + \int_a^b -ch'(x) dx = \\
\int_a^b f(x)h'(x) dx -c (h(b)-h(a))$$
But we know from our assumption $\int_a^b f(x)h'(x) \, \mathrm{d}x=0$, so the first term vanishes and as $h(a)=h(b)=0$ so does the second term.
This results in
$$\int_a^b (f(x)-c)^2 dx =0$$
As the integral of a nonnegative function is zero then the function $(f(x)-c)^2$ must be zero a.e as well, we have $f(x)=c \qquad x\in[a,b]$

A: First of all, assuming that $f$ has only a finite number of discontinuities, and noting that the integral is unaffected if we delete these points from $[a,b],$ we may assume without loss of generality that $f$ is continuous on all of $[a,b]$.
The second fact we will use is the following: if $f>0$ is continuous on $[a,b]$, and if $\int^b_a f(x)dx=0,$ then $f=0$ on $[a,b].$ To prove this, suppose it is false. Then there is an $x_0\in [a,b]$ such that $f(x_0)=\delta >0,$ and now the continuity of $f$ gives us a neighborhood $a<a'<x_0<b'<b$ such that $f(x)<\delta/2$ on $(a',b')$. This implies that $\int^b_a f(x)dx\ge \int^{b'}_{a'}f(x)dx\ge \frac{\delta (b'-a')}{2}>0$ which is a contradiction.
Now, if we define $h(x)=\int^x_a (f(s)-c)ds$ where $c$ is as in the hint, then $h'(x)=f(x)-c$ and a direct substitution shows that $\int^b_a (f(x)-c)^2dx=0,$ and so by what we just proved, $(f(x)-c)^2=0$ and thus $f(x)=c$.


text:
Q: Django DRF - Sending email with html template - html template appears as plain text I'm trying to send emails from django using a html template. It does send the email but the html is sent as plain text. How can I make the email appear as html to the receiver?
I'm using Django 4.0
views.py
# import file with html content
html_version = 'activate_email.html'
html_message = render_to_string(html_version, {'context': context })

email = EmailMessage(
    'Website email verification',
    html_message,
    'info@example.co',
    [user.email],
)
email.send()

activate_email.html
{% autoescape off %}

Test

{% endautoescape %}

A: you can use the content_subtype attribute on the EmailMessage class to change the main content.
email = EmailMessage(
    'Website email verification',
    html_message,
    'info@example.co',
    [user.email],
)
email.content_subtype = "html"  # Main content is now text/html
email.send()


text:
Q: word or phrase for "positive comments" or "positive review" I am looking for a work that almost means "positive comments" or "positive review". It should be subtle, so it cannot be very explicit that the review is positive. Simply hint it.
Some examples where this word or phrase would be used:

The movie critic gave the actor 'positive comments'.
The journal editor gave the authors 'positive comments'.

The sentence I actually want to compose is the following:

The most recent, positive comments from the referee are included in this letter.

but it's too obvious that I'm emphasizing the word positive. I would like it to be more subtle.

A: I think that the word "kind" can be of help here.
Kind comments... kind reviews etc., will be somewhat more subtle and may hint at the desired action on their part ;)
Hope that helps!

A: It's very difficult to come up with something that doesn't explicitly mean positive, but one way of doing so would be to use the word encouragement:

[Merriam-Webster]
: the act of encouraging : the state of being encouraged
encouraging
: giving hope or promise

In short:

The movie critic gave the actor encouragement.

While it's not made explicit if the comments are positive per se in terms of the actual performance, the overall tenor of the piece (and subtle implication) is that the critic sees, based on the performance (even if it was poor in context), positive things happening to the actor in the future.

A: We British do it all the time.  One such phrase is not bad.  Any

Ok, you bought all the papers:  what are the reviews of your performance like?
Not too bad.

Any Brit will understand that this actually means "pretty good"

A: Favorable might serve your purposes, either as "a favorable review," or as an adverb, "favorably reviewed."  In your case, "favorable comments."
favorable, adj.
https://www.dictionary.com/browse/favorable

characterized by approval or support; positive: a favorable report.
  creating or winning favor; pleasing: to make a favorable impression.
  affording advantage, opportunity, or convenience; advantageous: a
  favorable position. (of an answer) granting what is desired. boding
  well; propitious: The signs are favorable for a new start.

For example:  The paper was favorably received; or Comments on the paper were favorable.
Another term that's used in a general way is "well-received."  Academics sometimes speak of a book that got poor reviews as "not well-received" or "not favorably received."

A: It's quite simple:
Praise

The movie critic gave the actor praise

From Chambers:

The expression of admiration or approval

OK, it's perhaps not nuanced enough for the example, but it works in US English, where good means poor and great means tolerable.
For British English, I think you need to use what is effectively a double negative construction to get the idea of faint praise. Something like

The most recent, not disfavourable, comments from the referee are included in this letter.


text:
Q: Litebox plugin does not work I have been trying to create a gallery using the litebox plugin for popup effects. The website is an aspx website with a single master page.
Links in the master page:

<link href="assets/litebox/css/litebox.css" rel="stylesheet" type="text/css" />
<link href="assets/litebox/css/litebox.css" rel="stylesheet" type="text/css" />
<link href="assets/litebox/css/normalize.css" rel="stylesheet" type="text/css" />

Popup images:

A: Try
HTML

Javascript


text:
Q: Efficiency of SQL scalar function I have a three-database application (none developed by me) in which many phone numbers are stored, but their format is inconsistent (555-5555, (555) 555-5555, 5555555555, 5555555, etc.) On the web side, I want them always to be displayed like 555-555-5555. I've written a scalar function to clean them up, but it's going to be called OFTEN and I'm worried about its efficiency.
Can you have a look and please advise me if there's a better way.
ALTER FUNCTION [dbo].[FormatPhone]
(
  @p AS VARCHAR(20)
) RETURNS VARCHAR(12) AS

BEGIN
DECLARE @ret AS VARCHAR(12) = ''
DECLARE @c AS CHAR
DECLARE @i AS INT
DECLARE @stop AS INT

-- loop to grab only digits from @p
SET @i = 1
SET @stop = LEN(@p)
WHILE @i <= @stop
BEGIN
    SET @c = SUBSTRING(@p, @i, 1)
    IF @c >= '0' AND @c <= '9' SET @ret = @ret + @c
    SET @i = @i + 1
END
IF LEN(@ret) = 7 SET @ret = '204' + @ret -- account for forgotten area code

SET @ret = LEFT(@ret, 3) + '-' + SUBSTRING(@ret, 4, 3) + '-' + RIGHT(@ret, 4)

RETURN @ret

Thanks!
Nick.

A: What you are talking about is data cleansing. In my experience (I had a 6 month project with a Russian business unit that consisted about 90% of bashing my head against the wall on the issue of phone number formats) this is a total pain.
My advice on this is to do it once and do it properly; then put the systems in place to prevent dirty data from entering the system in the future.
What we ended up doing was getting a few girls from the admin office to do it by hand! The problem is that if you do it wrong you make the data useless. Have a go at automated parsing and see where it gets you, but sometimes man beats machine.

A: *

*Replace all haracters except numbers

*Convert into sample XXX-XXX-XXXX

Use SUBSTRING, REPLACE T-SQL

A: This function looks at the number/string to determine the size and format, with-out looping
CREATE Function [dbo].[FormatPhone] (@PD varchar(50))
RETURNS Varchar(50)
As
Begin

Declare @F1 As tinyint
Declare @F2 As tinyint
Declare @F3 As tinyint
Declare @F4 As tinyint
Declare @F5 As tinyint
Declare @F6 As tinyint

Declare @NPD As Varchar(50)

Declare @PDLen As tinyint

--Trim any space off the ends
SET @PD = RTRIM(LTRIM(@PD))

--Default just return the data, unless in proper foramt
SET @NPD = @PD

--Check for phone number that all ready has formatting,
--we are only going to format a 'Pure' set of numbers.
--Check for formating, space
SET @F1 = CHARINDEX('(', @PD)
SET @F2 = CHARINDEX(')', @PD)
SET @F3 = CHARINDEX('-', @PD)
SET @F4 = CHARINDEX('.', @PD)
SET @F5 = CHARINDEX(' ', @PD)
SET @F6 = @F1 +@F2 + @F3 + @F4 + @F5

IF @F6 = 0
--No formating, figure out the lenght
BEGIN
SET @PDLen = LEN(@PD)

    IF @PDLen = 10  SET @NPD = '('+SUBSTRING(@PD, 1, 3)+') '+SUBSTRING(@PD, 4, 3)+'-'+SUBSTRING(@PD, 7, 4)
    IF @PDLen = 11 AND SUBSTRING(@PD, 1, 1) = '1'  SET @NPD = '('+SUBSTRING(@PD, 2, 3)+') '+SUBSTRING(@PD, 5, 3)+'-'+SUBSTRING(@PD, 8, 4)
    IF @PDLen = 7  SET @NPD = '(   ) '+SUBSTRING(@PD, 1, 3)+'-'+SUBSTRING(@PD, 4, 4)

END

RETURN @NPD

END


text:
Q: DAX: Issues Calculating a Sum with Multiple Filters I thought I'd reach out for help as I'm having troubles creating a calculated measure in PowerBI. I'm trying to calculate the sum of multiple accounts using filters to grab the correct accounts.
Here is the measure that isn't working:
Measure =
CALCULATE (
    SUM ( 'Queryx'[Amount] ),
    FILTER (
        Queryx,
        LEFT ( 'Queryx'[Accnt], 4 )
            IN { "8980", "8981", "8982", "8983", "8987", "8988", "8989" }
    ),
    FILTER ( 'Queryx', [Accnt] IN { "89660", "89700", "89850" } ),
    FILTER ( 'Queryx', LEFT ( 'Queryx'[Accnt], 3 ) IN { "899" } )
)

If I run the measure with only 1 filter the measure works, but the addition of the other 2 filters throws a wrench in the system. Any idea how I could get this to run? Or is there a smarter way to go about creating this measure?
Thanks for taking the time to read this and I greatly appreciate any help =)

A: The filters are all applied using AND logic. I suspect you want to use OR logic since it's not possible to satisfy all those conditions at once.
Try something more like this:
Measure =
CALCULATE (
    SUM ( 'Queryx'[Amount] ),
    FILTER (
        Queryx,
        LEFT ( 'Queryx'[Accnt], 4 )
            IN { "8980", "8981", "8982", "8983", "8987", "8988", "8989" }
          || [Accnt] IN { "89660", "89700", "89850" } ),
          || LEFT ( 'Queryx'[Accnt], 3 ) IN { "899" } )
    )
)

The || is the logical OR syntax.


text:
Q: Getting Windows hardware information from cmd or powershell How can I determine if a mic, webcam, and speaker are installed onto a Windows device using Powershell or cmd? I don't need to manipulate these devices, just need to determine if they are present.

A: The Get-PnpDevice command is probably what you're looking for.


text:
Q: Carousel with Jquery I am struggling to understand how to implement a simple carousel. I've tried the append()/prepend() functions but can't seem to get it to operate how I would like.
The setup I am using:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
  <title>First Step Connections - Online Media Marketing</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;900&display=swap" rel="stylesheet">

 <

    How was lunch today?

 Justin Harris

 Houston, TX

    Football is the best sport!

 Justin Harris

 Houston, TX

    Meeting at 12pm.

 Justin Harris

 Houston, TX

    The weather outside is gorgeous.

 Justin Harris

 Houston, TX

    Susan can you call Jim?

 Justin Harris

 Houston, TX

 >

Basically I have a carousel container, and within the carousel container I have a testimonial container with x amount of testimonial divs.
The css seems okay in that I hid the overflow of carousel container, and removed white-space wrapping on the testimonial container. So everything appears fine.. I just need help with the logic of how I would endlessly be able to scroll through the x amount of divs.
So when I get to the last testimonial it continues fluidly to the first.
Here is my css incase you need it:
:root {
  --main-red-color: #e11a2c;
  --main-blue-color: #013e7b;
  --main-green-color: #8dc63f;

}

* {
  color:var(--main-blue-color);
  box-sizing:border-box;
  font-family:"Lato", sans-serif;
}

#testimonial-carousel-container {
  width:70%;
  margin: auto;
  position:relative;
}

#testimonial-carousel {
  margin: auto;
  background-color:var(--main-blue-color);
  position:relative;
  overflow:hidden;
}

#testimonial-container {
  white-space:nowrap;
  width:100%;
  position:relative;
}

.speech-bubble {
  border-radius:5px;
  background-color:var(--main-green-color);
  width:auto;
  display:inline-block;
  padding:20px;
  text-align:center;
  position:relative;
}

.speech-bubble .arrow {
  border-style: solid;
  position:absolute;
}

.bottom {
  border-color: var(--main-green-color) transparent transparent transparent;
  border-width:8px 8px 0 8px;
  bottom:-8px;
}

#testimonial {
  padding:10px 5px 5px 5px;
  height:200px;
  background-color:var(--main-red-color);
  position:relative;
  display:inline-grid;
  opacity:.4;
}

#testimonial img {
  width:40px;
  height:40px;
  border-radius:50%;
  margin-top:13px;
}

#testimonial span {
  color:#fff;
  font-weight:900;
}

#btn-prev, #btn-next {
  position:absolute;
  background-color:var(--main-red-color);
  color:#fff;
  height:40px;
  width:40px;
  z-index:5;
  border:3px solid #fff;
  text-align:center;
  line-height:40px;
  font-weight:900;
  margin-top:-20px;
}

#btn-prev:hover, #btn-next:hover {
  background-color:var(--main-blue-color);
}

#btn-prev {
  top:50%;
  left:-40px;
}

#btn-next {
  top:50%;
  right:-40px;
}

As for the Jquery scripting I am drawing blanks. If you could provide some help as to the logic for completing this I would greatly appreciate it. Is append() prepend() the only way to go?
You can view the demo at:
http://firststepconnections.com/carousel/


text:
Q: Handlebars usage in Bootstrap based template - how to iterate over many ul and lis I'm using Bootstrap to build my website, which is showing results based on jSON API call to youtube's API. Imagine a grid of youtube video clips with their thumbnails only, when you click one of them, it opens modal with player for this video.
That's nice, and I am trying to implement it with the help of handlebars.
I'm stuck because I can't just iterate with {{each}} on the results that I get from youtube, because for displaying them I (and this is because of Bootstrap) I need to add separate

for every 4

s.

I need to produce this

 ...

 ...

 ...

 ...

then again new

 with 4
s inside

 ...

 ...

 ...

 ...

For Now in one single

I am able to do 4

with the usage of handlebars,
but this is if I get only four results from youtube, but if I get let's say 16 results, how I can tell Handlebars to put

for every 4

s

That's my question.
Here is my current template inside one UL

A: First of all, don't do this:

That's a bad habit that often leads to "where did my template go?" questions when you $('ul').html('') to reset things. You're better off keeping your template


text:
Q: Packages have unmet dependencies, why? I get this error while trying to install a package as follows:
sudo add-apt-repository ppa:v-launchpad-jochen-sprickerhof-de/pcl
sudo apt-get update
sudo apt-get install libpcl-all

The first two don't issue any error message, but the last one gives:
The following packages have unmet dependencies:  libpcl-all : Depends: libpcl-
1.3-all but it is not going to be installed E: Unable to correct problems, you have
held broken packages.

How is that even possible? If package xxx depends on package yyy, why isn't yyy installed then? Usually, when you run apt-get install xxx it will automatically install all packages xxx depends on. What may prevent it from doing so?
but it is not going to be installed

well why isn't it?


text:
Q: Javascript Аналог игры Угадай слово Я только изучаю язык.
Подскажите как правильно реализовать чтоб при угадывании буквы ( при вводе с клавиатуры) в слове угадывание начиналось с первой буквы и при правильном вводе переходило дальше к следующей.
Во всех аналогичных примерах ( в интернете искал)  буквы вводятся там где находит угаданную букву. А мне нужно чтоб начинало с первой.
Хотя бы подскажите куда смотреть.
Спасибо.
Вот код скрипта:
const word = ['wrinkles','wrinkle it','wrink it lost'];

 var randNum = Math.floor(Math.random() * word.length);
 var choosenWord = word[randNum];
 var underScore = [];
 var rightWord = [];
 var wrongWord = [];

 var docUnderScore = document.getElementsByClassName("underscores");

 var generateUnderscore = () => {
    for(var i = 0; i < choosenWord.length; i++) {

         if(choosenWord[i] === ' '){
             underScore.push( ' ' );
        } else {
             underScore.push( '_' );

        }
    }
    return underScore;
 }

 document.addEventListener('keypress', (event) => {

   var keyword = String.fromCharCode(event.keyCode);

  if(choosenWord.indexOf(keyword) > -1) {

        rightWord.push(keyword);

        underScore[choosenWord.indexOf(keyword)] = keyword;

         docUnderScore[0].innerHTML = underScore.join('');

        console.log(underScore[choosenWord.indexOf(keyword)] = keyword);

    } else {

        wrongWord.push(keyword);

    }
 });

 docUnderScore[0].innerHTML = generateUnderscore().join('');

HTML
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0">

    <title>Words</title>

Guess


text:
Q: Allow use of screen without ability to detach sessions I'm wondering if this is possible. I'd like users to be able to launch screen on some of our hosts for the purpose of multiplexing their terminal login sessions. However, I don't want them to be able to detach the screen and leave it running in the background.
The reason for this being that the only way to log in to these machines is through a cluster job submission system, so if a screen becomes detached and the user logs off the only way to get back would be if they happened to land back on the same node on their next job submissions.

A: You can do a 'soft' disable of detaching by putting
bind d

in .screenrc, which removes the default ^A D keybinding for detach.  Or maybe
bind d echo Don't detach screens, it won't work because of the cluster.

Doing a hard disable of detach, including the command line forms, would take forking your own version of screen and coding out the capability.  Which, y'know, can be done, it being an open source project and all.

A: Here is a hack you could put into a bash script and run every minute with cron to kill detached sessions.  Not the cleanest solution though :-P
screen -S $(screen -ls | grep Detached | awk '{ print $1}') -X kill

A: echo autodetach off >> ~/.screenrc

Read the screen manpage for autodetach.  This will make sure it simply kills everything if their connection is disabled.
You'll still want the other solutions mentioned...

A: They'll always be able to just disconnect without closing their terminal(s), unless you hack auto-kill into screen of course.

A: Since detaching screen leaves the user logged in, you could add into the login script a check to see which server the user is already logged in to.  This would be more work than just disabling detach, but would be far more useful to your users.
An idea for the script: iterate through the servers, greping the outpot of who, and then logging the user in to the server that reports them logged in first; otherwise, log them in as they would be now (to handle when a user logs out cleanly).


text:
Q: Select a feature in a layer group in QGIS by coordinates I have the following layers inside a layer group 'Parcels'

I have created a Plugin that will determine a coordinate (Coordx,Coordy) based on a user input and then pan/zoom the map to the coordinate (Note: Coordx and Coordy are Qstrings). What I want it to do is select a feature that contains the coordinate and zoom/pan to the extent of that feature.  The feature could be in any of the 12 vector layers shown in the picture.  If there is no feature that contains the coordinate in any of the layers, then the plugin will zoom/pan to the coordinate instead at some predetermined extent based on the variable 'scale'. I have included the code for the pan/zoom function for reference
            # Create new extent rectangle
        rect = QgsRectangle(
          float(Coordx) - scale,
          float(Coordy) - scale,
          float(Coordx) + scale,
          float(Coordy) + scale)
        mc=self.iface.mapCanvas()
        # Set the extent to our new rectangle
        mc.setExtent(rect)
        # Refresh the map
        mc.refresh()

A: I would iterate over a list of layers using a filter. This assumes everything is in the same CRS.
# create a rectangle to sort features by. Qgis will find overlapping features
# it's ok that xmin & xmax are the same and ymin & ymax are the same.
# typecast to float may be unnecessary
filterRect = QgsRectangle(float(Coordx),float(Coordy),float(Coordx),float(Coordy))

projectRoot = QgsProject.instance().layerTreeRoot()
parcelGroup = projectRoot.findGroup("Parcels") # replace with actual group name

featFound = False

for lyr in parcelGroup.findLayers():
    try:
        # get feature iterator and select first one that overlaps
        featFound = lyr.layer().getFeatures(QgsFeatureRequest(filterRect)).next()
        lyr.layer().select(featFound.id())

    except StopIteration:
        # if none do just move on
        pass

if featFound: # will still be false if no feature was found
    mapExtentRect = featFound.geometry().boundingBox()
else:
    mapExtentRect = QgsRectangle(
        float(Coordx) - scale,
        float(Coordy) - scale,
        float(Coordx) + scale,
        float(Coordy) + scale)

mc=self.iface.mapCanvas()
# Set the extent to our new rectangle
mc.setExtent(mapExtentRect)
# Refresh the map
mc.refresh()

if for any reason you want to manually define a list of layers to search instead of using a group you can create a list of the layers by name:
searchLayers = ['layer1','layer2','layer3'...]
for layerName in searchLayers:
    layer = QgsMapLayerRegistry.instance().mapLayersByName( layerName )[0]
    # will return a list of layers matching name so select the first ([0])
    ...


text:
Q: "Hatching" or "hatch" to designate "a pattern of fine lines, used for shading" I am currently taking a look at some presentations my company made on several features of our software, and I came across several sentences saying that "the software shows a red/blue/whatever color hatch to indicate something", meaning that the software shows a pattern of fine lines.
Simply judging by intuition, this sounded not quite right for me; my impression was that:

*

*the word "hatching" was the most common noun to describe such a pattern;

*"hatch" on the other side could be used as an adjective ("hatch pattern"), but was generally not common as a noun that designates such a pattern.

A quick research on merriam-webster shows that "hatching" indeed means "the engraving or drawing of fine lines in close proximity especially to give an effect of shading; also : the pattern so made". But the entry for "hatch" shows, among other definitions, the meaning of "an instance of hatching" or "line; especially : one used to give the effect of shading".
So my question is: is either "hatching" or "hatch" preferable as a designation for "a pattern of fine lines used for shading", or are they completely interchangeable? Is it common to speak of "a hatch" when meaning such a pattern?

A: A simple search will answer your question

What Is Hatching?

Your word

Hatch

is not used in this way to describe a pattern, however

Hatch Pattern

is.


text:
Q: Could not load file or assembly System.ComponentModel.Annotations. The system cannot find the file specified I am using assembly binding, but I still get this error:
Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified
Here is my code:
  <dependentAssembly>
    <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
  </dependentAssembly>

Here are more details on the error:
=== Pre-bind state information ===
LOG: DisplayName = System.ComponentModel.Annotations, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///C://Source/Workspaces/CQB/Development/Dev-branch/Azure/CloudService1/csx/Debug/roles/CQB.TaskRole2/approot
LOG: Initial PrivatePath = C:\Users\Source\Workspaces\CQB\Development\Dev-branch\Azure\CloudService1\csx\Debug\roles\CQB.TaskRole2\approot
Calling assembly : Square.Connect, Version=2.25.0.0, Culture=neutral, PublicKeyToken=null.
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\Source\Workspaces\CQB\Development\Dev-branch\Azure\CloudService1\csx\Debug\roles\CQB.TaskRole2\approot\CQB.TaskRole2.dll.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.2.0.0 redirected to 4.2.1.0.
LOG: Post-policy reference: System.ComponentModel.Annotations, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
LOG: Attempting download of new URL file:///C://Source/Workspaces/CQB/Development/Dev-branch/Azure/CloudService1/csx/Debug/roles/CQB.TaskRole2/approot/System.ComponentModel.Annotations.DLL.
LOG: Attempting download of new URL file:///C://Source/Workspaces/CQB/Development/Dev-branch/Azure/CloudService1/csx/Debug/roles/CQB.TaskRole2/approot/System.ComponentModel.Annotations/System.ComponentModel.Annotations.DLL.
LOG: Attempting download of new URL file:///C://Source/Workspaces/CQB/Development/Dev-branch/Azure/CloudService1/csx/Debug/roles/CQB.TaskRole2/approot/System.ComponentModel.Annotations.EXE.
LOG: Attempting download of new URL file:///C://Source/Workspaces/CQB/Development/Dev-branch/Azure/CloudService1/csx/Debug/roles/CQB.TaskRole2/approot/System.ComponentModel.Annotations/System.ComponentModel.Annotations.EXE.

A: I discovered the version showing for Version 4.5.0 in the library reference properties is 4.2.1.0. When I changed the version to 4.4.1 via NuGet, the version in the properties changed to 4.2.0.0.
So change the version of System.ComponentModel.Annotations to 4.4.1 via nuget will resolve the issue for me.