text:
Q: How to understand the curvature of this metric? Suppose we have the metric $ ds^2 = dr^2 + \alpha^2 d\phi^2$, where $\alpha$ is a constant, $0 \leq r \leq \infty$, $ 0 \leq \phi \leq 2 \pi$ and we identify points $\phi = 0$ with points $\phi = 2\pi$.
Now since we have a constant metric the Christoffel symbols are zero and thus so to is the curvature tensor. So this should be flat space. When I try to find the length along radial paths from $0$ to $R$ I find the length to be $R$, but when I find the length of fixed radius paths from $0$ to $2\pi$ I find them to be of length $2\pi \alpha$. So regardless of the position in the $r$ direction we have fixed circumference, thus it seems like this space can be embedded in 3D cylindrical coordinates as a cylinder.
Question 1: Is the above correct? If it is, why are cylinders flat but not spheres or saddle points? Intuitively is it because flattening a cylinder only introduces folds where as a sphere would have complex deformations?
Question 2: If you draw a sphere in spherical coordinates where $r$, $\theta$ and $\phi$ are all draw at right angles a sphere would look like a rectangle with relevant sides of $\theta$ and $\phi$ identified. Since a rectangle looks flat to me, how can you be sure that you are embedding in such a way as to visualise the curvature? Is it that any coordinates where the sides are identified will reveal the curvature?

A: I answered an imported version of this question on physics overflow. I decided to post that answer here as well. Due to formatting differences between the sites it will be a inconvenient to maintain up to date versions of both answers, therefore I will only update the original posting of the answer unless a major modification is necessary.

To answer the first question:
This is the line element for a cylinder though the variable names might make more sense when the line element is written as, $ds^2 = dz^2 + r^2 d\phi^2$, where $r$ is a constant. In this context $z$ is the elevation on the cylinder, $r$ is the radius of the cylinder, $\phi$ is the angle which wraps around the cylinder.
Cylinders are flat because they can be cut and unfolded, making them into a rectangular sheet, without stretching the material of the cylinder. More formally there exists an isometric transformation from the cylinder to the plane.  The identification of $\phi=0$ with $\phi=2\pi$ is a topological property of the cylinder which doesn't necessarily say anything about its curvature.
To be clear when I say that a transformation is isometric I meant that it preserves the relative distances of points as measured locally within the manifold. Distances measured through the embedding space are irrelevant.
Now suppose we wanted to map the plane to the sphere. We might start by turning the plane into a cylinder since we know we can do isometrically. To turn the cylinder into a sphere we would have to identify all the points on the rim at the top of the cylinder. The problem with this last identification is that it sends points that were formerly a finite distance apart to the same location meaning that the metric cannot have been preserved.
The above example isn't really a proof that there is not isometric mapping from a plane to a sphere, but I think it at least gives some insight into what is going on.
To answer the second question:
It looks like you are thinking of Identifying $\theta=0$ with $\theta=\pi$ and $\phi=0$ with $\phi=2\pi$ which would not form a sphere. Instead this would form a torus.
To form a sphere from $0 \leq \theta \leq \pi$ and $0\leq \phi \leq 2\pi$:

*

*For $ 0 < \theta < 2\pi $ identify $\phi=0$ with $\phi = 2\pi$.

*For $\theta = 0 $ identify all values of $\phi$ with a single point.

*For $\theta = \pi $ identify all values of $\phi$ with a single point.

An important thing to realize at this point is that we still don't have a proper sphere because we haven't defined a metric. As it stands our manifold could just be some deflated beach ball.
One line element which would be consistent with the boundary conditions is,
$$ds^2 = d\theta^2 + \theta(\pi-\theta) d\phi^2, $$
which is not the metric of a $2$-Sphere.


text:
Q: Conditional Normal Distribution with Inverse Assume that Yi|θ ∼ N(3θ,2), for i = 1,...,n, and Θ ∼ N(1,9). Find the conditional pdf of Θ given the sample Y = (Y1, . . . , Yn)′.
I'm not sure how to go about this but my thought process was the following:
-We need to find f(Θ|Y)=f(Θ)/f(Y) and f(Y)=f(Yi|θ)f(Θ) and then we can inverse f(Y) and inverse it and find our answer. My problem tho is multiplying the two normal distributions together? It gets a messy answer and not sure how to fully continue it.

