text:
Q: How to pass string as variable in Python? I used Context Manager: cd from here: How do I "cd" in Python?
import os

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

Example
import subprocess # just to call an arbitrary command e.g. 'ls'

# enter the directory like this:
with cd("~/Library"):
   # we are in ~/Library
   subprocess.call("ls")

# outside the context manager we are back wherever we started.

Why not work this code if I use like this:
str = "~/Library"

with cd(str):
   subprocess.call("ls")

Error:
OSError: [Errno 2] No such file or directory: 'cd ~/Library'

A: Your example code seems to work as it should. I can only duplicate your error if I added 'cd' to the value of str such that it tried to change to a directory called 'cd ~/Library'. That is also what seems to have happened based on the error message you show.
Broken
str = "cd ~/Library"
with cd(str):
   subprocess.call("ls")

Fine
str = "~/Library"
with cd(str):
   subprocess.call("ls")


text:
Q: How can I validate exits and aborts in RSpec? I am trying to spec behaviors for command line arguments my script receives to ensure that all validation passes.  Some of my command line arguments will result in abort or exit being invoked because the parameters supplied are missing or incorrect.
I am trying something like this which isn't working:
# something_spec.rb
require 'something'
describe Something do
    before do
        Kernel.stub!(:exit)
    end

    it "should exit cleanly when -h is used" do
        s = Something.new
        Kernel.should_receive(:exit)
        s.process_arguments(["-h"])
    end
end

The exit method is firing cleanly preventing RSpec from validating the test (I get "SystemExit: exit").
I have also tried to mock(Kernel) but that too is not working as I'd like (I don't see any discernible difference, but that's likely because I'm not sure how exactly to mock Kernel and make sure the mocked Kernel is used in my Something class).

A: Its not pretty, but I've been using this:
begin
  do_something
rescue SystemExit => e
  expect(e.status).to eq 1 # exited with failure status
  # or
  expect(e.status).to eq 0 # exited with success status
else
  expect(true).eq false # this should never happen
end

A: try this:
module MyGem
  describe "CLI" do
    context "execute" do

      it "should exit cleanly when -h is used" do
        argv=["-h"]
        out = StringIO.new
        lambda { ::MyGem::CLI.execute( out, argv) }.should raise_error SystemExit
      end

    end
  end
end

A: Using the new RSpec syntax:
expect { code_that_exits }.to raise_error(SystemExit)

If something is printed to STDOUT and you want to test that too, you can do something like:
context "when -h or --help option used" do
  it "prints the help and exits" do
    help = %Q(
      Usage: my_app [options]
        -h, --help                       Shows this help message
    )

    ARGV << "-h"
    expect do
      output = capture_stdout { my_app.execute(ARGV) }
      expect(output).to eq(help)
    end.to raise_error(SystemExit)

    ARGV << "--help"
    expect do
      output = capture_stdout { my_app.execute(ARGV) }
      expect(output).to eq(help)
    end.to raise_error(SystemExit)
  end
end

Where capture_stdout is defined as seen in
Test output to command line with RSpec.
Update: Consider using RSpec's output matcher instead of capture_stdout

A: After digging, I found this.
My solution ended up looking like this:
# something.rb
class Something
    def initialize(kernel=Kernel)
        @kernel = kernel
    end

    def process_arguments(args)
        @kernel.exit
    end
end

# something_spec.rb
require 'something'
describe Something do
    before :each do
        @mock_kernel = mock(Kernel)
        @mock_kernel.stub!(:exit)
    end

    it "should exit cleanly" do
        s = Something.new(@mock_kernel)
        @mock_kernel.should_receive(:exit)
        s.process_arguments(["-h"])
    end
end

A: Thanks for the answer Markus.  Once I had this clue I could put together a nice matcher for future use.
it "should exit cleanly when -h is used" do
  lambda { ::MyGem::CLI.execute( StringIO.new, ["-h"]) }.should exit_with_code(0)
end
it "should exit with error on unknown option" do
  lambda { ::MyGem::CLI.execute( StringIO.new, ["--bad-option"]) }.should exit_with_code(-1)
end

To use this matcher add this to your libraries or spec-helpers:
RSpec::Matchers.define :exit_with_code do |exp_code|
  actual = nil
  match do |block|
    begin
      block.call
    rescue SystemExit => e
      actual = e.status
    end
    actual and actual == exp_code
  end
  failure_message_for_should do |block|
    "expected block to call exit(#{exp_code}) but exit" +
      (actual.nil? ? " not called" : "(#{actual}) was called")
  end
  failure_message_for_should_not do |block|
    "expected block not to call exit(#{exp_code})"
  end
  description do
    "expect block to call exit(#{exp_code})"
  end
end

A: There's no need for custom matchers or rescue blocks, simply:
expect { exit 1 }.to raise_error(SystemExit) do |error|
  expect(error.status).to eq(1)
end

I'd argue that this is superior because it's explicit and plain Rspec.

A: I had to update the solution @Greg provided due to newer syntax requirements.
RSpec::Matchers.define :exit_with_code do |exp_code|
  actual = nil
  match do |block|
    begin
      block.call
    rescue SystemExit => e
      actual = e.status
    end
    actual and actual == exp_code
  end
  failure_message do |block|
    "expected block to call exit(#{exp_code}) but exit" +
        (actual.nil? ? " not called" : "(#{actual}) was called")
  end
  failure_message_when_negated do |block|
    "expected block not to call exit(#{exp_code})"
  end
  description do
    "expect block to call exit(#{exp_code})"
  end
  supports_block_expectations
end

A: I've used @Greg's solution for years now, but I've modified it to work with RSpec 3+.
I've also tweaked it so that the code now optionally checks for an exit status, which I find much more flexible.
Usage
expect { ... }.to call_exit
expect { ... }.to call_exit.with(0)

expect { ... }.to_not call_exit
expect { ... }.to_not call_exit.with(0)

Source
RSpec::Matchers.define :call_exit do
  actual_status = nil

  match do |block|
    begin
      block.call
    rescue SystemExit => e
      actual_status = e.status
    end

    actual_status && (expected_status.nil? || actual_status == expected_status)
  end

  chain :with, :expected_status

  def supports_block_expectations?
    true
  end

  failure_message do |block|
    expected = 'exit'
    expected += "(#{expected_status})" if expected_status

    actual = nil
    actual = "exit(#{actual_status})" if actual_status

    "expected block to call `#{expected}` but " +
      (actual.nil? ? 'exit was never called' : "`#{actual}` was called")
  end

  failure_message_when_negated do |block|
    expected = 'exit'
    expected += "(#{expected_status})" if expected_status

    "expected block not to call `#{expected}`"
  end

  description do
    expected = 'exit'
    expected += "(#{expected_status})" if expected_status

    "expect block to call `#{expected}`"
  end
end

A: Just looking for exit status code of a command.
If all you're doing is testing the exit status code of a command, you can do something like this:
describe Something do
  it "should exit without an error" do
    expect( system( "will_exit_with_zero_status_code" ) ).to be true
  end

  it "should exit with an error" do
    expect( system( "will_exit_with_non_zero_status_code" ) ).to be false
  end
end

This works because system will return:

*

*true when the command exits with a "0" status code (i.e. no errors).

*false when the command exits with a non 0 status code (i.e. error).

And if you want to mute the output of the system command from your rspec documentation output, you can redirect it like so:
system( "will_exit_with_zero_status_code", [ :out, :err ] => File::NULL )

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP MVC routing rest api i would like to create rest api but I have problem with routing.
This url is ok: localhost/project/controller/action/id, but i would like this url localhost/project/controller/id too.
For example: localhost/project/article/5: ArticleController.Get(int id)
This is my code:
Project controller
[HttpGet]
[Route("project/{id}")]
public JsonResult Get(int id)
{
}

Route config:
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Api",
                url: "{controller}/{id}",
                defaults: new { id = UrlParameter.Optional }
            );
        }

When i call url localhost/project/article/5, error message is A public action method '5' was not found on controller 'ArticleController'.
Where is problem? Thanks

A: You can use attribute routing
Example:
[HttpGet]
[Route("project/{controller}/{action}/{id}")]
public JsonResult Get(int id)
{
}

OR
Default Route Table
Example:
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Api",
                url: "project/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

        }

As Per your Requirement, your Routing is:
[HttpGet]
[Route("project/article/{id:int}")]
public JsonResult Get(int id)
{
}

OR
  routes.MapRoute(
                    name: "Api",
                    url: "project/article/{id}",
                    defaults: new { controller = "ArticleController", action = "Get", id = UrlParameter.Optional }
                );


text:
Q: Turn Dynamics 365 address field into dropdown list I'm new to both Dynamics 365 and javascript.
By now users when have to fill an address form write values manually, therefore for the same region we have values like: Lombardia, LOMABARDIA, lomb, Lombadia, etc...
I can't create custom fields because address fields are grouped into composite field and are used for outlook sync.
So i think the right way is create a javascript mask that paste the choosen value in the free text address field, but here is my biggest problem, how to set that mask...
Questions:
Is this the best practice? if not what is?
I am able to create javascript's list and get/set value from crm, but i dont know how to build it over a free text field, any help?

A: You should consider address resolution API, you will then be able to split the selected address that will be in a standard format. Try to check out Experian or even the google API, you can build a custom web resource, hook up the JS that will do address resolution for you, on selection split the values in the composite fields.

A: Rather than "build it over a free text field", which is unsupported, you can build your own custom HTML web resource and add that to the form.
As this document points out, you will need to use parent.Xrm.Page to reference the form - e.g.:
var customerRef = parent.Xrm.Page.getAttribute('customerid').getValue();
This forum indicates that although Xrm.Page is deprecated in v9, it is still valid (for now) to use parent.Xrm.Page from a custom web resource.
Also, please note that to enable accessing the form you should include
<script type="text/javascript" src="../ClientGlobalContext.js.aspx"></script>
in your custom web resource.


text:
Q: Differentiation of $y = \tan^{-1} \Bigl\{ \frac{\sqrt{1+x^{2}} - \sqrt{1-x^{2}}}{\sqrt{1+x^{2}}+ \sqrt{1-x^{2}}}\Bigr\}$ How do i differentiate the following: $$y = \tan^{-1} \biggl\{ \frac{\sqrt{1+x^{2}} - \sqrt{1-x^{2}}}{\sqrt{1+x^{2}}+ \sqrt{1-x^{2}}}\biggr\}$$
I know that $\text{derivative}$ of $\tan^{-1}{x}$ is $\frac{1}{1+x^{2}}$ but not sure as to how to do this.