A: You only need to focus on the terms with $\theta$.
\begin{align}
f(y_1, \ldots, y_n, \theta)
&= f(\theta) \prod_{i=1}^n f(y_i \mid \theta)
\\
&= (2\pi \cdot 9)^{-1/2} e^{-(\theta - 1)^2/(2 \cdot 9)}
\prod_{i=1}^n (2 \pi \cdot 4)^{-1/2} e^{-(y_i - 3 \theta)^2 / (2 \cdot 4)}
\\
&= c_{y_1, \ldots, y_n} \exp\left(-\left(\frac{1}{18} + \frac{9}{8} n\right)\theta^2 + 2 \left(\frac{1}{18} + \frac{3}{8} \sum_{i=1}^n y_i\right)\theta\right)
\end{align}
Dividing this by $f(y_1, \ldots, y_n)$ will give you the desired conditional density, but this term also does not involve $\theta$. So it suffices to focus on the big exponential term above. You can complete the square to find that it is a normal distribution with some mean and variance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ajax remove item after reload So I created a little Ajax script which removes items from my database and view, unfortunately the view does only Change after a reload (item gets removed).
I could do a window.location.reload() in my success function, but I do not want to reload the whole page.
How do I handle this so that I do not have to reload the whole page and the item gets removed in the view.

html:
<form method="post">
    <input type="hidden" name="_method" value="delete">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="id" value="{{ $deviceValue->id }}">
    <button type="button" class="btn btn-danger destroy-device" data-id="{{ $deviceValue->id }}" name="destroy_device">

    </button>
</form>

A: Suppose you have a list of items (loaded from database) and you execute an ajax call to delete some of those items from the database.
You can return the deleted items' ids into the ajax callback and delete them from the UI:
HTML

Item one

Item two

Item three

jQuery
$.ajax({
   ...
   success: function(data) {
      // data --> Array of deleted items (data-item)
      if (data) {
         var list = $('#myList');
         for(var i=0;i<data.length;i++) {
            list.children('li[data-item="' + data[i] + '"]').remove();
         }
      }
   }
});

You can do something similar with a table or another UI element


text:
Q: Measured grid labeling in ArcMap Can the grid labels be written along the ends of the grid lines within the data box without Cartography tools and with E / N at the end?
I've been playing with offsets and other options. The only result I got were labels within the box but not along the lines. The chart is not north up.
Editing the labels is not what I'm looking for as there is quite a lot of these charts.


text:
Q: powerview in sharepoint 2013 app We got a requirement to embed powerview graphs and powerpivot tables in sharepoint 2013 app.  I am new to sharepoint app development.
Please direct me with some reference articles.
Thanks
MM

A: First you need to make sure you have Enterprise Version of SharePoint. Then you need to configure SharePoint BI features. Activate BI features requires set of configurations on SQL/SharePoint, Possibly Kerberos configuration etc. You will get an overview of how to install/configure BI features at:http://msdn.microsoft.com/en-us/library/hh231671.aspx. You will also get an step by step instructions at  http://blogs.msdn.com/b/querysimon/archive/2012/11/26/installing-the-bi-features-of-sharepoint-2013.aspx.


text:
Q: Overlay image on hover using only css I'm trying to overlay an image with a smaller image that has the background opacity of the first image when hover, using only css because i'm not able to edit the html.
Here is a sample HTML:

Using CSS only, i thought would be something like this:
.image:hover {
   background-image: url('https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-right-128.png');
}

But it will only replace the image.

A: You could use the css pseudo element if you wouldn't like to (or cannot) modify the html.
Please be awared you cannot use :before or :after on img element
Here is the CSS:
img { max-width: 300px; } /* the image dimension */

.image a { position: relative; display: inline-block; } /* allow :before element positioning easier */
.image a:hover:before {
  position: absolute;
  top: 30px; left: 40px; /* Where to put the overlay */
  display: inline-block;
  content: ''; /* must have */
  width: 300px; height: 164px; /* size of the element */
  background-image: url('https://i.kinja-img.com/gawker-media/image/upload/s--pEKSmwzm--/c_scale,fl_progressive,q_80,w_800/1414228815325188681.jpg'); /* URL of the image */
  background-size: 300px 164px; /* Resize the image as this dimension */
  opacity: .5; /* Transparent rate */
}

You can try it on https://jsfiddle.net/bq9khtz3/

A: Did not have the original image so used an image of my own. See if this helps.
You can also refer to this link:  https://jsfiddle.net/askptx0y/

.image:hover {
  background-image: url('https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-right-128.png');
  background-repeat: no-repeat;
  opacity: 1;
}
img:hover {
  opacity: 0.5;
}

A: Try adding a :before element on :hover.
.image a:hover:before {
   content: '';
   display: block;
   position: absolute;
   background-image: url('https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-right-128.png');
}

A: Make image transparency:
.image a:hover image {
   opacity: 0;
 }

Show your background image
.image a:hover {
   background-image: url('https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-right-128.png');
  /* add other properties */
}

A:     .image:hover img {
    -webkit-filter: brightness(40%);
    -moz-filter: brightness(40%);
    -ms-filter: brightness(40%);
    -o-filter: brightness(40%);
}
.image:hover img:after {
   content: '';
   display: block;
   position: absolute;
   background-image: url('https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-right-128.png');
}


text:
Q: Difference between valueOf() and String.format() Why are the values of String.valueOf(5.6d + 5.8d) and String.format("%f", 5.6d + 5.8d) diffrent?
String.valueOf(5.6d + 5.8d) will print "11.399999999999999".
String.format("%f", 5.6d + 5.8d) will print "11.400000".
Why is it so?
Edit: The question differs to Is floating point math broken? , because String.format() round up (see answers)

A: From the documentation of Format Strings for String#format:

If the precision is less than the number of digits which would appear after the decimal point in the string returned by Float.toString(float) or Double.toString(double) respectively, then the value will be rounded using the round half up algorithm.

By default, String.format("%f", ...) uses 6 decimal digits of precision; because this is fewer digits than what would appear when used by Double.toString(double) (which is equivalent to String.valueOf(double)), then the value is rounded as specified above.

A: There are two parts to the explanation.

*

*The result of 5.6d + 5.8d is not exactly 11.4 due to binary floating point representation, precision and rounding issues; see Is floating point math broken? for explanations of why that is so.  (And no, it isn't broken!)

*The reason that String.valueOf and String.format are outputting different answers for the same double value is down to the respective specifications:
For valueOf:

"How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double."

The double value is closer to 11.399999999999999 than 14.0 so the output is the former.
For format:

"If the conversion is 'e', 'E' or 'f', then the precision is the number of digits after the decimal separator. If the precision is not specified, then it is assumed to be 6."

When you round 11.399999999999999 to 6 digits of precision after the decimal point you get 11.40000000.
(The above quotes are from the Java 9 javadocs.)


text:
Q: How can I select VerticalBarSeries from a ReactVis series plot? ReactVis API here outlines what is available which might be helpful. I have successfully added a "drag to select" function to my custom code. In the picture, we would be selecting 13 to 17 and turn the fill value to red for example.
More pseudo code question but code would be awesome.
A container div in a Hook would look like this:

 {
    if (!x && !y) {
      setX(e.clientX); setY(e.clientY)
    }
  }}
  onMouseMove={(e) => {
    if (x && y) {
      const newX = e.clientX; const newY = e.clientY;
      setX1(newX); setY1(newY);
      setRect(

 newX ? newX : x, top: y > newY ? newY : y,
          width: Math.abs(newX - x), height: Math.abs(newY - y),
          backgroundColor: 'gray', opacity: 0.2
        }} />
      )
    }
  }}
  onMouseUp={(e) => {
    setX(null); setY(null); setX1(null); setY1(null);
    setRect(null);
  }}
>
    <XYPlot>
        //...
    </XYPlot>
    {rect}

Thank you very much.

A: In order to achieve "selected" vs "notSelected" state of the series, we need to use "datawithcolor" objects as our data object: {x: foo, y: bar, color:0}. Passing such an array to a react-series would be sufficient to render different coloured series (bars for example). For example: [{x: foo, y: bar, color:0}] where colorDomain would be [0, 1] and the colorRange would be some blue and red.
In order to have a listed of selected "values", we can hold on to a list of values in a react state (hooks or class), either during a dragging of a rectangle or after the rectangle has been drawn, in my case only during dragging. Every time the rectangle changes, the list must be updated.
On re-render generate a new "datawithcolor" array for React-vis bar-series with colour ranges and domains defined using indexes returned from onNearestX or similar React-vis callback.
How do we update the selected list?
<ReactSeries
          // see React-vis source of abstract-series.js for details
          /*
          onNearestX(value, {
            innerX: xScaleFn(value),
            index: valueIndex,
            event: event.nativeEvent
          });
          */
          onNearestX={(datapoint, { index, innerX }) => {
            // rect is mentioned in the question
            if (rect && isWithinRect({ x, x1, value: innerX })) {
              if (!selected.includes(index)) { // prevent rerender
                setSelected([...selected, index]);
              }
            } else {
              if (!rect) {
                setSelected([index]); // single hover
              }
            }
          }}
          colorDomain={[0, 1]}
          colorRange={['red', 'blue']}
          data={dataWithColor} />

For full example see this.
Things to remember, managing the rectangle and selected list are two different things. React-vis colorRange should be clear by now, the docs were not so helpful to me.


text:
Q: How to avoid database connection pool from being exhausted when using FastAPI in threaded mode ( with `def` instead of `async def`) I use FastAPI for a production application that uses asyncio almost entirely except when hitting the database. The database still relies on synchronous SQLAlchemy as the async version was still in alpha (or early beta) at the time.
While our services do end up making synchronous blocking calls when it hits the database it's still wrapped in async functions. We do run multiple workers and several instances of the app to ensure we don't hit serious bottlenecks.
Concurrency with Threads
I understand that FastAPI offers concurrency using threads when using the def controller_method approach but I can't seem to find any details around how it controls the environment. Could somebody help me understand how to control the maximum threads a process can generate. What if it hits system limits?
Database connections
When I use the async await model I create database connection objects in the middleware which is injected into the controller actions.
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):

    await _set_request_id()

    try:
        request.state.db = get_sessionmaker(scope_func=None)
        response = await call_next(request)
    finally:
        if request.state.db.is_active:
            request.state.db.close()
    return response