A: First the idea is to observe as to what would you substitute for $x$ in order to remove the square root. After some manipulations you find that the correct substitution is $x^{2} = \sin{2\theta}$. Once you have done this then you have $$y = \tan^{-1}\biggl\{ \frac{(\cos\theta + \sin\theta) - (\cos\theta - \sin\theta)}{(\cos\theta + \sin\theta)+(\cos\theta - \sin\theta)}\biggr\} = \theta = \frac{1}{2}\sin^{-1}{x^2}$$
So if $y = \frac{1}{2}\sin^{-1}{x^2}$ then $$\frac{dy}{dx} = \frac{1}{2} \cdot \frac{1}{\sqrt{1-x^{4}}} \cdot 2x = \frac{x}{\sqrt{1-x^{4}}}$$

A: Your function simplifies to $\arctan \dfrac{1-\sqrt{1-x^4}}{x^2}$, which should be slightly easier to differentiate (remember the chain rule!)...

A: Here are all the steps in excruciating detail.
Using the tangent of a sum formula gives
$$
\frac{1-\tan{\phi}}{1+\tan{\phi}}=\tan\left(\frac\pi4-\phi\right)\tag{1}
$$
and letting $\tan(\phi)=\sqrt{\frac{1-x^2}{1+x^2}}$ yields
$$
\begin{align}
\tan^{-1}\left(\frac{\sqrt{1+x^2}-\sqrt{1-x^2}}{\sqrt{1+x^2}+\sqrt{1-x^2}}\right)
&=\tan^{-1}\left(\frac{1-\sqrt{\frac{1-x^2}{1+x^2}}}{1+\sqrt{\frac{1-x^2}{1+x^2}}}\right)\\
&=\frac\pi4-\tan^{-1}\left(\sqrt{\frac{1-x^2}{1+x^2}}\right)\tag{2}
\end{align}
$$
Furthermore, we have
$$
\begin{align}
\sqrt{\frac{1-\cos(\psi)}{1+\cos(\psi)}}
&=\frac{\sin(\psi/2)}{\cos(\psi/2)}\\
&=\tan(\psi/2)\tag{3}
\end{align}
$$
so letting $x^2=\cos(\psi)$ yields
$$
\begin{align}
\tan^{-1}\left(\sqrt{\frac{1-x^2}{1-x^2}}\right)
&=\psi/2\\
&=\frac12\cos^{-1}(x^2)\tag{4}
\end{align}
$$
Combining $(2)$ and $(4)$ shows
$$
\begin{align}
\tan^{-1}\left(\frac{\sqrt{1+x^2}-\sqrt{1-x^2}}{\sqrt{1+x^2}+\sqrt{1-x^2}}\right)
&=\frac\pi4-\frac12\cos^{-1}(x^2)\\
&=\frac12\sin^{-1}(x^2)\tag{5}
\end{align}
$$
Therefore,
$$
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}x}\tan^{-1}\left(\frac{\sqrt{1+x^2}-\sqrt{1-x^2}}{\sqrt{1+x^2}+\sqrt{1-x^2}}\right)
&=\frac{\mathrm{d}}{\mathrm{d}x}\frac12\sin^{-1}(x^2)\\
&=\frac{x}{\sqrt{1-x^4}}\tag{6}
\end{align}
$$

A: Putting $x^2=\cos2z,1+x^2=1+\cos2z=2\cos^2z,1-x^2=1-\cos2z=2\sin^2z$
$$\frac{\sqrt{1+x^{2}} - \sqrt{1-x^{2}}}{\sqrt{1+x^{2}}+ \sqrt{1-x^{2}}}=\frac{\cos z-\sin z}{\cos z+\sin z}=\frac{1-\tan z}{1+\tan z}=\tan\left(\frac\pi4-z\right)$$
$$y = \tan^{-1} \biggl\{ \frac{\sqrt{1+x^{2}} - \sqrt{1-x^{2}}}{\sqrt{1+x^{2}}+ \sqrt{1-x^{2}}}\biggr\}=\tan^{-1}\tan\left(\frac\pi4-z\right)=\frac\pi4-z=\frac\pi4-\frac12\cos^{-1}x^2$$
$$\implies \frac{dy}{dx}=\frac{\frac\pi4-\frac12\cos^{-1}x^2}{dx}=-\frac12\left(-\frac{2x}{\sqrt{1-(x^2)^2}}\right)=\frac x{1-x^4}$$


text:
Q: Akka stream gateway between Kafka and TCP I'm trying to do some Graph with Akka Stream and I encounter some difficult cases. Basically I need to route messages to and from Kafka server and TCP server. The difficult part occurs because I have sometimes to answer the TCP server.

*

*Case 1: TCP -> Kafka (ok)

*Case 2: Kafka -> TCP (ok)

*Case 3: TCP -> TCP

*Case 4: nothing -> TCP
Case 3 occurs when I get some message and had to ask some precisions to the server before publishing it to Kafka
Case 4 occurs to open the TCP connection by sending the first handshake.
I think of feedback loop, Source.actoRef, fan-out but still cannot construct it.
This is mostly the Graph I think about:
                                            +------------------+
                                            |                  |
                                            | TCP msg          |
                                            | (Source.actorRef)|
                                            |                  |
                                            +----+-------------+
                                                 |
                                                 |
+------------+       +-----------------+    +----v----+      +--------------+
|            +------->                 +---->         +------>Kafka (Sink)  |
|   TCP      |       |   TLS           |    | Router  |      +--------------+
|   (flow)   |       |   (bi-dir flow) |    | (???)   |      +--------------+
|            <-------+                 <----+         <------+Kafka (Source)|
+------------+       +-----------------+    +---------+      +--------------+

I think that I need to construct some personalized graph with GraphStage, but miss some referencies. Specially for the Router, which has to able to accept three inputs and forward the answer into 2 different outputs.
If you have any clues I would love it.
Thanks in advance!

A: I finally got it... Here is a sample of my code, if it can help anyone in the
class Msg
  case class Msg1(string: String) extends Msg
  case class Msg2(string: String) extends Msg
  case class Msg3(string: String) extends Msg

def optionFilter[T]: Flow[Option[T], T, NotUsed] = {
  import akka.stream.scaladsl.GraphDSL.Implicits._

val graph = GraphDSL.create() { implicit builder =>
  {
    def partitioner(o: Option[T]) = o.map(_ => 0).getOrElse(1)
    val partition: UniformFanOutShape[Option[T], Option[T]] =
      builder.add(Partition[Option[T]](2, partitioner))

    val flow = builder.add(Merge[T](1))

    partition.out(0) ~> Flow[Option[T]].collect { case Some(t) ⇒ t } ~> flow
    partition.out(1) ~> Flow[Option[T]].collect { case None    ⇒ None } ~> Sink.ignore

    FlowShape(partition.in, flow.out)
    }
  }
  Flow.fromGraph(graph)
  }

val msg1Filter = optionFilter[Msg1]

def router(
  source1: Source[Msg, ActorRef],
  source2: Source[Msg, _],
  sink1: Sink[Msg1, _],
  sink2: Sink[Msg2, _],
  flow: Flow[Msg3, Msg, _]
  ): ActorRef = {
  import akka.stream.scaladsl.GraphDSL.Implicits._

  val graph: Graph[SinkShape[Msg], NotUsed] = GraphDSL.create() { implicit builder =>
    val unzipper: UnzipWith3[Msg, Option[Msg1], Option[Msg2], Option[Msg3]] =
    UnzipWith { msg: Msg =>
      msg match {
        case msg1: Msg1 => (Some(msg1), None, None)
        case msg2: Msg2 => (None, Some(msg2), None)
        case msg3: Msg3 => (None, None, Some(msg3))
      }
    }

  val merge   = builder.add(Merge[Msg](3))
  val forward = builder.add(Merge[Msg](1))

  val unzip = builder.add(unzipper)

  source2 ~> merge ~> unzip.in
  forward.out ~> merge

  unzip.out0 ~> optionFilter[Msg1] ~> sink1
  unzip.out1 ~> optionFilter[Msg2] ~> sink2
  unzip.out2 ~> optionFilter[Msg3] ~> flow ~> merge

  SinkShape(forward.in(0))
}

val sink: Sink[Msg, NotUsed] = Sink.fromGraph(graph)

sink.runWith(source1)
}

val source1 = Source.actorRef(4096, OverflowStrategy.fail)
val source2 = Source(List(Msg2("from source2")))

val sink1: Sink[Msg1, Future[Done]] = Sink.foreach((msg: Msg1) => println(s"sink1: $msg"))
val sink2: Sink[Msg2, Future[Done]] = Sink.foreach((msg: Msg2) => println(s"sink2: $msg"))

val flow = Flow.fromFunction((msg: Msg3) => {
  val msg2 = Msg2("from the flow")
  println(s"flow: forward msg $msg to $msg2")
  msg2
})

val actor = router(source1, source2, sink1, sink2, flow)

actor ! Msg1("from source1 (actor)")
actor ! Msg2("from source1 (actor)")
actor ! Msg3("from source1 (actor)")

Which gives you the following output
sink2: Msg2(from source2)
sink1: Msg1(from source1 (actor))
sink2: Msg2(from source1 (actor))
flow: forward msg Msg3(from source1 (actor)) to Msg2(from the flow)
sink2: Msg2(from the flow)

Hope it helps someone in the future !


text:
Q: XSCRON for scheduling a xsjob I need a XS Cron to schedule a job for every second Tuesday of every month.
I have a Cron which is "* * * tue 12 0 0"; it states that the job is scheduled for every month every tuesday to run at 12.
So Please help.

A: I don't have idea of XS. I hope below cron will work well as per your requirement.
You can validate on https://crontab.guru
"At every minute on every day-of-month from 8 through 14 and on Tuesday."
"* * 8-14 * TUE Your_script_path"

A: Thanks for all you help.
The cron that I am using to schedule my job for every months second Tuesday is
"* * * 2.tue 12 0 0"
Regards,
Renita


text:
Q: How to monitor ArangoDB with Newrelic We're having Newrelic application monitoring in many projects integrating with classical relational databases and mongo and recently started a new project with the ArangoDB as a multi-model graph database.
I cannot find any article on the web having both ArangoDB and Newrelic creatures in the topic.
Did anyone try to monitor a backend application with ArangoDB using Newrelic? Is it possible? Is it difficult?
If anybody knows, please share knowledge, describe available strategies and possible tactics.

A: We have a cookbook, that is meant for integration and monitoring of ArangoDB instances using Prometheus and Grafana.
https://docs.arangodb.com/devel/Cookbook/Monitoring/Collectd.html
There are to ways you could go about this. If you have some experience with Newrelic and feel motivated to adopt the above cookbook to Newrelic, we would not hinder you and help wherever we can.
Or you would go to our github repositpry and file a feature request after having stared us :) there.
In either case, you'd be awesome.


text:
Q: carrot2 Workbench and filter Query fq i need to add clusteringComponent from solr to my application. For tuning the clusteringComponent i use the Carrot2 workbench, which is very useful to find out what ar the right parameters.
The point is: i only like to analyse / cluster new data, which is added at the past 24 hours to the solr/lucene index. For that usually i use an timestemp filed on querytime, like:
....&fq=timestemp:[NOW-24HOUR TO NOW]

The question is: is there a way to add this filter query to the carrot2 workbench as an search parameter?

A: I just checked that currently there is no way to pass extra Solr parameters from the production releases of Carrot2 Workbench. I've already added such a feature, it is available in development builds of Carrot2 Workbench.
If you'd like to stick with production releases of Carrot2, a possible workaround may be configuring the extra fq parameter directly in your Solr request handler.


text:
Q: Derivation of output voltage of a Colpitts Oscillator I have been researching how the oscillations across the Drain and Source terminals of a FET occur when it is switched off. I have come across this explanation that it is due to feedback from parasitic capacitance across the Drain to Source terminals of the FET.
This PDF document I found online (Toshiba - Parasitic Oscillation and Ringing of Power MOSFETs) explains it in more detail stating that the reactances across the terminals of the device act as a Colpitts oscillator.
With all that I have read on the subject of Colpitts oscillator I cannot see how the expression for V2 is derived below:

I watched a video online about how a Colpitt's oscillator can be constructed using an Op amp where a gain applied to the input will permit a continuous (non decaying) sinusoidal output provided that it has the resonant frequency.

Here an expression can be determined simply using the voltage divider rule at the output of the Op-Amp with respect to the Impedance network shown on the left.
I then thought to apply the same logic to the circuit shown in the PDF as follows:

My guess was that I could calculate the Impedance due to the parallel RC combination as follows:

(Please excuse my use of photos to explain my logic. I at present only have my phone to work from and entering formulas etc. is difficult.)
Only it doesn't matter how hard I try to resolve this network to find how this expression is calculated, or repackage my own derivation, I can't make sense of this.
Does anybody see something I'm not seeing?

A: Toshiba's paper doesn't need any random poetry add-on, so forget the idea to mix it randomly with an obscure op-amp catch from the web sea.
Toshiba's paper gives a clear formula for the loop gain v2/v1. I would test it with simulation to be absolutely sure. Or recalculate it. Recalculation is = solve v2 with usual complex phasors and node voltage equations. The current generator outputs current Gm * v1 to passive circuit rd, C1, C3, L2. The circuit needs no equation solving, it's a 2 stage voltage divider. See NOTE2.
Gain v2/v1 is the formula of the output voltage v2 divided by v1 i.e. factor v1 simply removed.
The loop gain should be real exact +1 for pure sinusoidal oscillation. In practice it must be a real number > +1 to get the oscillation started. The amplitude will gradually grow until the signal gets distorted.
To get the oscillation frequency you must solve from the equation of v2/v1 the frequency which makes v2/v1 real. It's elementary complex number algebra (see NOTE1) if the capacitors and inductors are so large that the frequency is so low that the phase lag caused by the slowness of the fet is neglible. Otherwise also Gm should be taken as complex.
NOTE1: The imaginary part of the denominator should be zero, The gain of the fet should be high enough to compensate the attenuation caused by Rd and the real part of the denominator.
NOTE2: Current source -Gm * V1 feeds an impedance, say Za, which has 3 parts in parallel. The parts of Za are 1)Rd, 2)C1 and 3)L2 & C3 in series. The voltage over Za = -Gm * V1 * Za.
The final feedback to the fet i.e. V2 = the output from the voltage divider made of L2 and C3. The input to that voltage divider is the voltage over Za.


text:
Q: didEnterRegion only fired on device wake up I'm using local notifications triggered by iBeacons in my app. It works fine both in foreground and background as long as the iPhone is active, but doesn't trigger didEnterRegion after about 15 minutes of inactivity or reboot.
It then only fires again on wake up of the iPhone with the home button or sleep button, but I want didEnterRegion to "fire" when the iPhone is in a pocket for 15 minutes or more while entering the region as well.
Is this possible? If yes, how?
Background modes > Location updates is disabled
Some code:
.h
@property (strong, nonatomic) CLBeaconRegion *beaconRegion;
@property (strong, nonatomic) CLLocationManager *locationManager;

.m
- (void)start {
    self.beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:@"com.bla.bla"];

    self.beaconRegion.notifyOnEntry = YES;
    self.beaconRegion.notifyOnExit = YES;
    self.beaconRegion.notifyEntryStateOnDisplay = YES;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    [self.locationManager startUpdatingLocation];

    [self.locationManager startMonitoringForRegion:self.beaconRegion];
    [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
    [self.locationManager requestStateForRegion:self.beaconRegion];
}

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}

-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
    [self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
}

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
    NSLog(@"%@", [error localizedDescription]);
}

-(void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region {
    if (state == CLRegionStateInside) {
        [manager startRangingBeaconsInRegion:self.beaconRegion];
    } else {
        [manager stopRangingBeaconsInRegion:self.beaconRegion];
    }
}

A: I'm not sure what is going on here, but the experience described in the question is not consistent with what I have seen testing on multiple devices.  Posting the code that sets this up might help figure out some answers.
In several apps, I have been able to get background didEnterRegion callbacks, even after much more than 15 minutes of inactivity without pressing the shoulder button or the home button.  And to do this, I have not had to set any background modes.  (Apple will actually reject your app if you submit it to the store with background mode Location updates set unnecessarily.)
There is a bug in iOS 7.1 that cam halt iBeacon detections at some point after boot, so perhaps this is what is going on in this case.  Details are here.  Unfortunately, testing this hypothesis would require you to wake up the screen in order to turn bluetooth off and on to clear the condition, and that would wake up your screen and give you the region exit anyway.  Perhaps you could try setting beaconregion.notifyEntryStateOnDisplay=NO, recreating this condition then try cycling bluetooth to see if you then get the notification.  You can also use an off the shelf beacon scanning app like Locate for iBeacon to see if your device is able to range for iBeacons at all after it gets into this state, and only cycle to Bluetooth if you are unable to detect iBeacons.


text:
Q: RequireJS data-main called twice in Phonegap/Cordova platform Windows Phone I'm currently developping a Phonegap app with requireJS.
On iOS et Android platforms, my code is working just fine but on WP8 platform, the main.js file (data-main for requireJS) is called/executed twice.
And then it fires two deviceReady event and executing ajax requests, so this is not good !
I can't seem to find where is the problem.
Here is part of my code.
index.html
   <script src="cordova.js" type="text/javascript"></script>
   <script data-main="js/app/main" src="js/libs/require/require.js" type="text/javascript"></script>

main.js
requirejs.config({
    baseUrl: 'js/app',
     paths: {
         // Libs
         domReady:'../libs/require/domReady',
         jquery: '../libs/jquery/jquery-1.11.0.min',
         knockout: '../libs/knockout/knockout-3.1.0.min',
         kopostbox: '../libs/knockout/knockout-postbox.min',
         sammy: '../libs/sammy/sammy.min',
         amplify: '../libs/amplify/amplify.min',
         moment: '../libs/moment/moment-2.6.0.min',
         underscore: '../libs/underscore/underscore',
         owlcarousel: '../libs/owlcarousel/owl.carousel.min',
         viewport: '../libs/viewport/viewport.min',
         autosize: '../libs/autosize/jquery.autosize.min',
         imagesloaded: '../libs/imagesLoaded/imagesloaded.pkgd.min',
         details: '../libs/details/jquery.details.min'
     },
     shim: {
         jquery: {
             exports: '$'
         },
         knockout: {
             exports: 'ko'
         },
         kopostbox: {
             deps: ['knockout']
         },
         sammy: {
             deps: ['jquery'],
             exports: 'Sammy'
         },
         amplify: {
             deps: ['jquery'],
             exports: 'amplify'
         },
         underscore: {
             exports: '_'
         },
         owlcarousel: {
             deps: ['jquery'],
             exports: 'owlcarousel'
         },
         viewport: {
             deps: ['jquery']
         },
         imagesloaded: {
             deps: ['jquery']
         },
         details: {
             deps: ['jquery']
         }
     }
 });

 require([
        'domReady',
        'app',
        'owlcarousel',
        'ko.customBindingHandlers',
        'viewport',
        'imagesloaded',
        'details'
    ],
    function(domReady, app){
        domReady(function () {
                app.initialize();
        });
  });

At first, I thought of a conflict with cordova but since it's working nicely in iOS and Android, I suppose it can't be.
I've tried removing the data-main attribut and inserting a script tag for main.js but it doesn't change a thing.
If anyone can point me in the right direction, please help !


text:
Q: Como Mostrar Produtos en Ticket Tengo el siguiente codigo para imprimir un ticket, pero me marca error en el dataGridView1, el error es el siguiente( the name dataGridview1 does not exist in the current context) foreach (DataGridViewRow fila in dataGridView1.Rows) lo marca despues de que escribo el foreach
CrearTicket ticket = new CrearTicket();
            ticket.TextoIzquierda(" ");
            ticket.TextoCentro("TICKET CIERRE DE CAJA");
            ticket.TextoIzquierda(" ");
            ticket.TextoExtremos("FECHA : " + txtFechaV.Text, "HORA : " + txtHora.Text);
            ticket.TextoIzquierda(" ");
            ticket.EncabezadoVenta();
            ticket.lineasGuio();
            foreach (DataGridViewRow fila in dataGridView1.Rows)
            {
                ticket.AgregaArticulo(fila.Cells[1].Value.ToString(), int.Parse(fila.Cells[0].Value.ToString()), decimal.Parse(fila.Cells[3].Value.ToString()));
            }

A: Antes de mostrar el otro formulario, puedes tener un método que cargue la información del ticket.
Form2 form2 = new Form2();
form2.LoadTicketInformation(dataGridView1);
form2.Show();

El método LoadTicketInformation recibe el dataGrid y puedes hacer el foreach.


text:
Q: Cannot convert String array to Int array from core data and sum it in Swift 4 I have 2 question. First, I can't convert String array to Int array from core data
let sum = recordFilter.map{$0.amount!.dropFirst()} //["9.99", "6.58"]
let intSum = sum.map({Int($0)})  //[nil, nil]

My array format:
[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), ...})]

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)' How to fix it?
let sum = recordFilter.map{$0.amount!.dropFirst()}.reduce(0, +)
let intSum = sum.map({Int($0)}).reduce(0, +)
//Cannot invoke 'reduce' with an argument list of type '(Int, _)'

A:
First, I can't convert String array to Int array from core data

From the description of init?(_ description: String)

The string passed as description may begin with a plus or minus sign character (+ or -), followed by one or more numeric digits (0-9)

9.99 is an invalid format for an Int which is probably why the map that tries to do the conversion is returning nil for each element.
If you do this:
let doubleSum = sum.map({Double($0)})

You'll get close to what you want but the elements of the array will be optionals.

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)'

The problem is that the constructor returns an optional. One way to fix this would be to unwrap the optionals but make nils zero for the purpose of the addition.
let doubleSum = sum.map{ Double($0) ?? 0.0 }.reduce(0, +)