When it's done via threads is the controller already getting called in a separate thread, ensuring a separate connection for each request?
Now if I can't limit the number of threads that are being spawned by the main process, if my application gets a sudden surge of requests won't it overshoot the database connection pool limit and eventually blocking my application?
Is there a central threadpool used by FastAPI that I can configure or is this controlled by Uvicorn?
Uvicorn
I see that Uvicorn has a configuration that let's it limit the concurrency using the --limit-concurrency 60 flag. Is this governing the number of concurrent threads created in the threaded mode?
If so, should this always be a lower than my connection pool ( connection pool + max_overflow=40)
So in the scenario, where I'm allowing a uvicorn concurrency limit of 60 my db connection pool configurations should be something like this?
engine = sqlalchemy.create_engine(
    cfg("DB_URL"),
    pool_size=40,
    max_overflow=20,
    echo=False,
    pool_use_lifo=False,
    pool_recycle=120
)

Is there a central threadpool that is being used in this case? Are there any sample projects that I can look at to see how this could be configured when deployed at scale.
I've used Netflix Dispatch as a reference but if there are other projects I'd definitely want to look at those.

A: Fastapi uses Starlette as an underlying framework. Starlette provides a mechanism for starting def path operations in the thread pool for which it uses anyio. Therefore, we can limit the number of threads which can be executed simultaneously by setting property total_tokens of anyio's CapacityLimiter.
Example below:
import threading
import anyio
import uvicorn
from fastapi import FastAPI
import time
import logging

THREADS_LIMIT = 5

logging.basicConfig(level=logging.DEBUG)
app = FastAPI()

class Counter(object):
    def __init__(self):
        self._value = 0
        self._lock = threading.Lock()

    def increment(self):
        with self._lock:
            self._value += 1

    def decrement(self):
        with self._lock:
            self._value -= 1

    def value(self):
        with self._lock:
            return self._value

counter = Counter()

@app.get("/start_task")
def start_task():
    counter.increment()
    logging.info("Route started. Counter: %d", counter.value())
    time.sleep(10)
    counter.decrement()
    logging.info("Route stopped. Counter: %d", counter.value())
    return "Task done"

@app.on_event("startup")
async def startup_event():
    limiter = anyio.to_thread.current_default_thread_limiter()
    limiter.total_tokens = THREADS_LIMIT

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="debug")

Try to open 50 connections in parallel:
seq 1 50 | xargs -n1 -P50  curl "http://localhost:8000/start_task"

We see that the number of simultaneously processed requests is limited to 5.
Output:
INFO:root:Route started. Counter: 1
INFO:root:Route started. Counter: 2
INFO:root:Route started. Counter: 3
INFO:root:Route started. Counter: 4
INFO:root:Route started. Counter: 5
INFO:root:Route stopped. Counter: 4
INFO:uvicorn.access:127.0.0.1:60830 - "GET /start_task HTTP/1.1" 200
INFO:root:Route stopped. Counter: 3
INFO:root:Route started. Counter: 4
INFO:uvicorn.access:127.0.0.1:60832 - "GET /start_task HTTP/1.1" 200
INFO:root:Route started. Counter: 5
...


text:
Q: Preferred backend programming for Android I am a fresh PHP web developer, however, I'm working on a mobile app startup that will operate on Android. My programming team are highly experienced .NET developers. Is it the right choice to use .NET for the backend development? Is there any OTHER programming language that is better for Android (consider that an iOS version will be developed in the future)?

A: Naturally you should be coding in what you are experienced and productive in. If your team are experienced .NET developers they should be doing .NET. A native mobile application doesn't care what the backend is written in. Its a black box it talks to through APIs. All it cares about is the API and the format chosen for data serialization. .NET developers seem to go for SOAP, which I feel is a bad choice for a mobile application. Way to much overhead in the data payload.
TL;DR
Write the backend in whatever you like, but stick to a simple REST-ish API design with lightweight data serialization like JSON for communication.

A: I would HIGHLY recommend MonoDroid and MonoTouch from Xamarin. This platform greatly accelerates development and considering that you have a team of .NET developers (and are considering iOS soon) - I can think of no other development path that would give you a greater (development) cost/benefit ratio.
Remember - your code will mostly be portable to Windows 8, too!


text:
Q: StandardOutput option of systemd is not working I'm using systemd to start a program on boot and keep it running in the background.
I wrote a simple script for systemd to call and the script will print several lines of logs which I'd like to see in the terminal.
So I set StandardOutput=journal+console in the service configuration but I wasn't able to see the outputs neither in the terminal nor the journal.
frederick@Frederick-PC:~$ sudo systemctl start my_program.service
frederick@Frederick-PC:~$ journalctl _SYSTEMD_UNIT=my_program.service
No journal files were found.
-- No entries --

And these are my service configuration and the script.
/etc/systemd/system/my_program.service
[Unit]
Description=Start my_program client after system is booted