you'll get what you want. The ?? unwraps the result of the string to double conversion, using 0 where the conversion fails.
Or, even better, as Martin R suggests, you can use flatMap to eliminate the need for ??.
let doubleSum = sum.flatMap{ Double($0) }.reduce(0, +)

A: You should annotate explicit types for your variables to check if you are coding what you think you are. My guess is you are used to dynamic languages; it doesn't work that way here.
recordFilter.map { ... } creates a String, so reduce needs a pair of parameters of types T and (T, String) -> T, respectively. With T == Int, it's looking for +: (Int, String) -> Int which does not exist.
Note that if you fix that, sum is either String or Int (not sure what you want), to neither of which applying map does what you want it to do, by my estimation.


text:
Q: Json aggregation of data with missing values I have a simple table of supplements
create table consumption (
    account bigint not null,
    date date not null,
    supplement text not null check (supplement in ('multiVitamin', 'calMag', 'omega3', 'potassium', 'salt', 'antiOxidant', 'enzymes')),
    quantity integer not null default 0
);

And I want to fetch what people have consumed per day. This would be an exmaple of my desired output
[
    {
        "date" : "2016-01-01",
        "multiVitamin" : 7,
        "calMag" : 0,
        "omega3" : 3,
        "potassium" : 3,
        "salt" : 2,
        "antiOxidant" : 0,
        "enzymes" : 1
    },
    {
        "date" : "2016-01-02",
        "multiVitamin" : 2,
        "calMag" : 1,
        "omega3" : 1,
        "potassium" : 2,
        "salt" : 2,
        "antiOxidant" : 0,
        "enzymes" : 1
    }
]

I'm confused how to get those values into a json object and coalesce so that I return 0 if there aren't any supplements entered for that day. So everyday should return all supplements. This is what I have so far but its very far from complete - it's at least fetching for the dates selected though.
WITH duration_amount AS (
SELECT date_trunc('day', date)::date AS date_group,     json_build_object('quantity', SUM(consumption.quantity) )::jsonb->'quantity' as supplement
FROM consumption
WHERE account = 1667
GROUP BY date_group
)
SELECT DISTINCT date_group, supplement
FROM (
SELECT generate_series(date_trunc('day', '2016-10-20'::date), '2016-10-28'::date, '1 day') AS date_group
) x
LEFT JOIN duration_amount
USING (date_group)
ORDER BY date_group DESC

A: Example data:
insert into consumption values
(1667, '2016-10-21', 'multiVitamin', 1),
(1667, '2016-10-21', 'calMag', 2),
(1667, '2016-10-22', 'multiVitamin', 3),
(1667, '2016-10-22', 'calMag', 4),
(1667, '2016-10-22', 'omega3', 5);

You should prepare a template table containing rows for all possible values. In the example it will contain 14 rows (cross join 2 days with 7 supplements). Next, left join to it your table using coalesce() for missing values:
select
    date_group::date as date,
    supplement_group as supplement,
    coalesce(quantity, 0) quantity
from generate_series('2016-10-21'::date, '2016-10-22', '1 day') as date_group
cross join (
    values
        ('multiVitamin'), ('calMag'), ('omega3'),
        ('potassium'), ('salt'), ('antiOxidant'), ('enzymes')
    ) as supplements(supplement_group)
left join consumption
    on date_group = date
    and supplement = supplement_group
    and account = 1667;

    date    |  supplement  | quantity
------------+--------------+----------
 2016-10-21 | multiVitamin |        1
 2016-10-21 | calMag       |        2
 2016-10-21 | omega3       |        0
 2016-10-21 | potassium    |        0
 2016-10-21 | salt         |        0
 2016-10-21 | antiOxidant  |        0
 2016-10-21 | enzymes      |        0
 2016-10-22 | multiVitamin |        3
 2016-10-22 | calMag       |        4
 2016-10-22 | omega3       |        5
 2016-10-22 | potassium    |        0
 2016-10-22 | salt         |        0
 2016-10-22 | antiOxidant  |        0
 2016-10-22 | enzymes      |        0
(14 rows)

The result can be easily aggregated to jsonb, see the full example here.


text:
Q: intterrupt that checks if a key was pressed and reads which key it was As part of my school project, I am trying to build a snake game. I've managed to draw a pixel and make it move using the a,w,s,d keys as arrows so far. My problem is that instead of my snake moving and changing direction only when a key is pressed, my snake waits for a key press (meaning pausing my whole program) and only then continues to move. From my understanding, I've been using the wrong interrupt (int 16h\00) and I would like to know what other interrupts I can use instead.
I've tried int 16h \01 but all it did was changed direction once and then continued moving in that direction.
this is the part of my code that is in charge of changing my pixel's placement:
      proc check_press

        ; check for a key press
            mov ah,0
            int 16h

        ;check what key
        check_key:
            cmp al,119
            je down
            cmp al,97
            je left
            cmp al,100
            je right
            cmp al,115
            je up
            cmp al, 27
            je escape

        up:
        inc [y]
        jmp bye

        left:
        dec [x]
        jmp bye

        down:
        dec [y]
        jmp bye

        right:
        inc [x]
        jmp bye

        escape:
        mov ah, 0
        mov al, 2
        int 10h

        bye:

    ret
   endp check_press

I would thank anybody with any idea or even if someone has ever written a snake game in assembly it would be a lot of help

A:
I've tried int 16h \01 but all it did was changed direction once and then continued moving in that direction.

Ralph Brown's interrupt list contains a description of nearly all MS-DOS and BIOS interrupts.
The description about int 16h, function 01 on this page says:

...
  Return:
  ZF set if no keystroke available
  ZF clear if keystroke available
  AH = BIOS scan code
  AL = ASCII character
Note: If a keystroke is present, it is not removed from the keyboard buffer
  ...

This means that the function will return a value in AX that represents the value that will be returned when you call function 00 later.
Suppose you press the keys "A", "B", "C" and "D" and you don't call any int 16h function. Later you call function 00 four times. In this case you expect that "A" is returned the first time, "B" the second time, "C" the third time and "D" the fourth time.
If you call function 01 before calling function 00 the first time, the function will always return "A" (although you pressed "B", "C" and "D" later) because function 00 will return "A" when it will be called the next time.
If you don't call function 00, function 01 will return "key 'A' pressed" forever.
You must call int 16h, function 00 if function 01 returned ZF=clear:
  mov ah, 1
  int 16h
  jz noKeyPressed
  mov ah, 0
  int 16h
  ; AX contains information about the key pressed
  ...
noKeyPressed:
  ...

A: Normally you want the snake to move on its own, not to move one block left when you press left.  So you should be setting a direction variable instead of modifying x or y.  Your whole design is built around this press-to-move behaviour, so you'll have to rewrite a lot of it.
You probably want to use non-blocking keyboard reads to check for keyboard input right before a snake update.  Or hook the keyboard interrupt and update a direction variable from there.
You can use hlt to sleep until the next interrupt (e.g. timer or keyboard), then wake up and see if it's time to redraw the snake.
Another option might be drawing the snake from a timer interrupt, but doing a lot of work in an interrupt handler is bad.


text:
Q: How do I set CommandTimeout to Never Timeout in Entity Framework I see a lot of questions about setting a timeout value but none asking about an infinite timeout. We have a stored proc that can take over an hour to stage data for a process. So I was thinking it would be better to just set the CommandTimeout to never timeout. I know there are issues with this approach.
ObjectContext.CommandTimeout
I was reading the MS documentation for CommandTimeout and it doesn't really say anything regarding never timing out so I'm thinking one approach is to just set an arbitrarily high number. Or maybe go with double the average processing time.

A: So according to SqlCommand.CommandTimeout you can accomplish this by setting it to 0. On the documentation you linked, it says it throws ArgumentException if the timeout is less than 0. Have you tried using 0 as the timeout?


text:
Q: PHP Session active after session_start, but not active in function? I'm encountering an issue with sessions that I can't figure out.
I have a class that loads at the start of index.php. (Below code is an excerpt, but is the first code executed).
If the user logs out, I try to destroy the session, at which point I get a "trying to destroy uninitialized session after session_start" error.
If the user does not logout, I access session variables with no problem.
In trying to determine why, I added code to check session_status and found PHP_SESSION_ACTIVE immediately after session_start(), but when I again check session_status within the unsetSession function, right before session_destroy(), I find the session is not active.  How is that possible?
class UserAccess
{
    public function __construct($page)
    {
            session_start();

        if ($page == 'logout') {
            $this->logout();
        } else {
            $this->checkSession();
        }
    }

    private function unsetSession()
    {
        session_destroy();
    }

    private function logout()
    {
         $this->unsetSession();
    }

Index.php:
<?php
define ('BASE_DIR',  __DIR__ . '/');
include("includes/config.php");
include(INCLUDE_DIR . 'autoload.inc.php');

//** Get Target Page
$current_page_uri = HTMLSPECIALCHARS($_SERVER['REQUEST_URI']);
$path = parse_url($current_page_uri, PHP_URL_PATH);
$part_url = explode("/", $path);
$page = end($part_url);

$DB = DB::dbConnection();
$UserAccess = new UserAccess($page);


text:
Q: Google Sheets Script - Select next row + merge range? I'm trying to create a menu list that will add in X number of rows, and merge columns H>M of the new rows added (row by row - not the entire block). I can't work out how to select the active row +1 or active row +2 etc and then move along the appropriate number of cells.
Below is the script I have thus far for the UI and adding the rows, I'm tying myself in knots trying to merge H>M of the new rows I insert!
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Planning Functions')
      .addItem('Add 1 Row', 'add1row')
  .addItem('Add 2 Rows', 'add2row')
      .addToUi();
}

function add1row() {
  var ss = SpreadsheetApp.getActiveSpreadsheet ();
  var ar = ss.getActiveRange().getRow();
  ss.insertRowsAfter(ar, 1);
}
function add2row() {
  var ss = SpreadsheetApp.getActiveSpreadsheet ();
  var ar = ss.getActiveRange().getRow();
  ss.insertRowsAfter(ar, 2);
}

Thanks for any help!

A: Try this:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Planning Functions')
      .addItem('Add 1 Row', 'add1row')
  .addItem('Add 2 Rows', 'add2row')
      .addToUi();
}

function add1row() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var ar = ss.getActiveRange().getRow();
  var mergeRange = sheet.getRange(ar+1,8,1,6);
  ss.insertRowsAfter(ar, 1);
  mergeRange.mergeAcross();
}
function add2row() {
  var ss = SpreadsheetApp.getActiveSpreadsheet ();
  var sheet = ss.getActiveSheet();
  var ar = ss.getActiveRange().getRow();
  var mergeRange = sheet.getRange(ar+1,8,2,6);
  ss.insertRowsAfter(ar, 2);
  mergeRange.mergeAcross();
}


text:
Q: How can I create an overload for this method? I have a class with a method that looks like this:
class Foo
{
public:
    template<typename T>
    void pushItem(std::string name, T& item)
    {
        //Adds item
    }
};
#define pushItem(...) pushItem(#__VA_ARGS__, __VA_ARGS__)

This allows me to write:
int i = 5;
fooObject.pushItem(i);

Instead of:
int i = 5;
fooObject.pushItem("i", i);

How can I overload the pushItem method so that I can pass a string manually if I want to, like this:
int reallyLongVariableName = 5;
fooObject.pushItem("longVar", reallyLongVariableName);

A: Having a macro with a non-all-caps name is a bad, bad idea.
If anything, I would do this: #define WITH_NAME(x) #x, x, and use it as following: fooObject.pushItem(WITH_NAME(i));.

A: You could simply rename the macro (and remove the variadic portion, as it is not needed).
class Foo
{
public:
    template<typename T>
    void pushItem(std::string name, T& item)
    {
        //Adds item
    }
};

#define pushValue(p) pushItem(#p, p)

int i = 5;
fooObject.pushValue(i);

int reallyLongVariableName = 5;
fooObject.pushItem("longVar", reallyLongVariableName);


text:
Q: How to handle long running external function calls such as blocking I/O in Rust?
Editor's note: This question is from a version of Rust prior to 1.0 and uses terms and functions that do not exist in Rust 1.0 code. The concepts expressed are still relevant.

I need to read data provided by an external process via a POSIX file descriptor in my Rust program. The file descriptor connection is kept up a very long time (hours) and the other side passes data to me from time to time. I need to read and process the data stream continuously.
To do so, I wrote a loop that calls libc::read() (readv actually) to read the data and processes it when received. Since this would block the whole scheduler, I'm spawning a task on a new scheduler (task::spawn_sched(SingleThreaded)). This works fine as long as it runs, but I can't find a way to cleanly shut down the loop.
Since the loop is blocking most of the time, I can't use a port/channel to notify the loop to exit.
I tried to kill the loop task by taking it down using a failing linked task (spawn the loop task supervised, spawn a linked task within it and wait for a signal on a port to happen before fail!()ing and taking down the loop task with it). It works well in tests, but the libc::read() isn't interrupted (the task doesn't fail before read finishes and it hits task::yield() at some time.
I learned a lot looking at libcore sources, but I can't seem to find a proper solution.

*

*Is there a way to kill a (child) task in Rust even if it's doing some long external function call like a blocking read?

*Is there a way to do non-blocking reads on a POSIX file descriptor so that Rust keeps control over the task?

*How can I react to signals, e.g. SIGTERMif the user terminates my program? There doesn't seem to be something like sigaction() in Rust yet.

A: *

*According to mozila, killing a task is no more possible, for now, let alone blocking read.

*It will be possible to do so after mozilla/rust/pull/11410, see also my other issue report for rust-zmq erickt/rust-zmq/issues/24 which also depends on this. (sorry about the links)

*Maybe the signal listener will work for you.

A:
Is there a way to kill a (child) task in Rust even if it's doing some long external function call like a blocking read?

No.
See also:

*

*How does Rust handle killing threads?

*How to terminate or suspend a Rust thread from another thread?

*What is the standard way to get a Rust thread out of blocking operations?

Is there a way to do non-blocking reads [...] so that Rust keeps control over the task?

Yes.
See also:

*

*How can I read non-blocking from stdin?

*How do I read the output of a child process without blocking in Rust?

*How can I force a thread that is blocked reading from a file to resume in Rust?

*Force non blocking read with TcpStream

on a POSIX file descriptor

Yes.
See also:

*

*How can I read from a specific raw file descriptor in Rust?

*How do I write to a specific raw file descriptor from Rust?

*How to get tokio-io's async_read for a File handle

*How to asynchronously read a file?

How can I react to signals

Decide your desired platform support, then pick an appropriate crate.
See also:

*

*How to catch signals in Rust

*Is there a way to listen to signals on Windows

*How to handle SIGSEGV signal in userspace using Rust?
Putting it all together
use future::Either;
use signal_hook::iterator::Signals;
use std::os::unix::io::FromRawFd;
use tokio::{fs::File, io, prelude::*};

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

fn main() -> Result<()> {
    let signals = Signals::new(&[signal_hook::SIGUSR1])?;
    let signals = signals.into_async()?;

    let input = unsafe { std::fs::File::from_raw_fd(5) };
    let input = File::from_std(input);
    let lines = io::lines(std::io::BufReader::new(input));

    let signals = signals.map(Either::A);
    let lines = lines.map(Either::B);

    let combined = signals.select(lines);

    tokio::run({
        combined
            .map_err(|e| panic!("Early error: {}", e))
            .for_each(|v| match v {
                Either::A(signal) => {
                    println!("Got signal: {:?}", signal);
                    Err(())
                }
                Either::B(data) => {
                    println!("Got data: {:?}", data);
                    Ok(())
                }
            })
    });

    Ok(())
}

Cargo.toml
[package]
name = "future_example"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
edition = "2018"

[dependencies]
tokio = "0.1.22"
signal-hook = { version = "0.1.9", features = ["tokio-support"] }

shim.sh
#!/bin/bash

set -eu

exec 5< /tmp/testpipe
exec ./target/debug/future_example

Execution
cargo build
mkfifo /tmp/testpipe
./shim.sh

Another terminal
printf 'hello\nthere\nworld' > /tmp/testpipe
kill -s usr1 $PID_OF_THE_PROCESS


text:
Q: Derive density of log of theta when theta follows a uniform distribution I'm learning bayesian and I need to do some proofs that I'm not quite sure I can do. Any help will be very welcome!
If $\theta \text{~Unif}(0,1)$
What's the density of $y = - \log\theta$?
And what's density of $\theta \ (1-\theta)$?
Finally, what's density of $\log (\theta \ (1 - \theta))$?
Thanks

A: All three are similar:
1) $-\log\theta$ is monotonically decreasing on $(0;1]$ from $+\infty$ to $0$, therefore, for $y\ge 0$: $F_{-\log\theta}(y)=Pr\{-\log\theta&lty\}=Pr\{\theta>e^{-y}\}=1-e^{-y}$, and density is $e^{-y}$.
2) $\theta(1-\theta)$ is increasing on $[0;1/2]$ from $0$ to $1/4$, and decreasing on $[1/2;1]$ from $1/4$ to $0$, therefore, for $y\in[0;1/4]$: $F_{\theta(1-\theta)}(y)=Pr\{\theta(1-\theta)&lty\}=1-Pr\{\theta(1-\theta)>y\}=1-Pr\{\theta^2-\theta+y&lt0\}=1-\sqrt{1-4y}$, and density is just the derivative.
3) Similarly. I am pretty sure you can now get it done by yourself.


text:
Q: Scope/Isolate/Prefix angular material scss styles Problem
I want to integrate angular material scss, but scope and isolate it to only apply its styles to my application. I need this, because my angular application will be embedded in a big monolith. Therefore, we need to prefix our applications scss and have it scoped as it could style other parts of the application. The problem is, that if somebody uses the same class names like angular material does, the styles will win by specificity and this is uncontrollable and will lead to bugs.
Our Idea
The styles should be isolated/scoped to just be applied to our <my-app></my-app> tag by prefixing all selectors automatically.
Generated styles should look like this:
my-app .mat-button {}

Current Attempt
Our current attempt is to include it where we need it. It looks like the following:
styles.scss
@import "~@angular/material/theming";

my-app {
  @include mat-core();
  @import "~@angular/material/prebuilt-themes/deeppurple-amber";
}

The Problem with this solution is, that the scoping is applied to some classes, but not to all.
Demo/Showcase
I created a demo on stackblitz as showcase.
You can see the problem in the in the following screenshot:

Is there another option to have angular material styles isolated/scoped?

A: The styles applied are still within the project.. If you want some app-wide styles that should not be in the top-level styles.scss, put them in app.component.scss and make sure that all other components are children of app.component.ts. Angular scopes (s)css files to its related component by default.


text:
Q: The method openOrCreateDatabase(String, int, null) is undefined for the type DataBase I'm having trouble creating a class that create and manipulate the database! But the method create () has a problem saying

"The method openOrCreateDatabase(String, int, null) is undefined for
  the type BancoDeDados".

Anyone have any suggestions to overcome this problem? My code is as follows:
package com.example;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class DataBase{
     private SQLiteDatabase db;
     private String DATABASE_NAME;
     private String TABLE_NAME;
     private String SQL_SELECT_ALL;
     private String SQL_SELECT_ID;
     private String SQL_CREATE;

     public DataBase(SQLiteDatabase db,String DATABASE_NAME,String TABLE_NAME,String SQL_SELECT_ALL,String SQL_SELECT_ID,String SQL_CREATE){
         this.db = db;
         this.DATABASE_NAME = DATABASE_NAME;
         this.TABLE_NAME = TABLE_NAME;
         this.SQL_SELECT_ALL = SQL_SELECT_ALL;
         this.SQL_SELECT_ID = SQL_SELECT_ID;
         this.SQL_CREATE = SQL_CREATE;
     }

     public void create(){
         this.db = openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE,null);
         this.db.execSQL(this.SQL_CREATE);
         this.db.close();
     }
}

A: SQLiteOpenHelper is used to create a database in Android.
You need to override the onCreate method after extending this class.
db.execSQL(TABLE_CREATE); in onCreate creates the database.
TABLE_CREATE is your DDL String.
public class DbHelper extends SQLiteOpenHelper {

     //The database name and version can be parameterized in the constructor.
     public DbHelper(Context context, String databaseName, int databaseVersion) {
         super(context, databaseName, null, databaseVersion);
     }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
     * .SQLiteDatabase)
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

        try {
            // Create Database
            db.execSQL(TABLE_CREATE);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
     * .SQLiteDatabase, int, int)
     */
    @Override
    public void onUpgrade(SQLiteDatabase arg0, int oldVersion, int newVersion) {

    }

}

A: The main reason to create this class to create and manipulate database is repackage it and besides this class EXTENDS NO need no other!