[Service]
Type=forking
ExecStart=/usr/bin/my_program.sh start
ExecStop=/usr/bin/my_program.sh stop
PIDFile=/run/my_program.pid
WorkingDirectory=/home/frederick/Applications/my_program-go/
StandardOutput=journal+console

[Install]
WantedBy=multi-user.target

/usr/bin/my_program.sh
#!/bin/sh

start() {
    if [ -f /run/my_program.pid ]; then
        kill -0 $(cat /run/my_program.pid) > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            echo "my_program has been already started"
            exit 1
        fi
    fi
    echo -n "Starting my_program... "
    nohup /home/frederick/Applications/my_program-go/my_program-local -c /home/frederick/Applications/my_program-go/config.json >> /home/frederick/Applications/my_program-go/my_program.log 2>&1 &
    if [ $? -gt 0 ]; then
        echo "failed"
        rm /run/my_program.pid > /dev/null 2>&1
    else
        echo $! | tee /run/my_program.pid
    fi
}

stop() {
    if [ -f /run/my_program.pid ]; then
        echo -n "Stopping my_program... "
        msg=$(kill $(cat /run/my_program.pid) 2>&1)
        if [ $? -gt 0 ]; then
            echo "failed"
            echo $msg
        else
            rm /run/my_program.pid > /dev/null 2>&1
            echo "succeeded"
        fi
    else
        echo "my_program not started"
    fi
}

restart() {
    stop
    start
}

case $1 in
    start|stop|restart)
        "$1"
        ;;
    *)
        echo "No such operation"
        exit 1
        ;;
esac

How can I see those lines printed by echo in the script? Please help, thanks.

A:
I wrote a simple script for systemd to call …

… which was the source of the problem.  Your "simple script" overrode where the standard output and standard error were sent.  And that entirely unnecessarily.  All of the redirection, PID file writing, nohup-ing, and forking is entirely unnecessary for something that is already daemonized and already has its PID known by the service manager.  You don't need any part of that script at all.  Instead, write your service unit like this:

[Unit]
Description=Start my_program client after system is booted

[Service]
Type=simple
ExecStart=/home/frederick/Applications/my_program-go/my_program-local -c /home/frederick/Applications/my_program-go/config.json
WorkingDirectory=/home/frederick/Applications/my_program-go/
StandardOutput=journal+console

[Install]
WantedBy=multi-user.target

Invoke whatever options are necessary to stop your program from forking, unless it actually definitely implements the forking readiness protocol.  Very few programs actually do.  Your "simple script" certainly didn't, as it exited the parent process long before the dæmon had initialized and was ready.
Further reading

*

*Jonathan de Boyne Pollard (2015). The systemd house of horror.  Frequently Given Answers.

*Systemd kills service immediately after start

*Yocto linux service script problem

*The systemd.exec man page (and also systemd.service and systemd.unit). The man page says: Unit configuration files for services, sockets, mount points, and swap devices share a subset of configuration options which define the execution environment of spawned processes. This man page lists the configuration options shared by these four unit types.


text:
Q: using "IF" with "DLookup" in ms access I am making a form in MS Access, my version is 2019 from Office 2019. I have problem with duplicate entry of the invoice for purchased merchandise. Each supplier has their own way of defining their "invoice numbers" and sometimes they are using similar numbers since some use "date" to define their invoice number for example , company A invoice no is 202107001 and Company B also has 202107001 since it is July of 2021 and it happens to be the "first bill" of their month... some supplier do not have "invoice no." because they are individual selling handmade product.
Therefore, I have to write vba code to prevent entering "duplicate" invoice number from our suppliers! Here is my unworking code...
not even it doesn't work but also shows "method or data not found" too! Would there be anyone kindly help please?
Here is the condition I intend to do with the below code
"If the entered supplier invoice number is a duplicate value according to their own identification scheme, the message box should appear as the latter part of the vba code..."
Private Sub txtIMHead_supinvoicenumber_AfterUpdate()

    Dim supinvoicenumberstring As String

    supinvoicenumberstring = Me.IMHead_supinvoicenumber.Value

    If Me.txtHead_supinvoicenumber = DLookup("[IMHead_supinvoicenumber]", "tbl_IMHead", txt_IMHead_supid) Then
    MsgBox "This supplier's invoice number" & supinvoicenumberstring & ",has been recorded!" _
    & vbCr & " Please stop the process and record another invoice!" & vbCr & "Thank you very much!"
    Me.Undo

    End If

End Sub

A: WHERE CONDITION argument needs to specify field that criteria applies to:
DLookup("[IMHead_supinvoicenumber]", "tbl_IMHead", "some field name here=" & Me.txt_IMHead_supid)
However, that expression will return IMHead_supinvoicenumber from first record that matches the given supid. You need to know if invoice number already exists for selected supid so must use invoice number in criteria as well.
If Not IsNull(DLookup("[IMHead_supinvoicenumber]", "tbl_IMHead", _
   "some field name here=" & Me.txt_IMHead_supid & _
   " AND IMHead_supinvoicenumber='" & supinvoicenumberstring & "'")) Then