Under My class after you solve the problem '.
  DataBase.java`

 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;

 public class DataBase{
 private String DATABASE_NAME;
 private int DATABASE_VERSION;
 private String TABLE_NAME;
 private String SQL_SELECT_ALL;
 private String SQL_SELECT_ID;
 private String SQL_CREATE;

 public DataBase(String DATABASE_NAME,int DATABASE_VERSION,String TABLE_NAME,String SQL_SELECT_ALL,String SQL_SELECT_ID,String SQL_CREATE){
     this.DATABASE_NAME = DATABASE_NAME;
     this.DATABASE_VERSION = DATABASE_VERSION;
     this.TABLE_NAME = TABLE_NAME;
     this.SQL_SELECT_ALL = SQL_SELECT_ALL;
     this.SQL_SELECT_ID = SQL_SELECT_ID;
     this.SQL_CREATE = SQL_CREATE;
 }
 public DataBase(String DATABASE_NAME,int DATABASE_VERSION,String TABLE_NAME,String SQL_SELECT_ALL,String SQL_CREATE){
     this.DATABASE_NAME = DATABASE_NAME;
     this.DATABASE_VERSION = DATABASE_VERSION;
     this.TABLE_NAME = TABLE_NAME;
     this.SQL_SELECT_ALL = SQL_SELECT_ALL;
     this.SQL_CREATE = SQL_CREATE;
 }

public void onCreate(Context ctx,SQLiteDatabase db){
     db = ctx.openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE, null);
     db.execSQL(this.SQL_CREATE); //Criando tabela caso não exista!!
     db.close();
 }

public void onUpgrade(Context ctx,SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + this.TABLE_NAME);

    // Create tables again
    onCreate(ctx,db);
 }

 public long onWrite(Context ctx,SQLiteDatabase db,String row,ContentValues ctv){
     db = ctx.openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE,null);
     long lg = db.insert(this.TABLE_NAME,row,ctv);
     db.close();
     return lg;
 }

 public int onUpdate(Context ctx,SQLiteDatabase db,ContentValues ctv,String row,int id){
     db = ctx.openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE,null);
      int x = db.update(this.TABLE_NAME, ctv, row, new String[]{String.valueOf(id)});
     db.close();
     return x;
 }

 public Cursor onSelecAll(Context ctx,SQLiteDatabase db){
     db = ctx.openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE,null);
     Cursor cursor = db.rawQuery(this.SQL_SELECT_ALL, null);
     return cursor;
 }

 public Cursor onSelecId(Context ctx,SQLiteDatabase db,int id){
     db = ctx.openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE,null);
     Cursor cursor = db.rawQuery(SQL_SELECT_ID, new String[]{String.valueOf(id)});
      return cursor;
  }

 public int onDelete(Context ctx,SQLiteDatabase db,String row,int id){
     db = ctx.openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE,null);
     int x = db.delete(this.TABLE_NAME, row, new String[]{String.valueOf(id)});
     db.close();
     return x;
 }

 public void onClose(Context ctx,SQLiteDatabase db){
     db = ctx.openOrCreateDatabase(this.DATABASE_NAME,Context.MODE_PRIVATE,null);
     db.close();
 }
  }

And in Main.java:

     import android...
     public class Main extends Activity {

 private SQLiteDatabase db;
 private Context ctx;
 private static final int DATABASE_VERSION = 1;
 private static final String DATABASE_NAME = "database.db";
 private static final String TABLE_NAME = "table";
 private static final String SQL_SELECT_ALL = "SELECT * FROM "+TABLE_NAME;
 private static final String SQL_SELECT_ID = "SELECT * FROM table WHERE _id = ?";
 /* SQL de criação do banco de dados. */
 private static final String SQL_CREATE = "CREATE TABLE IF NOT EXISTS table(" +
                    "_id INTEGER PRIMARY KEY, " +
                    "person VARCHAR(30), "
                    "animal VARCHAR(30))";
 BancoDeDados BD = new BancoDeDados(DATABASE_NAME,DATABASE_VERSION,TABLE_NAME,SQL_SELECT_ALL,SQL_SELECT_ID,SQL_CREATE);
  @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ctx = getBaseContext(); //Context to use in class BancoDeDados
    BD.onCreate(ctx, db); // Create BD and table if needed!!
   /* .... */
 }
}


text:
Q: PostgreSQL serialize data as in PHP In my database,  I've got a field where are stored data serialized in PHP by serialize() function.
I have to prepare a function in PostgreSQL that inserts data into this field, so it is required to serialize the data before the insert. Is in pgSQL any equivalent function to PHP serialize()?


text:
Q: sshfs with different gid on remote I don't know how to mount a remote directory
"remote_dir" on computer "remote", having remote gid "wgrp".
Help is welcome.

  me@local$ sshfs me@remote:/remote_dir remote_as_wgrp ...wanted_options...

A workaround is to create a new user "me_wgrp" belonging to group "wgrp".
But the problem seems conceptually so simple that I'm sure there is a solution.
Context:
I'm able to connect using ssh on remote compute, and then to change my gid:

  me@local$ ssh me@remote
  me@remote$ newgrp wgrp

Now I can create files in directories which are only writable by the group "wgrp".
I have tried

  sshfs me@remote:/remote_dir remote_as_wgrp -o ssh_command='newgrp wgrp'

but sshfs seems blocked.
Also, if I try

  ssh me@remote 'newgrp wgrp'

ssh doesn't give the prompt, but it accepts commands.

A: You should consider changing the default group on the remote host has newgrp will never return because it opens a new shell.
"newgrp - return you to a prompt of a new shell."

A: unfortunately it looks like newgrp group, or "newgrp group -" causes sshfs to not work in the newgrp environment. You won't be able to cd into the sshfs directory or ls, basically you'll get a permission denied error (and it's not due to permissions issues). You'll also notice that df no longer shows the sshfs fuse mount.

A: Ten years after the question was asked, I needed this myself.
I found that it is now possible to add a parameter to sshfs:
sshfs -o sftp_server="sg <group> -c '/usr/lib/misc/sftp-server -u <umask>'" ...

where /usr/lib/misc/sftp-server is the location of sftp-server on the remote system, <group> is the desired group on the remote system, and -u <umask> is an optional way of providing a default umask for the particular sftp-server.


text:
Q: JS error when I set an object property to Nested property, a function, or an array Very new to JS using VSCode trying out examples in tutorials. Ran into this error when I and setting an object's properties. The first properties such as firstname, lastname, and age seem to log fine, however when I try to use an array, a function or nested properties, as a property of the object I get an error and it will not log to console.
The error is:

" "." expected. (TS1005)

Please advise, total noob but trying hard to learn more so please forgive my ignorance at this point.

   var person = {
       firstname: 'Matilda',
       lastname:'Milner',
       age: 68
       kids: ['Dave', 'Lynn', 'Cal', 'August', 'Cade'],
       location: {
                street: '500 Some St.',
                city: 'Inola',
                state: 'Oklahoma',
                zip: '66702',
                }

        fullname: function(){
           return this.firstname + " " + lastname;
        }
   }
   console.log(person.firstname +" "+person.lastname + " " +"is"+ " " + person.age+ " "+ "years old");
   console.log(person.kids[3])
   console.log(person.address.zip)

A: There are few syntax errors in your code

*

*You missed , at lots of places in your object definition.

*You missed this before lastname in your fullname function

*You don't have any property called address but you're trying to access person.address.zip

var person = {
       firstname: 'Matilda',
       lastname:'Milner',
       age: 68,
       kids: ['Dave', 'Lynn', 'Cal', 'August', 'Cade'],
       location: {
                street: '500 Some St.',
                city: 'Inola',
                state: 'Oklahoma',
                zip: '66702',
                },

        fullname: function(){
           return this.firstname + " " + this.lastname;
        }
   }
   console.log(person.firstname +" "+person.lastname + " " +"is"+ " " + person.age+ " "+ "years old");
   console.log(person.kids[3])
   console.log(person.location.zip)
   console.log(person.fullname())


text:
Q: Unusual behaviour of "\r" character in java I typed tried to use implement the backslash character '\r' in java code  by using the following statement on my IntelliJ Ide compiler
 System.out.print("This  message will self destruct in five seconds\r");
    try {
        Thread.sleep(5000);
    }
    catch (InterruptedException e){

    }
    System.out.print("Bye");

The output which I got was as:
...five seconds and then on the same line "Bye"

But the expected output must have been as:
"This  message will self destruct in five seconds"...after five seconds on
the beginning of the same line "Bye" only

But If I type the following the same code snippet as:
System.out.print("This  message will self destruct in five seconds");
try {
Thread.sleep(5000);
}
catch (InterruptedException e){

}
System.out.print("\rBye");

then I get the above mentioned desired output.Why is this happening I really have no clue...The very first code gives the output on https://www.jdoodle.com/online-java-compiler as:
This  message will self destruct in five seconds
Bye

I am really confused please help.


text:
Q: Not getting data in ng-view tabs on using ngRoute.? I am getting some strange url like this
http://localhost/bootstrap/aroute/index.html#!#%2Fstudent instead of
http://localhost/bootstrap/aroute/index.html#/student and also not getting the data on the page from templates.
My angular code is like this
`function RouteConfig($routeProvider){
        $routeProvider
            .when('/home',{

            templateUrl : 'home.html',
                controller : 'MainController'
            })
            .when('student',{
                templateUrl : '/student.html',
                controller : 'MainController'
            })
            .when('courses',{
                templateUrl : '/courses.html',
                controller : 'MainController'
            });
    }`

A: Include $locationProvider.hashPrefix(''); in your config.
function RouteConfig($routeProvider,$locationProvider){
        $locationProvider.hashPrefix('');
        $routeProvider
            .when('/home',{
            templateUrl : 'home.html',
                controller : 'MainController'
            })
            .when('student',{
                templateUrl : '/student.html',
                controller : 'MainController'
            })
            .when('courses',{
                templateUrl : '/courses.html',
                controller : 'MainController'
            });
    }


text:
Q: Access to global JS variables without owning the page overflow community,
I've read several posts trying to solve the problem, but they dont answer my question.
Is there any legal way to find out what events (?) another site sends?
I dont ask because of illigal buissness and i am ready to find out more myself as soon as i know what i realy have to look for  in terms of topic and methods.
In particular its about advertising and finding out if someone registered on another via a referal link. Like a sign that is sent as soon as the    registration (on the other site which is not mine) is completed.
I want to find this out during the visit of the client on my site.
I just need to know if such a thing is legally possible and what JS topics i should give a go to find out more.
I hope my post is comprehensible enough. :)
edit: It's not about global variables.

A: You can use your browser's developer tools to see what's happening behind your back while you're visiting a web page (I recommend Firebug in Firefox). Alternatively, you may use a network spoofer like Wireshark to capture the traffic from the browser and analyze it in any way.
It's all up to you to find the information you think is relevant inside it in URLs, in request headers and bodies, etc. In your case, this would include script generated content and referal codes that may help keeping track of a user's browsing history across domains.
You don't really need Javascript knowledge to do this, but you need some basics about networking protocols.
This is probably as illegal as using a text editor, but just ask your lawyer if you're unsure :D


text:
Q: If don't see the picture after successful upload django project in heroku server then how can i solve this problems? I have uploaded my django project in heroku server and everything working properly but when i use in settings file DEBUG=False only  this time images are not visible.
If i use DEBUG=True then visible images but if i use DEBUG=False then start problem.
This is Settings file
import django_heroku
import os
import environ
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')

env = environ.Env(
    DEBUG=(bool, False),
    ALLOWED_HOSTS=(list),
)
envfile_path = os.path.join(BASE_DIR, '.env')
environ.Env.read_env(envfile_path)

DEBUG = env('DEBUG')

SECRET_KEY = env('SECRET_KEY')

ALLOWED_HOSTS = env('ALLOWED_HOSTS')

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

THIRTPARTY_APP = [
    'django_filters',
    'corsheaders',
    'rest_framework',
    'rest_framework.authtoken',
]

LOCAL_APP = [
    'protfolio.apps.ProtfolioConfig',
]

INSTALLED_APPS += THIRTPARTY_APP+LOCAL_APP

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000/'
    'http://10.100.68.37:3000/'
    'http://127.0.0.1:8000/'
)

ROOT_URLCONF = 'backapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backapp.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.postgresql_psycopg2',
        'NAME': env('DATABASE_NAME'),
        'USER': env('DATABASE_USER'),
        'PASSWORD': env('DATABASE_PASSWORD'),
        'HOST': env('DATABASE_HOST'),
        'PORT': env('DATABASE_PORT')
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfile')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

REST_FRAMEWORK = {

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),

    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),

    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
}

django_heroku.settings(locals())


text:
Q: String, rod and inertia I was recently reading through some posts on this site. A question struck me -
Why does an object attached to the end of a string which is further attached to an accelerating car behave differently than it would if the object is attached with a rod welded to the roof?
P.S.- Apparently there is a misunderstanding with my question. What I mean by 'differently' is that the object when attached through a string tries to remain in rest, but then accelerates with the car (inertia), causing the string to make an angle $\theta$ with the vertical, whereas it is not the case when the object is attached through a rod, i.e., the rod always make $0^\circ$ with the vertical.

Edit - I have added a picture, if that helps...

A: I understand I have not understood the question right when I answered the following:

Because of inertia. If no forces are acting on an object, the objects velocity does not change. Using a string the car accelerates the object to a certain velocity and when slowing down the object will continue to move towards the car as no forces are acting on it (until it hits the car where the normal force of the mass of the car slows it down at once). Using a rod the object again accelerates with the car as it is tied to it. But when the car slows down, the normal force of the mass of the car immediately acts on the object thrue the rod, slowing down the object at the same time as the car slows down.

Second Try:
If I understood correctly what is meant here, the reason for the object making an angle to the "vertical" is simply inertia and the fact that it the string has a finite length: The object (attached outside of the car on the ceiling or inside on the ground) wants to stay at rest but is accelerated. The only way to stay as much at rest as possible is to move down (in addition to moving to the opposite side of the acceleration relative to the car) and thus making that angle.
If you meant horizontal instead of "vertical" (the object being attached to the back of the car outside) then the reason is chaos of aerodynamics. Aerodynamics predicts that the object moves in every direction, despite being dragged back by inertia and thus making that angle. But I'm not that familiar with aerodynamics and am therefor not able to give you more details. What I do understand is that when using a fixed rod welded to the car, the object has no degree of freedom whatsoever. Its position is completely determined by the car. A string gives the object all three degrees of freedom $(r,\theta,\varphi)$, inspite of some boundaries: $r\le L$ (length of string), $\varphi\in [0,\pi]$ (object can't go into the car), $\theta\in [0,\pi]$ (boundaries for $\theta$ are normal). Having these degrees of freedom the chaotic consequences of aerodynamics act on the object.

A: Alright then. Imagine you find yourself on a bus. There is a string hanging from the ceiling. Next to the string, a rod is welded to the ceiling. I think you agree that the string is movable in all directions while the rod is not (unless you attach the rod to a flexible joint).
Now attach a mass to the end of the string and one to the end of the rod. Can you see it? The bus starts to accelerate. The passengers feel themselves pushed to the seat they are in. Just so, both masses feel a force directed to the rear of the bus. The mass on the string is free to move (within the confine the string imposes) and the string will make an angle with the vertical direction. This angle depends on the value of the mass attached. The higher the mass, the smaller the angle (the force of gravity, which pulls the mass down gets bigger). The mass on the rod will not be able to move because the rod is welded to the ceiling. Only if the rod can move in the way the string can move, both the string and the rod will make an angle with the vertical upon acceleration.
Do you get me?


text:
Q: Send custom error message, with serverless-http (express) I need to send custom error message in JSON format, from my express app, served in a lambda function using serverless-http
Please correct me if i got it wrong, but as i understand it, we need to use LAMBA_PROXY APIG integration to be able to send custom error messages defined directly from a lambda function.
This is what i have tried so far:
res.status(400).json({ message: 'email already taken' });

serverless.yml
functions:
  auth:
    handler: src/express/auth/index.handler
    name: ${self:service}-auth-${env:STAGE}
    # warmup: true
    integration: lambda-proxy
    memorySize: 128
    timeout: 15
    events:
        - http:
            path: /auth/
            method: ANY
            cors: true
        - http:
            path: /auth/{any+}
            method: ANY
            cors: true

this is what the API is returning(with status code 400)
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Error</title>

Bad Request

Any leads, on how I can send a custom response, in JSON format?
update:
After more tests, I found out that calling next(error) doesn't reach the last error handler

const register = async (req, res, next) {
  try {
    await verifyEmail(req.body.email);
    const user = await Users.register(req.body);
    const token = sign(user.attrs, {});
    res.json({ token, user });
  } catch (e) {
    next(e);
  }
};

const generalError = async (err, req, res, next) => {
  // doesn't reach this part! :(
  console.log('generalError handler', JSON.stringify(err));
  res.status(errorOut.status).json(errorOut);
};

ApiRouter.post('/register', register);
app.use('/auth', ApiRouter);
app.use(generalError);

A: (I just answered a very similar question here)
Yes, this is explained in the Express docs under Error Handling.

Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack.
If you pass an error to next() and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment.

To override this handler, refer to the section in the Express docs titled Writing error handlers.
It explains:

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next). For example:
app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

You define error-handling middleware last, after other app.use() and routes calls

So in your case, if you wanted to respond with a 400 and some JSON, you might write something like this:
const serverless = require('serverless-http');
const express = require('express');
const app = express();

// Your middleware and other routes here
app.use(/* register your middleware as normal */);

// Finally, your custom error handler
app.use(function customErrorHandler(err, req, res, next) {
   res.status(400).json({ message: 'email already taken' });
});

module.exports.handler = serverless(app);


text:
Q: Is it possible to get a div's position when the `document.readyState` is still `interactive` (using React.js)? I have two DIVs and the first DIV's position and height depends on the second DIV's position. Provided the second DIV will not change its position after it is rendered, I want to (and must) get the second DIV's position immediately after it is rendered, so that I can set the attributes of the first DIV and let the first DIV renders correctly, and just in time. (The actual page is huge and complicated and sorry I can only describe the relating details here. In short, this is a mobile page, it is re-rendered using some rem auto calc logic and every position is calculated after the related DOM is rendered.)
I've tried this (using React.js):
Add a props to the first DIV named ready-state, whose value is set to the document.readyState value.
I thought when the document.readyState change into interactive stage (the second div is rendered out), the first DIV will be re-rendered correctly.
But the truth is, I don't know which event should I listen to, so I just listened to the readystatechange event on document. That makes a time gap between the render time of the second DIV and the first DIV.
My page will block for some time after the document.readyState changed to interactive. During this time the second DIV is already rendered but the first DIV's props can not be set yet. Only when the blocking stage ended can the first DIV get the node reference to the second DIV by document.getElementById('second-div').
I can get reference to #second-div by listening to the readystatechange event when the document.readyState is completed. But it is too late. (which makes the time gap)
The question is:
Is it possible to get a DIV's position when the document.readyState is still interactive? (Because I found the DOM node of #second-div is already rendered and positioned, need not wait until the readyState changed to complete.)


text:
Q: Ocultar elementos de página web en WebView - Android Studio - Java Buen día estimados.
Tengo una aplicación android que muestra por un webview una página. Pero la página web tiene muchos elementos que no quiero mostrar y es por eso que los oculto de la siguiente manera:
  webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
               view.loadUrl ("javascript:(function() { "+"document.getElementsByClassName('td-header-wrap td-header-style-1 ')[0].style.display='none'; "+ "document.getElementsByClassName('td-fix-index ')[1].style.display='none';  "+"document.getElementsById('td_uid_1_5ff8cc46439eb ')[0].style.display='none'; "+"document.getElementsByClassName('td-fix-index ')[0].style.display='none';  "+"document.getElementsByClassName('tdm-mobile-full')[0].style.display='none'; "+"document.getElementsByClassName('td-fix-index ')[0].style.display='none'; "+"} )()");

  }

¿Es posible mediante una función de javascript indicar solo lo que debe mostrarse y no indicar lo que hay que ocultar?


text:
Q: How do you retrieve an accidentally deleted point in an ArcGIS Web Mapping Application? Hypothetical scenario: I've shared an ArcGIS Web Mapping Application with non-tech-savvy staff members. One of the staff members accidentally deletes a point within the Web Mapping Application.

*

*Is it possible to undo this operation within the Web Mapping Application?

*If not, Can I retrieve the data from the linked database?

A: As far as I know, and we have run into this problem before, you can not undo this operation in AGO (if anyone has other information I would love to hear it.)  Our solution was to create a versioned environment with the AGO web edits occuring on a child version of the GDB.  That way if field crews screw up some data, which happens more often than you would think, we could easily replace that data with the parent version and go from there.  Here is some data on how to setup versioning, of course this would require ArcSDE.
http://resources.arcgis.com/EN/HELP/MAIN/10.1/index.html#//003n000000t7000000
http://www.esri.com/news/arcuser/0110/versioning101.html


text:
Q: Slack Markdown for Links Are Not Resolving What am I doing wrong? None of the example Markdown links work so far in my Slack app.
I pasted in the example below in a chat in my Slack app. I got this example from slack markdown syntax and it still treats it as literal text in the Slack App:
[like this](http://someurl)

so I end up seeing that instead of just "like this" as a link in Slack chat.
Or maybe the above is wrong, in which case my question would then be how do you do explicitly create links in Slack? I want some text that I specify to be clickable to a specific URL (hyperlink).

A: Reuben's answer will work, but it will look like an untitled file upload, as seen here: untitled file posted to Slack. With a slight modification, however, you can easily post a natural looking message featuring a working hyperlink such as you see here: natural looking Slack post with hyperlink by using the chat.postMessage Slack api method instead of "files.upload" and adopting Slack's own message formatting instead of Markdown. That would be done like this:
curl -F text="*<https://someurl|like this>*" -F as_user=true -F link_names=true -F channel=C1.....7L -F token=xoxp-... https://slack.com/api/chat.postMessage

The link_names=true argument isn't used in this example, but is useful to be able to @mention users and #refer to channels.

A: As of August 2021 this feature is finally enabled for markup mode in slack app. Enable markup mode in Preferences -> Advanced -> Input options -> Format messages with markup.
https://slack.com/help/articles/202288908-Format-your-messages#markup
Surround text with brackets, then surround the link with parentheses:
[your text](the link)

A: As an alternative to Slack Messages (covered in Wilhem's answer), you can create Slack Posts via the API and use at least some Markdown. These both create
like this
:
curl -F filetype=post -F content="# [like this](https://someurl)" -F channels=C1.....7L -F token=xoxp-... https://slack.com/api/files.upload

or swap content="..." for file=@post.md
curl -F filetype=post -F file=@post.md -F channels=C1.....7L -F token=xoxp-... https://slack.com/api/files.upload

This is using files.upload. I think the easiest way to try posting as yourself is with a legacy token. Get the channel ID from the URI of the channel.

A: My markup setting was disabled, once I've enabled it (Preferences -> Advanced -> Format messages with markup) it worked.

A: This is not yet supported by Slack for direct messages, you can only do this using Slack API. But you can upvote the feature request I have submitted here.

A: As of today, 2020.02.14, in one of the Slack instances I'm a member in, I can create/paste hyperlinks!

Example pasting hyperlink from copy Teams meeting info into Slack:

Slack has updated their documentation.  Still no markdown way of doing it though , i.e.  [blah](https://stackoverflow.com) doesn't work.

Neat feature, select some text and CTRL + V when a URL is on the clipboard and it creates a hyperlink

Through some reverse engineering I was able to put text on the Windows Clipboard via C# and get it to paste into Slack:
var textToDisplay = "Test";
var url = "https://stackoverflow.com";
var arbitraryText = "Mike D.";
var dataObject = new DataObject();
//to my surprise, the Fragment comments ARE required
dataObject.SetData(DataFormats.Html, @$"

    {textToDisplay}

    ");
//have to set the Text format too otherwise it won't work
dataObject.SetData(DataFormats.Text, arbitraryText);
Clipboard.SetDataObject(dataObject);

A: Slack uses their own flavor of markdown:
Slack Markdown Links work in the following way: <http://someurl|like this>
Note: You can only do this via the Slack API and NOT just as a simple message you send via the Slack client.
Message Builder Example

More Info in the Docs

A: If you are using slack-bot or something that uses Slack API, you'll be able to use mrkdwn syntax for your messages.
<http://www.example.com|This message is a link>

Reference: https://api.slack.com/reference/surfaces/formatting

A: I wrote this code to convert markdown links within a body of text into the link format slack expects:
// Pretty hacky, convert [sup](http://example.com) to <http://example.com|sup>
const reformatLinks = /\[(.*?)\]\((.*?)\)/g
const slackBody = body.replace(reformatLinks, (_m, text, url) => `<${url}|${text}>`)

From what I can tell slack does not support image links inside text.

A: Slack currently does not support hyperlinks; see this link which says:

Note: It's not possible to hyperlink words in a Slack message.

UPDATE:
Slack has finally added this functionality to their chat interface (source):

*

*Select text, then click the  link icon in the formatting toolbar

*Select text, then press Cmd+Shift+U on Mac or Ctrl+Shift+U on Windows/Linux.

  Copy the link you'd like to share and paste it in the empty field under Link, then click Save.

A: None of the markup in the other answers here (Markdown, , etc.) works anymore.
If you're composing by hand, there's something that to me is better than the keyboard shortcut in the docs (since that shortcut conflicts with global defaults on Linux and is a pain to work around).
Copy your URL to the clipboard, then select the text you'd like to be the anchor text, and just paste the URL as if you were going to replace the selected text with the URL.  Slack instead automatically turns the selected text into a link.

A: Had a problem with this form of markdown when the url is involving a vertical bar |
solved this with urltext.replace("|", "%7C")

A: Following spottedmahn's answer, here's how I got it working in Javascript. Note that for Firefox, the user needs to enable a flag for this to work.
a.addEventListener("click", function() {
    var textToDisplay = "foo";
    var url = "https://stackoverflow.com";
    var message = `

    ${textToDisplay}

    `;
    const htmlBlob = new Blob([message], {type : 'text/html'});
    const textBlob = new Blob(["sda"], {type : 'text/plain'});

    const cbi = new ClipboardItem({
        ['text/html']: htmlBlob,
        ['text/plain']: textBlob
    });
    navigator.clipboard.write([cbi]);
});

A: Super late to the party but I recently discovered that you can use a URL shortener to create a https link which you can then reference using markdown links.


text:
Q: Unable to run query:You have an error in your SQL syntax I am getting variables substituted by Ajax through selection, and then these variables are being used in php file. The variable values are displayed well,but when used in Sql Qyery it gives error like: Unable to run query:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-part WHERE BANK = 'State Bank of Mysore ' AND STATE = 'Maharashtra' AND ADDRESS' at line 1.

This is my code:
$sql="SELECT * FROM bankifsc-part
 WHERE BANK = '$bank'
AND STATE = '$state' AND ADDRESS LIKE '%$city%'";

A: You have to put the table name in ``:
$sql="SELECT * FROM `bankifsc-part`
 WHERE BANK = '$bank'
AND STATE = '$state' AND ADDRESS LIKE '%$city%'"

A: You need to put the table name in back ticks `` as the table name contain hyphen.
$sql="SELECT * FROM `bankifsc-part`
 WHERE BANK = '$bank'
AND STATE = '$state' AND ADDRESS LIKE '%$city%'";

In MySQL, use the back-ticks. In standard SQL, use double-quotes.


text:
Q: IOS get notified when UI updates. I have a custom keyboard extension. This function is called when the delete key is pressed:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
            {
                for _ in 1..<50
                {
                    (self.textDocumentProxy as UIKeyInput).deleteBackward()
                }
                print("Deletion End")
                self.deleteCounter = 0
        })

I do not think the dispatch_async is relevent but I included it, just incase.
The problem is that even though my console prints "Deletion End" once the loop is finished, the UI of the textfield does not update until a second or two has passed.
It seems calling
(self.textDocumentProxy as UIKeyInput).deleteBackward()

Does not immediately delete a character and update the UI.
How can I be notified when the UI is actually updated?

A: Change like this:
dispatch_async(dispatch_get_main_queue(),{
                for _ in 1..<50
                {
                    (self.textDocumentProxy as UIKeyInput).deleteBackward()
                }
                print("Deletion End")
                self.deleteCounter = 0
        })

Explanation:
The UI must work in the Main thread so when you work with the background queue you always have to dispatch in main queue the UI updates.


text:
Q: How can I compute an ANOVA for this mixed-design experiment for error rate? Using the data frame below, I managed to compute a repeated-measures ANOVA for subject reaction time.  Here is the data frame in question:
> str(a)
'data.frame':   2778 obs. of  9 variables:
 $ Phase    : Factor w/ 1 level "Test": 1 1 1 1 1 1 1 1 1 1 ...
 $ Subject  : Factor w/ 17 levels "1","2","3","5",..: 7 7 7 7 7 7 7 7 7 7 ...
 $ Group    : Factor w/ 2 levels "Attn","Dist": 1 1 1 1 1 1 1 1 1 1 ...
 $ Global   : Factor w/ 2 levels "D","S": 1 1 1 1 1 1 1 1 1 1 ...
 $ Local    : Factor w/ 2 levels "D","S": 1 1 1 1 1 1 1 1 1 1 ...
 $ trialtype: Factor w/ 1 level "Dist": 1 1 1 1 1 1 1 1 1 1 ...
 $ RT       : num  477 682 720 NaN 604 720 910 707 705 758 ...
 $ ACC      : logi  TRUE TRUE TRUE FALSE TRUE TRUE ...

And here is the code I used to compute the ANOVA for the reaction times:
raw<-read.table('R_notarg_noattn.tdf',header=T)
head(raw)
str(raw)
raw$Subject = factor(raw$Subject)

raw$logrt = log10(raw$RT)  # logorithm of RT
hist(raw$logrt)

tsttrl_nooutliers = subset(raw, logrt>2 & ACC==TRUE)  # take values greater than 2 logs AND where subj responded correctly
attach(tsttrl_nooutliers)  # make column names available as global variables
hist(logrt)
summary(aovrt <- aov(logrt ~ Group*Global*Local + Error(Subject/(Global*Local)), subset=Phase=='Test', data=tsttrl_nooutliers))  # ANOVA table

meanrt=10^tapply(logrt,list( Global=Global, Local=Local, Group=Group), mean)  # de-log and calculate means by condition

par(mfcol=c(1,2))  # c() *combines* values into vector/list; par() sets graphical parameters... equivalent to Matlab's set() ????
barplot(meanrt[,,'Attn'],beside=T,ylim=c(700,1000),xpd=F)
barplot(meanrt[,,'Dist'],beside=T,ylim=c(700,1000),xpd=F)

detach(tsttrl_nooutliers)

I'd like to repeat a similar analysis on the error rates, which are coded in the boolean column ACC.  I was wondering how I should go about doing this, since this computation requires the intermediate step of calculating error rates by subject per condition.  When I say "condition", I mean to say the unique combination of factors, i.e. $Group, $Global, $Local, $trialtype (selecting only trials where $Phase == Test, as in the previous snippet).
Could anybody point me in the right direction?  In short, I'm unclear on how to obtain the error rates, which I then should have no problem feeding into the aov function.

A: I disagree that the use of aov() would impose no problems, since you would be moving from analyzing an outcome that is continuous to one that is discrete (multiply observed binomial). Leaving aside the fact that this would normally require Poisson regression or logistic regression, it is possible to aggregate the sum/length of "ACC" within categories of $Subject, $Group, $Global, $Local, and $trialtype. At the moment there is only one level to $trialtype and $Phase, so subsetting would appear unneeded, but if this str() output is on a subset then you could restrict it to those with $trialtype=="Test" by only using a[a$trialtyp=="Test" , ] as your dataframe.
categ.a <- with( a, tapply(a$ACC, INDEX =list(Subject Group, Global, Local),
                     FUN = function(x) {
                                   sum(x)/ length(x) }

Edit 1: You may want to seek statistical consultation regarding how to approach this study design for a discrete outcome at www.stackexchange.com. You may not even need this step if you set up your glm() or lmer() analysis properly. I would have been thinking that I might try $Subject as a level in a mixed model having ACC==TRUE as the outcome with Poisson errors using an offset of log(length(ACC)).
Edit 2: It is possible that the original approach would be sufficient if you had sufficient numbers in each subject and category that the error rates were "pseudo-continuous", i.e were not largely zeros.

A: You don't do the RT analysis correctly so it's difficult to see how to do the error analysis.  You're not allowed to do an ANOVA on the raw values, you need to aggregate down to conditions first.  After you exclude outliers (what's the justification for these outliers anyway?) you need to then aggregate the rt.
agg <- aggregate( RT ~ Group + Global + Local + Subject, data = tsttrl_nooutliers, mean )

Then you can do the modelling.  I don't want to tell you how to do the accuracies, although you should be able to figure it out now.  You need to read Dixon (2008) and Jaeger (2008).  ANOVA of accuracies is not recommended and they do a nice job covering the bulk of the reasons.