An option is DCount:
If DCount("*", "tbl_IMHead", "some field name here=" & Me.txt_IMHead_supid & _
   " AND IMHead_supinvoicenumber='" & supinvoicenumberstring & "'") > 0 Then


text:
Q: NPM not working. Cannot find module 'strip ansi' I just downloaded node but npm is  not working. whenever I use a npm comman I get Error: cannot find module 'strip-ansi'.

A: I was stuck on this problem too. Finally, I solved the issue by adding value '.js', '.ts' to resolve.extensions in my webpack.config.js.  If you are using webpack too, this may help.

A: just reinstall strip using npm install strip --save this kind of error occurs because some file may be corrupt in strip library if this will not work you can try also npm install you will solve this error.

A: I hit this same issue. I tried to update npm after a fresh Node.js install, but cancelled in the middle because it appeared stuck. Reinstalling Node.js didn't help.
I resolved the issue by deleting the temporary npm files in my AppData folder (for me on Windows, I found it in c:\Users\Me\AppData\Roaming\npm). Then I was able to run npm normally again.
Hope that helps!

A: For what it's worth, this ended up happening to me, using nvm on mac. npm cache clean didn't work. I ended up reinstalling via nvm:
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash
$ nvm install node

A: It solved for me by going to the NPM install folder at /usr/local/lib/node_modules/npm and running the yarn command. After running it successfully, NPM started working normally.

A: I had the same issue with my next js application. What i did was uninstall strip-ansi(npm uninstall strip-ansi) and then reinstall (npm install strip-ansi)

A: Clear your temporary paths of npm and this is solution.
if you're using linux:
go to $ cd /tmp/
search by npm-* folders
and remove all.

A: Solved by doing npm cache clean and then npm install


text:
Q: Getting NULL when open file in C code by JNI in android I'm calling C code by JNI in android app.
Every thing is OK in calling, but when I put this code:
FILE* fp = fopen("/storage/sdcard0/input.txt","w+");
if(fp==NULL)
    return(*env)->NewStringUTF(env,"n");
else
    return(*env)->NewStringUTF(env,"y");

it gets "n". I'm sure that the path is true and I tried this command on my mobile's terminal:
cat /storage/sdcard0/input.txt

and it got me the file's contents.
Edit:
I tried to change the permission of the file by this code but it gave me the same response:
void changePerm()
{
    Process chperm;
    try {
        chperm=Runtime.getRuntime().exec("su");

   DataOutputStream os =
          new DataOutputStream(chperm.getOutputStream());
        os.writeBytes("chmod 777 /storage/sdcard0/input.txt\n");
        os.flush();

        os.writeBytes("exit\n");
        os.flush();

          chperm.waitFor();

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

I also add this permission and no thing changed:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

A: I take it that the permissions on the file are in fact 0777.
You added android.permission.READ_EXTERNAL_STORAGE, but you try to open for writing
FILE* fp = fopen("/storage/sdcard0/input.txt","w+");

You can get the error by checking for errno and get a message with strerror.
You must either open the file for reading only "r" or add permission for writing WRITE_EXTERNAL_STORAGE


text:
Q: Dialogues complex with Watson I started developing a chatbot using watson, I found it surprising and simple to deploy. But I was left with some doubts on how to do it and if it is possible (I saw in some chatbot).
An example is, using the conversation I can define #intentions, @ties and dialogs. But how would the process of giving options work? For example, I asked the question "What's the best beer?" and he would respond to something like "There are a lot of beers, but a list with 5 for you" and so they list themselves in the list. and that I could click and follow with the dialogue and so on. I've seen this in some chatbot, but I have not seen how to do that sort of thing with watson.
Another thing is, is it possible to interact with a Back End? Ex: "Overdue accounts", and my back would consult the bank and return the overdue accounts.
I was pretty confused about this topic. And finally, Watson is the best option to develop a chatbot?

A: The Watson conversation tool is used to create the dialogue flow of the content and is not designed yet for deploying with other options such as buttons, videos etc straight from within the tool.
In order to do this, you require an "orchestration" layer which is usually an app.js with code in that will enable you to use buttons, call other services, interact with backend systems etc.
An example kit can be found here which will support many facebook buttons and options but the logic is the same for whichever front end you use. The kit includes facebook buttons, carousel, share button and images. Also included are some additional Watson services such as visual recognition and tone analyzer, which demonstrate interacting with another service.
Facebook bot actions
Simple HTML Front end with buttons
In order to present the options to the user, you simply place the code required to display a button in the dialog output. e.g "Choose your option"option1
Recently launched also are the IBM Cloud Functions for making service backend calls https://developer.ibm.com/recipes/tutorials/watson-conversation-ibm-cloud-functions-to-do-a-longtail-chatbot/

A: Just complemeting what @ReeceMed said... Watson is just one API endpoint, so you app can do a lot of things with some custom codes.
About your first doubt, you need to create one #intentBeer with examples of how to ask for beer, best beers:

*

*"What's the best beer?"

*"Can you please recommend the best beer here?"

*"I want to buy the best beer here!"

*"I'd like to request the best beer, please"

I really recommend to you give the maximum of examples in your mind or request for another person's how they ask for something similar. And see this project example, conversation simple, building in Node.js with Watson Conversation from IBM Developers.
And in the Dialog, you will create one Node that will recognize the #intentBeer
if bot recognizes #intentBeer response: Oh! The best beer here is: - X
 - Y
 - Z

So, if you're using a web example, you can add HTML tags in the Watson response, like this answer that I answer a few months ago.
And for do something, like "Overdue accounts" example, you can see this answer. Basically, you need to access the context variable or the action object in the return of your post /message, and in your back-end, you'll do something with a custom code.


text:
Q: Help implementing "Horizontal UITableViewController"? I've got a bunch of "slides" which I'm trying to show on the iPad, one at a time, using a UIScrollView. The "slides" are various subclasses of the UIViewController class.
I'm storing my slides in NSUserDefaults, represented by NSDictionaries. At startup, I, load the NSArray of NSDictionaries and loop through them, passing the views to the UIScrollView.
Right now this is inefficient, because all of the slides are being held in memory even when they offscreen. I suspect that I should make it behave a little more like the UITableViewController, in terms of reusing slides and releasing slides when they are offscreen and recreating them as they come onscreen.
I have two questions.

*

*Firstly, how does UITableViewController handle the cell-swapping? Where can I find some sample code or algorithms?

*Second, How can I re-use slides if they are not all of the same type?

A: I wrote an answer about a cyclic UIScrollview here:
How to implement a cyclic UIScrollView?
If you use that approach then you only really need 3 views loaded at any time.
If your views are not all the same type then you just need to implement as much of the commonality as you can into a UIView subclass and perform necessary customisation (setting the image etc.) before display. It should be possible to create only three of them. The one you are scrolling towards begins to be displayed, the one you are scrolling away from is modified for display as it scrolls into view...
A B C
Three views - A and C are not visible, B is visible.
If you scroll to the right some of B, some of C is visible. A can be reused and logically moved to follow C so you have
B C A
Keep scrolling to the right, alter B and make it logically after A
C A B
If you scroll in the other way same idea but do it in reverse.


text:
Q: Cloud Function finished with status: 'timeout'" In Firebase console, the last Event message in Functions/Log section is "Function execution took 60006 ms, finished with status: 'timeout'". Is "timeout" the status the function is supposed to finish with? Or did I miss something in the code that would say "that's the end"?

A: You should send a response like res.send(200) at the end for it to terminate properly


text:
Q: File "python", line 25 SyntaxError: 'return' outside function File "python", line 25
SyntaxError: 'return' outside function
total=0
for key in prices:
    sum=prices[key]*stock[key]
    print sum
    total=total+sum
return total

A: Try relocating this code into a function.
For example:
#!/usr/bin/env python
prices = { 'Python': 100 }
stock = { 'Python': 20 }

def total_portfolio_value():
  total=0
  for key in prices:
    sum=prices[key]*stock[key]
    print sum
    total=total+sum
  return total

total_portfolio_value()


text:
Q: Atualizar array posições especificas usando mongodb com ou sem Mongoose! Tenho a seguinte situação!
const meuModel = new mongoose.Schema({

  nome: { type: String, required: [true, 'Nome'] },

  links:{type : Array,},
})

Links é um array de objetos!
links [{url:link, clicks:0},{url:link1, clicks:0},{url:link2, clicks:0}]
Eu preciso fazer update especifico. Sem nunca mudar os clicks, nem mexer neles!
links [{url:link, clicks:4},{url:novoLink, clicks:0},{url:link2, clicks:5},{url:novoLink2, clicks:0}]

eu quero permitir o usuário modificar os Links como quiser. Mas os clicks sempre serão via sistema.
Meu problema esta me salvar isso no mongo!
teste = await MeuModel.findOneAndUpdate({
          _id
        },{$inc: {
          "links.0.url":'novolink',
          "links.1.url": 'linkantigo',
          "links.2.url": 'novo link se for novo',
      }}

Isso não funciona!
Pois quer mudar uma posição, só quando viver do front algo novo!
Se o usuário mudou 3 links, eles devem ser salvos!
"$set" não aceita que eu percorra o array para modificar somente onde for preciso!
"$set" só permite mudança de 1 posição especifica
await meuModel.findOneAndUpdate({
          _id
        },{
          "$set": {[`links.$[outer].url`]: 'novoLink'}
        },
        {
          "arrayFilters": [{ "outer.url":'antigoLink'}]
        })

$set com arrayFilters só aceita uma condição para muitos ou apenas 1.
Quero poder mandar salvar o array todo de uma vez, com as modificações apenas dos links, se ela existirem!

A: Consegui usando
o comando save()
Minha lógica:
Dados vem do front modificados ou não!
chamo o meu model pelo ID.
const links = await meuModel.findOne({
    _id
   })

   links.links.forEach((v,i) =>{

   if(v.url !== front.links[i]?.url){

   links.links[i].url = front.links[i]?.url

   }

 })
 Links.markModified('links')
 const save =  await links.save()

uso forEach para comparar os dados do front com os do back
forEach
compara cada posição do array do front com cada posição do array que veio do
banco
se algum link esta diferente do antigo, o novo é adicionado na mesma posição!
links.links[Posicao].url = dado_do_front na mesma posição

Faço isso em todas as posições
aviso ao mongo que mudei o array
Links.markModified('links')

const save =  await links.save()

Esta lógica funciona perfeitamente! Os links são mudados e os clicks nunca mexidos
Mas não sei se é a melhor lógica!


text:
Q: Make npx silently install latest package version, without prompting user for input Synopsis
When I use npx create-next-app@latest, I am prompted to install a newer package version. I cannot find a parameter on npx to make the command silently work inside of a script.
For example, I would expect to find a parameter such as --silent or --force or --yes, as is common convention with other package managers.
There has to be an easy answer to this, but I honestly can't find it.
FYI I am using PowerShell as my shell environment on Windows 10, although I would expect the npx command to provide a parameter, instead of having to use shell features (piping) to accomplish this.
PS C:\git\myapp> npx create-next-app@latest
Need to install the following packages:
  create-next-app@latest
Ok to proceed? (y)

The npx --help command doesn't produce any guidance.
PS > npx --help
npm exec

Run a command from a local or remote npm package

Usage:
npm exec -- <pkg>[@<version>] [args...]
npm exec --package=<pkg>[@<version>] -- <cmd> [args...]
npm exec -c '<cmd> [args...]'
npm exec --package=foo -c '<cmd> [args...]'

Options:
[--package <pkg>[@<version>] [--package <pkg>[@<version>] ...]]
[-c|--call <call>]
[-w|--workspace <workspace-name> [-w|--workspace <workspace-name> ...]]
[-ws|--workspaces]

alias: x

Run "npm help exec" for more info

Actual Result
npx pauses execution until user input is provided.
Expected Result
npx automatically installs the latest version of the package and executes it, without prompting the user.

A: This appears to be a bug. According to the online documentation, the --yes parameter is supported on npm exec (aka. npx). However, on version 7.19.1 of npm, specifying the --yes option is ignored by the CLI.
To reproduce the problem, run a new Node.js container using the Docker CLI, using a Bash shell:
docker run --rm --interactive --tty node:16.5.0 bash

Then, run these commands inside the container:
npm install --global create-next-app@10.0.9
npx create-next-app@latest --yes

Here's the version information from the 16.5.0 container image:
{
  npm: '7.19.1',
  node: '16.5.0',
  v8: '9.1.269.38-node.20',
  uv: '1.41.0',
  zlib: '1.2.11',
  brotli: '1.0.9',
  ares: '1.17.1',
  modules: '93',
  nghttp2: '1.42.0',
  napi: '8',
  llhttp: '6.0.2',
  openssl: '1.1.1k+quic',
  cldr: '39.0',
  icu: '69.1',
  tz: '2021a',
  unicode: '13.0',
  ngtcp2: '0.1.0-DEV',
  nghttp3: '0.1.0-DEV'
}


text:
Q: Parsing NSData is crashes I get this data from BLE, but is crashes on certain values (I think when data is float )
function to get data :
  func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {

         print(characteristic); // prints a value always
         if characteristic.UUID == UUID_CHAR {

            if ( characteristic.value == nil)
            {return; }

             //***crash is here :
             let str:NSString = NSString(data: characteristic.value!, encoding: NSUTF8StringEncoding)!
            print ("got::",str);

This will crash when the characteristic is :
<CBCharacteristic: 0x157685860, UUID = FFE1, properties = 0x16, value = <00ff00>, notifying = YES>

and not when its this : (value field here is 00  )
<CBCharacteristic: 0x157685860, UUID = FFE1, properties = 0x16, value = <00>, notifying = YES>

I have tried wrapping it with if let , which did not worked.
ERROR: unexpectedly found nil while unwrapping an Optional value

How would you cast the value to string, knowing it could be a float or integer ?

A: Don't need to cast to NSString, Then you don't have to forcefully unwrap the result. Try this:
let str = NSString(data: characteristic.value!, encoding: NSUTF8StringEncoding)

Now if the value is not a valid UTF-8 Sequence, You won't get a crash


text:
Q: Similar download manager in Chrome to that in Firefox? In Firefox, I am using a download manager which can resume downloading if it breaks because of bad connection, and can automatically download multiple selected links in a webpage.
I tried some extensions in Chrome, but none has the above abilities.
I wonder what chrome extensions can do the above two?