text:
Q: Convert ppt to pdf and protect the file The below is the line of code I'm using it currently which converts ppt to pdf, however I want to protect pdf , Is there any possibility
PowerPointapp.ActivePresentation.SaveAs path & pdffileNm & ".pdf", 32

A: This is not possible with the default vba functions available!
See this, not tested by me, example of using an external library to save pdf with password in the past.

A: Protecting a PDF is not permanent, once the file is opened (using the users decryption key provided by handing over the password), the contents are available to the new owner to add comment or fill forms or otherwise modify by print or text edit or remove watermarks.
Adobe reader will use different parts of those keys to reduce user writes, but no other editor has to.
Browsers need to edit PDF in exactly the same way so my Firefox pdf reader allows me to correct / change web page content or the embedded pdf contents, exactly the same as any other browser or pdf viewer or editor can. The only protected PDF is an unpublished one.


text:
Q: How to use `getUserMedia()` api to simulate WebRTC like behaviour? My primary intention is to setup a VoIP session between 2 users A & B; Here the raw audio / video media bytes are fetched from A's browser are played in B's browser and vice versa.
The reason is that, when the user C & D are added into this call, we need not have to create a P2P mesh network which limits the performance.
Tried recording media with getUserMedia() and playback, but it is not real time. It also gives a bad user experience. (However, haven't experimented yet with videos of small chunks as 200 ms)
Is there any approach where I can get the raw bytes of the media and play it on other browser? Currently I have a server in between which can connect to both peers if required.
Any online examples or libraries are welcome.

Have already asked 2 questions in this regard with 100-100 bounties, but not much of use:

*

*How to use libsrtp or similar library to decrypt/encrypt the WebRTC data stream?

*How to integrate part of WebRTC as a static / dynamic library with the existing C++ code?
Related: How to stream, live video playing on my browser to browser of another user?

A: If i understand you well is you're looking on how to have more than two users on the session right? without using mesh topology
thats possible and configurable as well by means that some maybe active speaker or everyone is active speaker not only receiver whatever configuration you choose but to me it seems that you're asking for video conferencing
there are couple of tools for this the best one i might recommend is mediasoup its a SFU as selective fowarding unit mediasoup

A: I don't know if I understand correctly, but it is not likely that you will get raw video data and play it on the browser, it will just kill your bandwith and performance because the raw data is huge.
You need to use the compressed data ( media codec ex.H264 ) and you need a protocol to send and receive it. If you are looking for sub-second latency than webrtc is your best choice in here already. If you have a server in between, distribute your media through that server instead of Mesh. Check this out for webrtc network topologies:
https://antmedia.io/webrtc-servers/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Working out the distance between 2 points in one plane only
How can I find the distance between the two points as shown in the above picture.
I know I can use Pythagoras to find the 'actual' distance between the two points, but I want to find the X distance between them only.
Also, obviously I know I can subtract the x coordinate of point A from that of Point B, but this won't help because they might be the other way around (i.e., B might be on the left and A on the right).
Would be grateful if someone could advise the simplest method to discover this distance.

A: You have the answer already, you subtract the x coordinate from one point to the other.  You simply need to take the absolute value of that and then it doesn't matter which one is greater.
absoluteValue(Ax - Bx) = absoluteValue(Bx - Ax)

A: you could use absolute value, i.e., abs(a - b)


text:
Q: Multiple region deployment with Geolocation based policy v/s Cloudfront I have a custom origin i.e. a web app on an EC2 instance. How do I decide whether I should go for:

*

*a Cloudfront CDN

or,

*deploy multiple instances in different regions and configure a Geolocation/proximity based routing policy

The confusion arises from the fact that both aim at routing the request to the nearest location (edge location in case of Cloudfront and region specific EC2 instance when it comes to multi-region deployments with Geolocation based policy with Route 53) based on where the request originates from.

A: There is no reason why you can't do both.
CloudFront automatically routes requests to an edge location nearest the viewer, and when a request can't be served from that location or the nearest regional cache, CloudFront does a DNS lookup for the origin domain name and fetches the content from the origin.
So far, I've only really stated the obvious.  But up next is a subtle but important detail:
CloudFront does that origin server DNS lookup from a location that is near the viewer -- which means that if the origin domain name is a latency-based record set in Route 53, pointing to deployments in two or more EC2 regions, then the request CloudFront makes to "find" the origin will be routed to the origin deployment nearest the edge, which is also by definition going to be near to the viewer.
So a single, global CloudFront deployment can automatically and transparently select the best origin, using latency-based configuration for the backend's DNS configuration.
If the caching and transport optimizations provided by CloudFront do not give you the global performance you require, then you can deploy in multiple regions, behind CloudFront... being mindful, always, that a multi-region deployment is almost always a more complex environment, depending on the databases that are backing your application and how they are equipped to handle cross-region replication for reads and/or writes.
Including CloudFront as the front-end is also a better solution for fault tolerance among multiple regional deployments, because CloudFront correctly honors the DNS TTL on your origin server's DNS record, and if you have Route 53 health checks configured to take an unhealthy region out of the DNS response on the origin domain name, CloudFront will quickly stop sending further requests to it.  Browsers are notoriously untrustworthy in this regard, sometimes caching a DNS answer until all tabs/windows are closed.
And if CloudFront is your front-end, you can offload portions of your logic to Lambda@Edge if desired.

A: You can use multi region for lot reasons mainly,

*

*Proximity

*Failover (incase if first region fails, requests can be sent to another region)

Multi region lambda deployment is clearly documented here. You can apply the same logic to all of the AWS Resources too. (DynamoDB, S3)
https://aws.amazon.com/blogs/compute/building-a-multi-region-serverless-application-with-amazon-api-gateway-and-aws-lambda/
You can also run Lambda@Edge to force all your requests / splits to one region on the edge.
Hope it helps.


text:
Q: Search for running script PID by script name I have the following script
hello.sh
--------
while :
do
    echo "hello"
    sleep 20
done

And when I ran the above script, I got 2627 as the PID of the script
root@localhost ~]# ./hello.sh &
[1] 2627
[root@localhost ~]#

Now when I'm running the ps command in another terminal, I'm not getting the script name in the output
[root@localhost ~]# ps -ef| grep 262[7]
root      2627  1582  0 19:19 pts/1    00:00:00 -bash
root      3427  2627  0 19:52 pts/1    00:00:00 sleep 20
[root@localhost ~]#

$$ is the PID of the main shell where I'm running the script. I know that inside the script I can put $$ to get the PID of the script, but that's not my intention here.
Once I ran the long running script in the background and suppose I have closed the terminal accidentally, then is there a way to grep the PID using the script name or any other means?
FYI
[root@localhost ~]# echo $$
2586
[root@localhost ~]# ps -ef| grep 262[7]
root      2627  1582  0 19:19 pts/1    00:00:00 -bash
root      3657  2627  0 20:02 pts/1    00:00:00 sleep 20
[root@localhost ~]# ps -ef| grep bas[h]
root      1517  1513  0 18:43 pts/18   00:00:00 -bash
root      1582  1578  0 18:45 pts/1    00:00:00 -bash
root      2586  2581  0 19:18 pts/54   00:00:00 -bash
root      2627  1582  0 19:19 pts/1    00:00:00 -bash
[root@localhost ~]#

2586 is the PID of the main shell and inside it, I have run the hello.sh script. It created a new shell and started running the commands inside it. All these basic I know. This is not a duplicate question. Please see the output to understand it.

A: You should add a proper she-bang line (#! /bin/sh or #! /bin/bash) to your script if you want it to appear with its name in the process list.
Example:
$ cat foo
sleep 10

$ ./foo &
[4] 4403
$ ps -q 4403
  PID TTY          TIME CMD
 4403 pts/3    00:00:00 bash

$ cat bar
#! /bin/sh
sleep 10

$ ./bar &
[5] 4406
$ ps -q 4406
  PID TTY          TIME CMD
 4406 pts/3    00:00:00 bar

Otherwise, on linux you can still find the name of the script from the /proc/PID/fd directory:
$ ./foo &
[2] 5125
$ ls -l /proc/5125/fd
total 0
lrwx------ 1 ahq ahq 64 Oct 22 17:57 0 -> /dev/pts/3
lrwx------ 1 ahq ahq 64 Oct 22 17:57 1 -> /dev/pts/3
lrwx------ 1 ahq ahq 64 Oct 22 17:57 2 -> /dev/pts/3
lr-x------ 1 ahq ahq 64 Oct 22 17:57 254 -> /tmp/foo
lrwx------ 1 ahq ahq 64 Oct 22 17:57 255 -> /dev/pts/3

Notice to forth line, the 254 fd which points to the path of the script being run. With other shells than bash it will be other fd, like 3 or 10.
That could also be reverse searched with lsof /tmp/foo.

A: On Linux, you could:
grep -l hello.sh /proc/*/task/*/comm 2>/dev/null

... which would report back any of your processes with "hello.sh" in their command-line (pid 26560, when I ran it):

/proc/26560/task/26560/comm

The stderr redirection is to drop grep's complaint about your current process' comm file (/proc/self/task/$$/comm) disappearing between the time the shell expands the wildcarded path and when grep decides to open it for reading/grepping.
If you run a second "hello.sh", you'll get two results back, etc:
$ ./hello.sh &
[2] 28328
$ grep -l hello.sh /proc/*/task/*/comm 2>/dev/null
/proc/26560/task/26560/comm
/proc/28328/task/28328/comm


text:
Q: nutch crawl path I would like to know how to make nutch crawl not only the domain that I specified, but also the dir path within the domain that I specified.  I know that you can configure this information on regex-urlfilter.txt

A: This should crawl only the domain/path you want :
+.*www\.domain\.com/yourpath/.*
#skip everything else
-.*


text:
Q: How to accumulate the sum in VB?         Dim index As Integer
        Dim choice As String
        Dim total As Integer

        total = 0

        index = NumericUpDown1.Value

        Dim arr(4) As Integer
        arr(0) = 10
        arr(1) = 5
        arr(2) = 21
        arr(3) = 33

        If index > 0 Then
            choice = (Combobox1.SelectedItem.ToString + " x " + NumericUpDown1.Value.ToString)
            ListBox1.Items.Add(choice)
            CheckedListBox1.Items.Add(choice)
            total += arr(Combobox1.SelectedIndex) * index
            TotalLabel.Text = total.ToString()

      Else
            MsgBox("error.")

        End If

I can calculate the total of single choice, but fail to accumulate to sum.
What's wrong of the code?
Current Situation:
Step 1:
choose arr(0), index = 2
total = 20
Step 2:
choose arr(2), index = 1
total = 21
Correct Situation:
Step 1:
choose arr(0), index = 2
total = 20
Step 2:
choose arr(2), index = 1
total = 41

A: You'll need a either a global variable or a class with a public variable. You should create a Transaction class to store the data about the transaction and probably a Product class to store the data about the product. What you put in it is up to you, but I'd start out with something like this:
Public Class Transaction
    Private _productsList As List(of Product)
    Private _transationNumber As Integer
    '...more stuff...

    'you'll want to remember what products are in your "cart" for the transaction
    Public Property ProductsList As List(of Product)
        'your get/set accessors
    End Property
    Public Property TransactionNumber As Integer
        'your get/set accessors
    End Property
    Public Property TotalTransactionCost() As Double
        Get
            'this will sum of the prices of all of the products you have stored in your
            'list of products for this transaction
            Return _productsList.Sum(product => product.Price)
        End Get
    End Property

    Public Sub New()
        '...constructor stuff
    End Sub
    Public Sub AddProductToTransaction(byval product)
        _productsList.Add(product)
    End Sub

End Class

Public Class Product
    Private _price As Double
    Private _productName As String
    Private _UPC As String

    Public Property Price() As Double
        'your get/set accessors
    End Property
    Public Property ProductName() As String
        'your get/set accessors
    End Property
    Public UPC As String () As String
        'your get/set accessors
    End Property

    Public Sub New()
       'constructor stuff
    End Sub
End Class

These are a couple class shells to get you started. If you're serious about making a product, this is a step in the right direction. If you're going to write code, write it the right way.
If you're just looking for a quick and dirty solution, you can declare a global variable and just keep a running sum. Just don't forget to clear it out before you start a new transaction.
You'll want to do something like:
Private TransactionCost As Double in your form outside of all your methods.
Again, I would recommend the first way of going about things. You'll need at least those two classes and they'll definitely be more fleshed out for a real product.
I hope this helps and answers your question. If it does, hit me with an upvote and accept the answer. Welcome to SO.


text:
Q: Smoothing measure by convolution I'm reading Optimal Transport for Applied Mathematicians by Fillipo Santambrogio. At one point he says that taking the convolution of a measure with a smooth mollifier, i.e $\eta_\varepsilon \in C^\infty_c (X)$ such that
$$ \int_{\mathbb{R}^d} \eta_\varepsilon = 1$$
then considering
$$ \mu * \eta_\varepsilon $$
we obtain an absolutely continuous (with respect to the d dimensional lebesgue measure) smoothing of $\mu$. However, I am somewhat struggling to understand how this is the case. For example, if I consider the dirac measure $\delta_0$ at 0 on $\mathbb{R}$, then take $\eta_\varepsilon * \delta_0$, I should have
$$ \eta_\varepsilon * \delta_0 (\{0\}) = \int_{\{0\}} 1 d\eta_\varepsilon * \delta_0 = \int_{\{0\}} 1 * \eta_\varepsilon d(\delta_0) = \int_{\{0\}} \left( \int_\mathbb{R} 1 \cdot \eta_\varepsilon(z) dz \right) d(\delta_0) = \int_{\{0\}} 1 d(\delta_0) = 1$$
which would seem to imply that $\delta_0 * \eta_\varepsilon$ gives mass to a set of lebesgue measure zero, which obviously means it cannot be absolutely continuous. What am I missing here?

A: Since $\delta_0$ is the neutral element for convolution, you have $\eta_{\epsilon}\star \delta_0=\eta_{\epsilon}$ which is smooth. Your computation went wrong, you should have written, since $\delta_0$ is a distribution,
$$(\delta_0\star\eta_{\epsilon})(x)=\left<\delta_0,\eta_\epsilon(x-\cdot)\right>=\eta_\epsilon(x-0)=\eta_\epsilon(x).$$


text:
Q: How do you store ICs used in hobby electronics? I've recently started working on a project and I need to find a way to store some ICs that I'm using. I have around five different ICs and someone said I could just put them all together in a small cylindrical tube I have (think a little box medicine pills come in). Wouldn't this damage the ICs? And/or are there better ways to store them?

A: a half step or so beyond the hobby perspective, and this tries to address the question of "finding the parts" in addition to "storing them".
method 1: clear plastic bins from walmart etc, sold as "bead organizers".  example ... inside that use little mini ziploc bags for the parts too, so they don't go flying all over the place. not appropriate for all part types. Write a "map" of what's in the box on the lid with sharpie. (erase with isopropanol if needed).
method 2:  keep in original bag, or matching sized anti static ziplocs, put those into shoebox-sized clear totes, and be obsessive about keeping them sorted. Having 4-5 subdivisions within each container can help, keeps bags upright, abbreviated label w/ sharpie on top, go thru them like card catalog of old.
method 3: per-project containers (the inevitable end state), but of limited use when prototyping/experimenting, IMO

A related practice: if re-bagging, or binning, a coworker showed me to take scissors and cut out the label from the original bag, just a little rectangle with the full mfg and vendor part numbers, description etc, and put it in the new bag, as a kanban for reordering.

A: I store everything in the Mouser/Farnell/DigiKey bags they're delivered in. They have convenient readable labels, which is nice, especially when they contain tiny SOT-23 transistors which are quite impossible to identify and basically disappear into a black hole, or into the carpet floor, if you lose sight of them.
To find them, I just slip the bags in photo albums, and I have a spreadsheet that says on page X, there is this chip. It's extremely convenient. Plastic bags stacked in a container are unusable. But photo albums are great, and cheap.

Or I just make holes in the bags and put them in a binder.

If you have DIP ICs... a sheet of black foam fits nicely inside an A4 transparent plastic sleeve that goes into a ring binder. Or in a photo album. And if they fall off the black foam, they're still at the bottom of the plastic pocket.

For passives, I store them in a box that has the same width as the plastic bags laying vertical on their side. Ordered by value, with a cardboard separator between each E24 value. So if I need 12 kOhm, I just leaf through the stack of bags like a dictionary. It's very convenient.

A: I often find that storing in the packaging that they come in from suppliers works best.  You need to provide both protection from ESD as well as from physical damage like bent or broken pins.  The re-seller packaging often fits both needs.
Failing that, "black foam" or "pink foam" which are readily available, offer a reasonable ESD and physical damage barrier.
Don't use things like styrofoam which generates static and can damage sensitive components.  I think your suggestion of putting them in a bottle is not a good one as they are easily damaged like that.

A: Yes, it will damage the ICs
Unless a container is specifically designed to be anti-static, the IC is at risk of being damaged by static shock. That's a risk, not an absolute - but why risk it in the first place?
The best solution is to keep them in the bag/tube they came in, until you need them. The less you handle ICs, the happier they're going to be.
If you really do want to consolidate your ICs into one place, you need an anti-static plastic box, and anti-static foam inside the box which you push the ICs into. This isn't ideal because you've had to handle the ICs to get them in there, but at least they're safe from that point.
And you now know that the person who told you this has zero understanding of electronics. Ignore their input on everything related to electronics in future, because their advice, however well-intentioned, will result in damage to your equipment.


text:
Q: How to refresh cache mediator in wso2 esb Was going through the cache mediator in ESB and planning to use it. As I understood,cache mediator calls the end point if the request is not cached and returns the same response for subsequent requests. In my case if the end point service is updated to return different out put then how does ESB knows that the end point result is updated and need to refresh the cache in ESB. In nutshell I would like to know is there any way to invalidate cache in WSO2 ESB. Not seeing anything so far.

A: The ESB cache implementation does not contain direct support for cache synchronization and cache invalidation.  You need to build a service endpoint that will receive data modification messages and either invalidate or update the cache entry.

A: According to the current caching implementation, it generates a hash for the request and get the cached response for the particular hash and the cached response is refreshed after the current caching time expires


text:
Q: How to run AngularJS2 application without Node server Is it possible to run an Angular 2 application in browser without using NodeJS as a server. I am not sure, but if i understand correctly the newest browsers are able to compile/"understand" the TypeScript code so i don't have to use any third part js lib to compile it into plain javascript?

I would like to create an application using 100% Angular 2 on frontend and for the
  backend REST API using Ruby On Rails, without using Rails's page rendering, sessions etc..

I am little confused about it how does Angular2 work/run behind the scenes... How i should configure my Angular2 application to use it without NodeJS?

A: I think you're mixing up some technologies here.
Server
You can run an Angular app on any server that can host static files. There is nothing special about node. So yes, you can use a ruby. Or an Apache, nginx, lighttpd etc.
The reason for this is that JavaScript is run on the client side. The server's response is only to deliver the JS/HTML/CSS files to the client that is visiting your site.
TypeScript
If you're writing an application with TypeScript you need to transpile it to JavaScript before any browser understands it. You can do this (1) before you're deploying your app to the server or (2) use a library like System.js that will transpile TypeScript on the fly.
While (2) is definitely an option and the Angular CLI used it until recently, (1) is in my opinion the better option. Angular CLI switched to (1) and is now using webpack. Webpack is transpiling and bundling your app before it is hosted on a server.
Hope I could clear things up a bit for you.

A: You can use any server side technology including Asp.Net Core, Node.Js, PHP to server the js, html and css content.
While building the application in the IDE, the Node.js transpile the .ts files into .js file.

A: TL;DR
If you use TypeScript with Angular 2, you only need Node during development:
DEV: NodeJS is used to transpile .ts files to .js files.
PROD: Generated .js files are used inside the browser, NodeJS is not required anymore, except if you also happen use it in the backend.
NOTE: If you only use plain JS in development you do not even need Node


text:
Q: Using find to look for a directory and remove its subdirectories Let's say I have a list of nested directories that looks like this:
./x1/mf/dir1
./x1/mf/dir2
./x1/mf/file1
./x2/mf/dir3
./x2/mf/file2
...

I want to remove all the subdirectories of every mf directory. Meaning dir1, dir2, dir3 in the previous example.
I know that
find . -type d -name "mf"

will return a list of all the directories called mf. And ls -d */ returns all the subdirectories in the current directory. So I tried
find . -type d -name "mf" -exec ls -d /* {} \;

to list the desired directories, but it would actually print the directories inside /. I was planning to pipe the resulting list to xargs rm -r to do the removal afterwards.

A: Setting up test directories and files:
$ mkdir -p x{1..3}/mf/dir{1..3}
$ touch x{1..3}/mf/file{1..3}
$ tree
.
|-- x1
|   `-- mf
|       |-- dir1
|       |-- dir2
|       |-- dir3
|       |-- file1
|       |-- file2
|       `-- file3
|-- x2
|   `-- mf
|       |-- dir1
|       |-- dir2
|       |-- dir3
|       |-- file1
|       |-- file2
|       `-- file3
`-- x3
    `-- mf
        |-- dir1
        |-- dir2
        |-- dir3
        |-- file1
        |-- file2
        `-- file3

Then find all directories that has mf in its path and delete them. The -depth does a depth-first traversal, so that find doesn't try to enter directories that it has already deleted.  We also print the names of all directories that are deleted.
$ find . -depth -type d -path "*/mf/*" -print -exec rm -rf {} +
./x1/mf/dir1
./x1/mf/dir2
./x1/mf/dir3
./x2/mf/dir1
./x2/mf/dir2
./x2/mf/dir3
./x3/mf/dir1
./x3/mf/dir2
./x3/mf/dir3

Now:
$ tree
.
|-- x1
|   `-- mf
|       |-- file1
|       |-- file2
|       `-- file3
|-- x2
|   `-- mf
|       |-- file1
|       |-- file2
|       `-- file3
`-- x3
    `-- mf
        |-- file1
        |-- file2
        `-- file3

A: I strongly suggest using this to ls before rm -fring for obvious reasons:
find . -type d -name "mf" -print0 | xargs -0 -n1 -I haystack find haystack -type d -exec rm -fr {} \;

Example:
$ tree
.
├── bar
│   ├── foo
│   │   ├── bar
│   │   └── baz
│   └── freeble
├── baz
│   ├── foo
│   │   ├── bar
│   │   └── baz
│   └── freeble
└── quux
    ├── foo
    │   ├── bar
    │   └── baz
    └── freeble

15 directories, 0 files
$ find . -type d -name "foo" -print0 | xargs -0 -n1 -I haystack find haystack -type d -maxdepth 0 -exec rm -fr {} \;
$ tree
.
├── bar
│   └── freeble
├── baz
│   └── freeble
└── quux
    └── freeble

6 directories, 0 files


text:
Q: Error Handling in Classic Asp without timeout error In classic asp page, i need to catch the error description and insert into a table in the database.
when i use 'on error resume next', i am getting a timeout error as follows:

The maximum amount of time for a
  script to execute was exceeded. You
  can change this limit by specifying a
  new value for the property
  Server.ScriptTimeout or by changing
  the value in the IIS administration
  tools

Please help me to catch the exception and insert into database.

A: I believe your question is "How do I trap the Script Timeout error and record it in the database".  Then the answer is you can't do it with On error resume next.
The problem is that ASP has determined your script has run for too long.  In order for your code to trap and record the error your code needs to continue but that is exactly what ASP has determined shouldn't happen since its time is up.
Also in general unless you can continue to do something sensible (and that does not include logging) in your script there is no point trying to use On Error Resume Next to trap the error.
Instead create a new ASP script that should run whenever you get a script error (this will include a Script timeout error).  In IIS manager open your applications property dialog and select the Custom Errors tab.  Edit the handler for the 500;100 HTTP error and change it to URL and the path of this ASP script.
Now you can place your error logging code in this ASP script.  You can access the error thrown by the failing ASP page by accessing the Server.GetLastError method.  You can also configure this page to send something friendly to the user.

A: Why not investigate/fix the timeout issue rather than try and catch the exception? Whilst you should log errors you should also investigate why it is occuring in the first place.

A: If the exception is with anything to do with your database you might have found your answer... have you checked to see what the problem is first?


text:
Q: How to invoke a method every time database is modified I am writing a Ruby on Rails app and I want a method to be called every time the database is modified.  Is it possible to do this without inserting a method call in every location where the database is modified?

A: Depends on the database. Many databases have very powerful stored procedure languages that can, among other things, invoke web services.
You could have a trigger on the important database tables call a ruby web service that calls your method.
Or you can have triggers that update an event table, and then have a process that watches for changes on that table and then fires the method.
There's likely some meta-programming magic that you might be able to use to tweak your ruby code to invoke the change as well.
All sorts of options.

A: If you want to log all models:
Monkey patch the ActiveRecord::Base class.
class ActiveRecord::Base
  after_save :log_something
  after_destroy :log_something

private
  def log_something

  end
end

For a specific model:
class User < ActiveRecord::Base
  after_save :log_something
  after_destroy :log_something

private
  def log_something

  end
end

A: I like KandadaBooggu's answer but if you did not want to monkey with AR you might be able to do this with an Observer.
class AllObserver < ActiveRecord::Observer
  observe :model_a, :model_b

  def after_save(record)
    logger.info("CREATED #{record.class}")
  end

  def after_update(record)
    logger.info("UPDATED #{record.class}")
  end
end

Just add the models that you want to observer. In this example it will log updates to ModelA and ModelB

A: Have you considered using: after_update or before_update in ActiveRecord:
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html


text:
Q: v-if not working without v-else using computed property that returns Vuex state I am not sure where the problem is, however, basic v-if is just not working properly.
<template>

       <select v-model="col.code">
            <option v-for="i in foo" :value="i.code">{{ i.code }}</option>
       </select>

       {{ col }}
       // { "code": "B" }

 // not working
            {{ col.code }}

</template>

However, if i add v-else, result will be rendered.
I also found out, that if i am doing same thing, without computed property, but with data property directly, it is not working either. What makes it to work is to add  around v-if statements.

    <select v-model="col.code">
        <option v-for="i in [1,2,3,4,5]" :value="i">{{ i }}</option>
    </select>

        {{ col }}

Strange.

A: It looks that's no problem with
 but binding the select to a computed property is wrong, so you should use a computed setter :
  computed: {
        col: {
            get(){
              return this.$store.state.col;

              },
            set(newVal){
              this.$store.commit('UPDATE_COL',newVal);
            }
        }
    }

Vue.use(Vuex)
//store instance
const store = new Vuex.Store({
  state: {
    col: {
      code: 'A'
    }
  },
  mutations: {
    UPDATE_COL(state, payload) {
      state.col = payload
    }
  }
})

//vue instance
let app = new Vue({
  el: '#app',
  store,
  data() {
    return {
      foo: [{
          code: 'A'
        },
        {
          code: 'B'
        },
        {
          code: 'C'
        }
      ]
    }
  },
  created() {

  },

  computed: {
    col: {
      get() {
        return this.$store.state.col;

      },
      set(newVal) {
        this.$store.commit('UPDATE_COL', newVal);
      }
    }
  }

})

  <select v-model="col.code">
    <option v-for="i in foo" :value="i.code">{{ i.code }}</option>
  </select>

   My code : {{ col.code }}


text:
Q: Use SVG componets in a monorepo shared UI library without webpack Hello everyone I have a Yarn, Turborepo monorepo. I have 2 Next apps that share some UI components
src
|- apps/ the next js apps
|- packages/ui the UI  library

I am unable to add SVGR as I don't have webpack, I use NextJS transpile to get the library into my project. What are my options to import SVGs it my code? I am currently failing during the build
My setup is the same as this
Most of my confusion comes from how the compilation and builds happen with monorepos
Next transpiles the library, but library itself fails during build as SVG files cannot be imported
Basically I am trying to do this
import Star from './star.svg'
In a shared library like this
Do I need to create a react app for this? I am suspecting that I need a more complex setup with proper build step, outputs and entry point for the types


text:
Q: Can I write $\sum_{n=1}\frac{n}{2^n}$ as sum of odd and even? I was wonder why I can't write : $\sum_{n=1}\frac{n}{2^n}$, as:
$\sum_{n=1}\frac{n}{2^n}=\sum_{n=1}\frac{2n}{2^n}+\sum_{n=1}\frac{(2n-1)}{2^n}$
It seems logic to say that the sum of the odd and even for $n$ will be the sum of the original,but I got :
$\sum_{n=1}\frac{n}{2^n}=2\sum_{n=1}\frac{n}{2^n}+2\sum_{n=1}\frac{(n)}{2^n}-\sum_{n=1}\frac{1}{2^n}$
And that's not give me $S=2$.

*

*all are infinite sums.

Thanks.

A:
$$\sum_{n=1}\frac{n}{2^n}~=~\sum_{n=1}\frac{2n}{2^n}~+~\sum_{n=1}\frac{2n-1}{2^n}$$

I assume what you actually meant to write is

$$\sum_{n=1}\frac{n}{2^n}~=~\sum_{n=1}\frac{2n}{2^{\color{blue}{2n}}}~+~\sum_{n=1}\frac{2n-1}{2^{\color{blue}{2n-1}}}$$


text:
Q: Select and animate all divs with a class but ignore all children with same class I'm hoping there's a simple solution to this, but I can't see it at the minute.
I'm attempting to select all divs with a class myClass, but ignore all children of said class including those that have the class myClass. For example:

 //select

 //don't

 //don't etc

I know this is an odd situation, it's come about from a need to slide map controls across a Google map when sliding in a side-div (so as not to cover them). The classes that need to be altered are all named 'gmnoprint' and if children are not ignored then elements within a parent are moved by double the required amount for each level of nesting.
My current solution (more of a bad hack) is to call:
$('div.gmnoprint').stop().animate({ 'marginLeft': '418px' }, 800);
$('div.gmnoprint').children('div.gmnoprint').stop().animate
    ({ 'marginLeft': '0px' }, 800);

But this is horribly inefficient and processor intensive.
Apologies if this is a duplicate, but I could not find anything similar.
Any help greatly appreciated.

A: $('div.gmnoprint')
    .filter( function() {
        return $(this).parent().closest('div.gmnoprint').length === 0;
    })
    .stop()
    .animate({ 'marginLeft': '418px' }, 800);

A: These divs must all live within another container of some sort. If we assume it's id is container, call:
$('#container').children('div.gmnoprint').stop().animate({ 'marginLeft': '418px' }, 800);

This will only go one level deep and not select all div.gmnoprint elements on the page.


text:
Q: Require assets in react's JSX? A completely noob question, sorry. I'm using dva to generate a project. If I want to create an  tag, I can get the SRC for the asset like this:

This works properly. However, I need to generate this code:
<picture>
  <source srcset="assets/card-cultural.png, assets/card-cultural@2x.png 2x" />

</picture>

Notice the srcset value on source. How would I generate that string using require?


text:
Q: Javascript difference between {} and [] I am working on javascript and I run into this:
if i do
let object = {};
object.length

It will complain that object.length is undefined
But
let object = [];
object.length

works
Any know why?
Thanks

A: In JavaScript, virtually everything is an object (there are exceptions however, most notably null and undefined) which means that nearly all values have properties and methods.
var str = 'Some String';
str.length // 11

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.
[] is shorthand for creating an empty array. While also a data structure similar to an object (in fact Object as mentioned previously is in its prototype chain), it is a special form of an object that stores sequences of values.
typeof [] // "object"

When an array is created it automatically has a special property added to it that will reflect the number of elements stored: length. This value is automatically updated by certain methods while also used by others.
var arr = [];
arr.hasOwnProperty('length'); // true
arr.length; // 0

In fact there is nothing special about properties on arrays (although there are few if any good reasons to use them) aside from the engine using them for those methods.
var arr = [];
arr.foo = 'hello';
arr // []
arr.foo // "hello"
arr.length // 0

This is not true of an Object though. It does not have a length property added to it as it does not expect a sequence of values. This is why when you try to access length the value returned is undefined which is the same for any unknown property.
var obj = {};
obj.hasOwnProperty('length'); // false
obj.length; // undefined
obj.foo; // undefined

So, basically an array is a special data structure that expects a sequence of data. Because of this a property is added automatically that represents the length of the data structure.
BONUS: You can use length to trim an array:
var a = [1,2,3,4,5];
a.length; // 5
a.length = 2;
a; // [1, 2]
a.length; // 2

A: This is because [] is an array object and the length is 0 because there are no elements. {} is an object and there is no property length.  The array object does have a property called length, thats why you see the number of elements when you call [].length

A: [] signifies an array in javascript, so it has length. {} is just declaring an object.

A: They're different things. One is an object, another is an array.
{} is an object, which has keys and values.
You can't necessarily determine the length of an object since its key-value pairs may not necessarily be numbers or indexed in any way.
[] is an array, which has numbered indices. It's pretty straightforward it has a length.


text:
Q: How can i put 3 divs side by side with a margin and a border? I'm trying to put three divs side by side which works fine but when i add a border and a small gap between each div the 3rd div goes onto a new line. Is there a way to auto resize the divs so they fit?
HTML:

Trending

        123

Trending

        123

Trending

        123

CSS:
.trendingContainer {
    margin: 0 auto;
}
.trendingBox {
    border: 1px solid #e5e5e5;
    background: #fff;
    margin: 0 2px 0 0;
}

A: You can always use calc and percentage based widths:
.trendingBox {
    border: 1px solid #e5e5e5;
    background: #fff;
    margin: 0 2px 0 0;
    width: calc(100% / 3 - 4px);
}

If you want to support multiple browser widths separately you can use media queries:
@media(max-width: 600px) {
    .trendingBox {
        border: 1px solid #e5e5e5;
        background: #fff;
        margin: 0 2px 0 0;
        width: calc(100% / 2 - 4px);
    }
}

@media(min-width: 601px) {
    .trendingBox {
        border: 1px solid #e5e5e5;
        background: #fff;
        margin: 0 2px 0 0;
        width: calc(100% / 3 - 4px);
    }
}

A: You can use either float or flex model, but make sure you have border-box set. And when you are using margin along with a fixed layout like this, ensure the widths correctly:

* {
  box-sizing: border-box;
}
.trendingContainer {
  margin: 0 auto;
  overflow: hidden;
}

.trendingBox {
  border: 1px solid #e5e5e5;
  background: #fff;
  float: left;
  width: 30%;
  margin: 0 0.5%
}

Trending

    123

Trending

    123

Trending

    123

Preview

A: One more try, this time totally different, added a child DIV to specify the content with margin and border:
(This maintains the original sizing and other bootstrap stuff, only defines the additional styling on a separate div, which is more clean to use)
HTML:

Trending

            123

Trending

            123

Trending

            123

CSS:
.trendingContainer {
    margin: 0 auto;
}
.trendingBox {
    /* Add other style here */
}
.trendingBox-content{
    border: 1px solid #e5e5e5;
    margin: 0 2px 0 0;
    background: #fff;
}

A: .trendingBox {
    border: 1px solid #e5e5e5;
    background: #fff;
    margin: 0 2px 0 0;
    display: inline-block;
    float: left;
    width: calc(33.3% - 4px);
}

*

*calc is new in css3 I believe.

*4px is 2px(margin) + 2*1px(border)

*Another thing you can try is using outline. I believe its width would is considered as a port of the box element, haven't tried though.

I believe rest all is clear

A: You can try this.

.trendingContainer {
    margin: 0 auto;
}
.trendingBox {
    border: 1px solid #e5e5e5;
    display: inline-block;
    position: relative;
    float: left;
    background: #fff;
    margin: 0 2px 0 0;
}

Trending

        123

Trending Big

        123

Trending

        123

A: .trendingBox {
    border: 1px solid #e5e5e5;
    background: #fff;
    margin: 0 2px 0 0;
    box-sizing: border-box;
}

The box-sizing: border-box; does the trick. This makes sure the div doesn't resize when adding padding to it.
EDIT: See my other answer, which is the right way to do it in my opinion.


text:
Q: Combine a value from an array with each values from other? What i want is to combine every value from first array with every value from second array.
For example, let's take two arrays:
$array1 = ['green', 'red', 'blue'];
$array2 = ['s', 'm'];

The result array should be:
$result = [1 => 'green-s', 2 => 'green-m', 3 => 'red-s', 4 => 'red-m', 5 => 'blue-s' ...];

The result array can be different, but with that elements combined.

A: check this,
<?php

$array1 = array('green', 'red', 'blue');
$array2 = array('s', 'm');

$data = array();
foreach($array1 as $val){
    foreach($array2 as $val2){
        $data[] = $val."-".$val2;
    }
}

print_r($data);

?>


text:
Q: Is there a way to set all values of a dictionary to zero? For example, I have a list of ASCII characters and want to zip them with a list of zeroes equal to the number of characters in the ASCII list,
like:
    import string

    a = string.printable
    #Gives all ASCII characters as a list ^
    b = zeroes * len(a)
    c = zip(a,b)

Something like that?

A: There is a standard method for that:
mydict = dict.fromkeys(string.printable, 0)

or, if you need a list of tuples (to be quite honest, Martijn's version of that is more pythonic, but just for variety):
import itertools
tuples = zip(string.printable, itertools.repeat(0))

A: Just use a list comprehension:
c = [(i, 0) for i in a]

A: You can use a dict comprehension:
{ x:0 for x in string.printable}

A: It may not help you, but if you are going to be using the dictionary to count you can use a defaultdict.
from collections import defaultdict
my_dict = defaultdict(int)

Any key is then set to 0 by default.
>>> print my_dict['a']
    0

A: Maybe something like this, if you need a list:
import string
c = zip(string.printable, [0]*len(string.printable))


text:
Q: Как получить список всех файлов со всех дисков? Как можно получить все что есть файлы на компе (вот к примеру как в Directory.GetFiles только вместо одной паки все )

A: https://msdn.microsoft.com/ru-ru/library/ms143316(v=vs.110).aspx
public static string[] GetFiles(
    string path,
    string searchPattern,
    SearchOption searchOption
)

Позволяет указать AllDirectories - со всеми подпапками.

Если нужно прямо все файлы с компьютера, то выгоднее будет использовать
https://msdn.microsoft.com/ru-ru/library/dd383571(v=vs.110).aspx
public static IEnumerable<string> EnumerateFiles(
    string path,
    string searchPattern,
    SearchOption searchOption
)

Он в реальном времени отдает файлы, а не пытается прочитать сразу всё.


text:
Q: Can I use languagetool for android app development I used languagetool 3.4 API for my desktop application, now I want to use it in my android app. Is it possible? if so, how to use it? I am using Android Studio.
Thanks


text:
Q: Как сделать чтобы выбранное значение в выпадающем списке осталось после переключения? Как сделать так, чтобы при нажатии на стрелку или на li, раскрывался список и выбранное значение отображалось, как 'Декоративная краска'? То есть, чтобы вешался класс active на выбранную мной li. Я делал так- создал блок paint и внутри ul c лишками. Первому задал класс active, чтобы отображался выбранным, а другим li задал фон и цвет по средствам .paint li:not(:first-child). А вот как сделать так, чтобы при нажатии выпадал список и на выбранное вешался класс active не пойму.
вот так выглядит пример:

.paint li:not(:first-child) { display: block; }

Код блока

.paint {
  display: flex;
  justify-content: center;
}

.paint li a {
  font-family: Lora;
  font-style: italic;
  font-size: 18px;
}

.paint li a:hover {
  color: #fdac7a;
}

.paint li.active a {
  border-bottom: 1px dashed #ff8d2e;
  color: #ff8d2e;
}

.paint li.active:after {
  content: ' \25BC';
  color: #ff8d2e;
  font-size: 50%;
  cursor: pointer;
}

.paint li:not(:first-child) {
  background: #fff;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.35);
  display: none;
  padding: 5px;
}

      лучшие предложения

Декоративная краска

Эмалевая краска

Масляная краска

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Cupiditate consequatur quae qui quia dolore minus quaerat nulla, sit, hic culpa fuga at veniam ipsum animi. Suscipit quod minima, pariatur debitis impedit, vel officiis, aspernatur voluptas inventore
    voluptate, enim quia quaerat?

A: Добавил немного стилей так, чтобы выбранный элемент всегда был первым и остальное по мелочи.
Показ и скрытие происходит благодаря навешиванию класса paint--visible, а у элементов списка с этим классом-родителем появляется свойство display: list-item.
Смена самого класса active происходит следующим образом:

*

*убираем с активного элемента класс active

*в зависимости от того, по какой ноде был клик навешиваем класс active (event delegation)

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

const paintNode = document.querySelector('.paint')

paintNode.addEventListener('click', (e) => {
  const liActiveNode = paintNode.querySelector('li.active')

  paintNode.classList.toggle('paint--visible')
  liActiveNode.classList.remove('active')

  if (e.target.tagName === 'LI') {
    e.target.classList.add('active')
  } else if (e.target.tagName === 'A') {
    e.preventDefault()
    e.target.parentNode.classList.add('active')
  }
})
.paint {
  display: flex;
  justify-content: center;
}

.paint ul {
  display: flex;
  flex-direction: column;
}

.paint li a {
  font-family: Lora;
  font-style: italic;
  font-size: 18px;
}

.paint li a:hover {
  color: #fdac7a;
}

.paint li.active {
  order: -1;
}

.paint li.active a {
  border-bottom: 1px dashed #ff8d2e;
  color: #ff8d2e;
}

.paint li.active:after {
  content: ' \25BC';
  color: #ff8d2e;
  font-size: 50%;
  cursor: pointer;
}

.paint li:not(.active) {
  background: #fff;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.35);
  display: none;
  padding: 5px;
}

.paint--visible li {
  display: list-item !important;
}

      лучшие предложения

Декоративная краска

Эмалевая краска

Масляная краска

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Cupiditate consequatur quae qui quia dolore minus quaerat nulla, sit, hic culpa fuga at veniam ipsum animi. Suscipit quod minima, pariatur debitis impedit, vel officiis, aspernatur voluptas inventore
    voluptate, enim quia quaerat?


text:
Q: selenium: element which not visible? I tried this xpath but I don't know how to continue ? the element isn't visible at all
the html of the page is:
<form id="form-resetpass" method="post" action="">

    תעודת זהות
    <input class="only-numbers ltr" type="text" value="" maxlength="9" name="wupid" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAAXNSR0IArs4c6QAAAPhJREFUOBHlU70KgzAQPlMhEvoQTg6OPoOjT+JWOnRqkUKHgqWP4OQbOPokTk6OTkVULNSLVc62oJmbIdzd95NcuGjX2/3YVI/Ts+t0WLE2ut5xsQ0O+90F6UxFjAI8qNcEGONia08e6MNONYwCS7EQAizLmtGUDEzTBNd1fxsYhjEBnHPQNG3KKTYV34F8ec/zwHEciOMYyrIE3/ehKAqIoggo9inGXKmFXwbyBkmSQJqmUNe15IRhCG3byphitm1/eUzDM4qR0TTNjEixGdAnSi3keS5vSk2UDKqqgizLqB4YzvassiKhGtZ/jDMtLOnHz7TE+yf8BaDZXA509yeBAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: left center;">

    <input class="sprite form-resetpass" type="submit" value="" name="">

    </form>

the java code:
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class='only-numbers ltr']")));

try also this code: and the same error
driver.findElement(By.xpath("//input[@class='only-numbers ltr' and @name='wupid']")).sendKeys("111");

After execution of code I got the following exception:

Exception in thread "main" org.openqa.selenium.TimeoutException: Timed
  out after 10 seconds waiting for visibility of element located by
  By.xpath: //input[@class='only-numbers ltr']

also try/check:
maximize the current window that webdriver is using (e.g. maximize()).
the element is not hidden.
that is the problem here?


text:
Q: Disk Optimization - SCAN algorithm in Java I am currently trying to create a method named arrangeBySCAN which takes in the parameters of previous, current, and an array of sequence. The purpose of this method is to arrange inputs from a .properties file according to SCAN format in disk optimization.
I am however getting an error:

IllegalArgumentException

on the following line of code:
int scanArray1[] = Arrays.copyOfRange(tmp, 0, currentIndex); //line 17

I'm not an experienced programmer and any help would be appreciated.
Here's the following code.
    private int[] arrangeBySCAN(int previous, int current, int sequence[]){
        int direction = previous - current;
        int seqLength = sequence.length;
        int tmp[] = new int[seqLength];
        // If direction is less than 0, it is increasing
        // If direction is greater than 0, it is decreasing
        if (direction < 0) {
            Arrays.sort(tmp);
        }
        else if (direction > 0){
            Arrays.sort(tmp);
            Collections.reverse(Arrays.asList(tmp));
        }
        // Find the index position of the current cylinder after sorting
        int currentIndex = Arrays.asList(tmp).indexOf(current);
        // Split the sequence into two parts, taking the index of the current cylinder as reference
        int scanArray1[] = Arrays.copyOfRange(tmp, 0, currentIndex);
        int scanArray2[] = Arrays.copyOfRange(tmp, currentIndex, tmp.length);
        // Reverse first sequence
        Collections.reverse(Arrays.asList(scanArray1));

        // Append the first sequence onto the second sequence
        int scanArray[] = new int[scanArray1.length + scanArray2.length];
        System.arraycopy(scanArray1, 0, scanArray, 0, scanArray1.length);
        System.arraycopy(scanArray2, 0, scanArray, currentIndex ,scanArray2.length);
        return scanArray;
    }

A: The IllegalArgumentException is due to currentIndex being -1. The exception you get most likely has a message saying "0 > -1". currentIndex is -1 because you never put anything in your tmp array, so indexOf returns -1 unless current happens to be 0.


text:
Q: The following StateError was thrown while handling a gesture: Bad state: Stream has already been listened to geofencing flutter i am trying to get the user geofencingstatus using the easy geofencing package but when i start the service and close it and restart it the console throw an error:
this is what the console print :
═══════ Exception caught by gesture ═══════════════════════════════════════════
The following StateError was thrown while handling a gesture:
Bad state: Stream has already been listened to.
When the exception was thrown, this was the stack
** my code **

import 'dart:async';
import 'package:easy_geofencing/easy_geofencing.dart';

import 'package:geolocator/geolocator.dart';
import 'package:easy_geofencing/enums/geofence_status.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/domain/models/shop_model.dart';
import 'package:flutter_application_1/presentation/resources/assets_manager.dart';
import 'package:flutter_application_1/presentation/resources/color_manager.dart';
import 'package:flutter_application_1/presentation/resources/values_manager.dart';
import 'package:flutter_application_1/presentation/sidebars/cardWidget.dart';
import 'package:flutter_application_1/presentation/sidebars/profileSideBar.dart';
import 'package:flutter_application_1/services/shop_services.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

class ShopsDownBar extends StatefulWidget with ChangeNotifier {
  ShopsDownBar({Key? key}) : super(key: key);

  @override
  State<ShopsDownBar> createState() => _ShopsDownBarState();
}

class _ShopsDownBarState extends State<ShopsDownBar>
    with SingleTickerProviderStateMixin<ShopsDownBar> {
  StreamSubscription<GeofenceStatus>? geofenceStatusStream;
  StreamSubscription<EasyGeofencing>? easyGeofencingStream;
  StreamController<GeofenceStatus>? geofenceStatusStreamController =
      StreamController<GeofenceStatus>.broadcast();
  Geolocator geolocator = Geolocator();
  String geofenceStatus = '';
  bool isReady = false;
  int raduis = 25;
  double? longitude;
  double? latitude;
  Position? position;
  late StreamController<bool> isOpenStreamController;
  late Stream<bool> isOpenNStream;
  late StreamSink<bool> isOpenNSink;
  late AnimationController _animationControler;
  List<Shops> shops = [];

  getCurrentPosition() async {
    position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print("LOCATION => ${position?.toJson()}");
  }

  setLocation() async {
    await getCurrentPosition();
    print("POSITION => ${position!.toJson()}");
  }

  final _animationDuration = const Duration(milliseconds: 500);
  setShops() {
    ShopServices().fetchShops().then((value) {
      setState(() {
        if (value != null) {
          for (int i = 0; i < value.length; i++) {
            shops.add(Shops(
              type: value[i].type,
              shopStatus: value[i].shopStatus,
              rewards: value[i].rewards,
              id: value[i].id,
              shopName: value[i].shopName,
              shopAddress: value[i].shopAddress,
              markerShop: value[i].markerShop,
              createdAt: value[i].createdAt,
              updatedAt: value[i].updatedAt,
            ));
          }
        }
      });
    });
  }

  void onIconPressed() {
    final animationStatus = _animationControler.status;
    final isAnimationDone = animationStatus == AnimationStatus.completed;
    if (isAnimationDone) {
      isOpenNSink.add(false);
      _animationControler.reverse();
    } else if (Provider.of<ProfileSideBar>(context, listen: false).isOpen ==
        false) {
      isOpenNSink.add(true);
      _animationControler.forward();
    }
  }

  @override
  void initState() {
    setShops();
    getCurrentPosition();

    setLocation();

    _animationControler =
        AnimationController(vsync: this, duration: _animationDuration);
    isOpenStreamController = PublishSubject<bool>();

    isOpenNStream = isOpenStreamController.stream;
    isOpenNSink = isOpenStreamController.sink;
    super.initState();
  }

  @override
  void dispose() {
    _animationControler.dispose();
    isOpenStreamController.close();
    isOpenNSink.close();
    EasyGeofencing.stopGeofenceService();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    var height = size.height;
    var width = size.width;

    return StreamBuilder<bool>(
        initialData: false,
        stream: isOpenNStream,
        builder: (context, isOpenAsync) {
          return AnimatedPositioned(
            duration: _animationDuration,
            top: isOpenAsync.data == false ? height * 0.91 : height * 0.24,
            bottom: AppSize.s1_5,
            right: AppSize.s1_5,
            left: AppSize.s1_5,
            child: Column(
              children: [
                Align(
                  child: GestureDetector(
                    onTap: () {
                      onIconPressed();
                    },
                    child: Container(
                      //  alignment: Alignment.cen,
                      padding: const EdgeInsets.only(
                        left: AppMargin.m60,
                        right: AppMargin.m60,
                        top: AppMargin.m8,
                      ),
                      child: Icon(
                        isOpenAsync.data == true
                            ? Icons.close
                            : Icons.wallet_giftcard,
                        size: AppSize.s28,
                        color: ColorManager.primary,
                      ),
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(AppSize.s40),
                            topRight: Radius.circular(AppSize.s40)),
                      ),
                    ),
                  ),
                ),
                Expanded(
                    child: Container(
                        margin: const EdgeInsets.only(
                            left: AppMargin.m16, right: AppMargin.m16),
                        height: height / 1.4,
                        width: width,
                        decoration: BoxDecoration(
                          color: ColorManager.white,
                          borderRadius: const BorderRadius.only(
                              topLeft: Radius.circular(AppSize.s28),
                              topRight: Radius.circular(AppSize.s28)),
                        ),
                        child: Column(
                          children: [
                            Center(
                              child: Giftcart(
                                  ontap: () {
                                    EasyGeofencing.startGeofenceService(
                                        pointedLatitude: '36.837134',
                                        pointedLongitude: "10.239917",
                                        radiusMeter: "100",
                                        eventPeriodInSeconds: 5);
                                    geofenceStatusStream =
                                        EasyGeofencing.getGeofenceStream()!
                                            .listen((status) {
                                      setState(() {
                                        print(status.toString());
                                        geofenceStatus = status.toString();
                                      });
                                    });
                                  },
                                  shopName: "shopName",
                                  details: "details",
                                  imagePath: ImageAssets.logo1),
                            ),
                          ],
                        ))),
                ElevatedButton(
                    onPressed: () {
                      EasyGeofencing.stopGeofenceService();
                      geofenceStatusStream?.cancel();
                    },
                    child: Text("stop"))
              ],
            ),
          );
        });
  }
}


text:
Q: How to use JavaScript to dynamically update the Bugzilla Additional Comments textarea? I am customising Bugzilla and I need to update the text in the Additional Comments text area on the bug editing page. This text will need to be changed dynamically depending on which status the user selects from the drop down menu. For this I'm hoping to use the onChange event. Has anyone any suggestions on how to implement this?

A: Here is an example that may illustrate one way of doing it:
<html>
<head>
<script>
var messages = ['Message 0', 'Message 1', 'Message 2', 'Message 3', 'Message 4'];
function myOnChangeHandler(selectObj) {
    // if there are more elements with name="additional_info" then you should attach unique id to your text area and use getElementById instead
    var textAreaElement = document.getElementsByName("additional_info")[0];
    textAreaElement.value = messages[selectObj.selectedIndex];
}

</script>
</head>
<body>
<form>
<select id="continent" onchange="myOnChangeHandler(this);">
    <option value="0">Select a Continent</option>
    <option value="1">North America</option>
    <option value="2">South America</option>
    <option value="3">Asia</option>
    <option value="4">Europe</option>
  </select>
  Additional info:
 <textarea cols="80" rows="8" style="" name="additional_info"></textarea>
</form>
</body>
<html>

Hope that this helps!


text:
Q: Removing a column from a matrix I'm a bit new to R and wanting to remove a column from a matrix by the name of that column. I know that X[,2] gives the second column and X[,-2]  gives every column except the second one. What I really want to know is if there's a similar command using column names. I've got a matrix and want to remove the "sales" column, but X[,-"sales"] doesn't seem to work for this. How should I do this? I would use the column number only I want to be able to  use it for other matrices later, which have different dimensions. Any help would be much appreciated.

A: I'm not sure why all the answers are solutions for data frames and not matrices.
Per @Sotos's and @Moody_Mudskipper's comments, here is an example with the builtin state.x77 data matrix.
dat <- head(state.x77)
dat
#>            Population Income Illiteracy Life Exp Murder HS Grad Frost   Area
#> Alabama          3615   3624        2.1    69.05   15.1    41.3    20  50708
#> Alaska            365   6315        1.5    69.31   11.3    66.7   152 566432
#> Arizona          2212   4530        1.8    70.55    7.8    58.1    15 113417
#> Arkansas         2110   3378        1.9    70.66   10.1    39.9    65  51945
#> California      21198   5114        1.1    71.71   10.3    62.6    20 156361
#> Colorado         2541   4884        0.7    72.06    6.8    63.9   166 103766

# for removing one column
dat[, colnames(dat) != "Area"]
#>            Population Income Illiteracy Life Exp Murder HS Grad Frost
#> Alabama          3615   3624        2.1    69.05   15.1    41.3    20
#> Alaska            365   6315        1.5    69.31   11.3    66.7   152
#> Arizona          2212   4530        1.8    70.55    7.8    58.1    15
#> Arkansas         2110   3378        1.9    70.66   10.1    39.9    65
#> California      21198   5114        1.1    71.71   10.3    62.6    20
#> Colorado         2541   4884        0.7    72.06    6.8    63.9   166

# for removing more than one column
dat[, !colnames(dat) %in% c("Area", "Life Exp")]
#>            Population Income Illiteracy Murder HS Grad Frost
#> Alabama          3615   3624        2.1   15.1    41.3    20
#> Alaska            365   6315        1.5   11.3    66.7   152
#> Arizona          2212   4530        1.8    7.8    58.1    15
#> Arkansas         2110   3378        1.9   10.1    39.9    65
#> California      21198   5114        1.1   10.3    62.6    20
#> Colorado         2541   4884        0.7    6.8    63.9   166

#be sure to use `colnames` and not `names`
names(state.x77)
#> NULL

Created on 2020-06-27 by the reprex package (v0.3.0)

A: my favorite way:
# create data
df <- data.frame(x = runif(100),
                 y = runif(100),
                 remove_me = runif(100),
                 remove_me_too = runif(100))

# remove column
df <- df[,!names(df) %in% c("remove_me", "remove_me_too")]

so this dataframe:
> df
              x           y  remove_me remove_me_too
1   0.731124508 0.535219259 0.33209113   0.736142042
2   0.612017350 0.404128030 0.84923974   0.624543223
3   0.415403559 0.369818154 0.53817387   0.661263087
4   0.199780006 0.679946936 0.58782429   0.085624708
5   0.343304259 0.892128112 0.02827132   0.038203599

becomes this:
> df
              x           y
1   0.731124508 0.535219259
2   0.612017350 0.404128030
3   0.415403559 0.369818154
4   0.199780006 0.679946936
5   0.343304259 0.892128112

A: As always in R there are many potential solutions. You can use the package dplyr and select() to easily remove or select columns in a data frame.

df <- data.frame(x = runif(100),
                 y = runif(100),
                 remove_me = runif(100),
                 remove_me_too = runif(100))

library(dplyr)
select(df, -remove_me, -remove_me_too) %>% head()
#>            x           y
#> 1 0.35113636 0.134590652
#> 2 0.72545356 0.165608839
#> 3 0.81000067 0.090696049
#> 4 0.29882204 0.004602398
#> 5 0.93492918 0.256870750
#> 6 0.03007377 0.395614901

You can read more about dplyr and its verbs here.

A: As a general case, if you remove so many columns that only one column remains, R will convert it to a numeric vector. You can prevent it by setting drop = FALSE.
(df <- data.frame(x = runif(6),
                  y = runif(6),
                  remove_me = runif(6),
                  remove_me_too = runif(6)))
#           x          y remove_me remove_me_too
# 1 0.4839869 0.18672217 0.0973506    0.72310641
# 2 0.2467426 0.37950878 0.2472324    0.80133920
# 3 0.4449471 0.58542547 0.8185943    0.57900456
# 4 0.9119014 0.12089776 0.2153147    0.05584816
# 5 0.4979701 0.04890334 0.7420666    0.44906667
# 6 0.3266374 0.37110822 0.6809380    0.29091746

df[, -c(3, 4)]
#           x          y
# 1 0.4839869 0.18672217
# 2 0.2467426 0.37950878
# 3 0.4449471 0.58542547
# 4 0.9119014 0.12089776
# 5 0.4979701 0.04890334
# 6 0.3266374 0.37110822

# Result is a numeric vector
df[, -c(2, 3, 4)]
# [1] 0.4839869 0.2467426 0.4449471 0.9119014 0.4979701 0.3266374

# Keep the matrix type
df[, -c(2, 3, 4), drop = FALSE]
#           x
# 1 0.4839869
# 2 0.2467426
# 3 0.4449471
# 4 0.9119014
# 5 0.4979701
# 6 0.3266374


text:
Q: Nextjs path invoked from browser return 404 (Nextjs, NGINX) How does the nextjs handle SEO? I am trying to render page by invoking it directly (localhost:8080/about) from the browser, but NGINX is returning 404. The link to same page embedded in the home page is working but the page can not be loaded directly using URL. Are additional configurations needed either in NGINX or Nextjs app.

A: Since you're using NGINX as your web server, you may want to reverse proxy to your NextJS app. https://medium.com/@deresegetachew/serving-react-spa-using-nginx-and-reverse-proxy-4e5485c814a0
React/NextJS uses port 3000 by default. Your URL in your post is pointing to port 8080. NGINX is not used by NextJS by default, so I believe a different web server is rendering your page, i.e. NGINX.
When you run the following commands on your nextjs project, you'll see the following output and it'll say what port is being served. Then try viewing that with your web browser.
$ npm install
$ npm run dev
...
[ wait ]  compiling ...
[ ready ] compiled successfully - ready on http://localhost:3000

If your have a server.js in your projects top directory, or you can add one to configure which port your app will serve. https://nextjs.org/docs/old#custom-server-and-routing
If your web server has a firewall enabled, not all ports will be available.

A: NextJS serves the site itself and doesn't use nginx or Apache.
In your package.json file, you should have a next command in the scripts section. I normally have:
  "scripts": {
    "build": "next build",
    "dev": "next"
  }

Running yarn dev or npm run dev will bootstrap the site and allow you to connect to the site locally and see how it handles 404s and other errors.
When you deploy your site, it will be using this kind of server set-up rather than either of the servers mentioned above.
I hope that's helpful.

A: Could you share some configuration code?
Out of the box nextjs should display the default export react component that lives under pages/about.js or pages/about/index.js /about when hitting https://localhost:8080/about.

A: Next.Js has it's on server so you don't have to use another one.
Just run the command npm run dev after installing the next.js using the command prompt for running locally in you machine.

A: maybe you run application on port 3000 and when you want to serve on another port for example 80 or 8080, you need redirect Nginx requests to port 3000 in this way that you make redirection in Nginx's config file :
(replace server-ip with your server ip or localhost or 127.0.0.1)
location / {
                proxy_pass http://<server-ip>:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Port $server_port;
        }

although you can run PM2 for manage and run your application on the server easily
as I saw your nginx serve nothing on 8080 port, that's why you didn't reach to your application on http://localhost:8000, so you can test with http://localhost:3000 because default port is 3000
that's  all it.


text:
Q: несколько ссылок на произвольные типы данных в админке вот код, который добавляет один тип данных и делает для него одну ссылку в админке wordpress
                function sliders_ent() {
                $args = array(
                        'label' => 'Слайдеры',
                        'labels' => array(
                                'edit_item' => 'Редактировать',
                                'add_new_item' => 'Добавить новый',
                                'view_item' => 'Показать',
                        ),
                        'singular_label' => 'Передача данных для юридических',
                        'public' => true,
                        'show_ui' => true, // показывать в админке?
                        'has_archive'=>true,
                        '_builtin' => false, // это не встроенный тип данных
                        '_edit_link' => 'post.php?post=%d',
                        'capability_type' => 'post',
                        'hierarchical' => true,
                        'rewrite' => array(
                                        "slug" => '',
                                        'with_front'=>true
                                    ), // формат ссылок
                        'supports' => array('title', 'editor', 'page-attributes')
                );

                // регистрируем новый тип
                register_post_type( 'sliders-ent' , $args ); // первый параметр - это название нашего нового типа данных

            }

            add_action('init', 'sliders_ent');

вот картинка - слева то что есть а справа как я хочу чтоб было

A: Решил правда с помощью плагина, так что вопрос еще все равно открыт
только почему так всегда - если хочешь что-то узнать по теме программирования лучше задавать по английски?
типа ok google: wordpress pinned labels in left dashboard


text:
Q: How do I update my List view to list discovered bluetooth devices? So I have made a list view to list the discovered bluetooth devices for when I click a button. The problem appears when I click the button with startDiscovery() in it. The listView doesn't list anything.
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="serenaApp.serenaapp">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".ProfileScreen"></activity>
    <activity
        android:name=".LoginScreen"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".AjustesConexionSensores">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Layout:
<Button
    android:id="@+id/botDesc"
    style="@style/Base.Widget.AppCompat.Button.Colored"
    android:layout_width="266dp"
    android:layout_height="wrap_content"
    android:minWidth="200dp"
    android:background="@color/naranjaApp"
    android:text="Descubrir" />

<ListView
    android:id="@+id/scanLv"
    android:layout_width="match_parent"
    android:layout_height="277dp" />

AjustesConexionesSensores:
Even if I put startDiscovery() in my mBotDescubrir and below add the devices to the list, it won't list anything and it won't update the listView.
ListView scanLv
ArrayList<String> devsAL = new ArrayList<>();
ArrayAdapter<String> devsAAd;
Button mBotDescubrir;
BluetoothAdapter mBlueAdapter;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ajustes_conexion_sensores);

    mBotDescubrir = findViewById(R.id.botDesc);
    scanLv = findViewById(R.id.scanLv);

    mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

mBotDescubrir.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mBlueAdapter.startDiscovery();

        }
    });

    IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(bReceiver, intentFilter);

    devsAAd = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,devsAL);
    scanLv.setAdapter(devsAAd);

   }

    BroadcastReceiver bReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)){
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            devsAL.add(device.getName());
            devsAAd.notifyDataSetChanged();
        }
    }
};

I'm really stuck so help is much appreciated


text:
Q: Fazer pesquisa somente de um tipo de registro no banco de dados e mostrar no DataGrid Como faz para fazer uma pesquisa no banco e mostrar no DataGrid, so que eu seleciono uma categoria
não estou sabendo como fazer esse tipo de busca no banco, quando eu selecionar no ComboBox1 a palavra ativo, ele me traz somente os produtos ativos, porém eu queria fazer fazer o  meu textBox pesquisar somente o nome dos produtos ativos.
vamos supor que tenho dois produtos com o mesmo nome, porém um está ativo e o outro inativo, se eu selecionar ativo ele busca somente esse nome que esta ativo
código que estou utilizando(ao menos tentando fazer isso):
 private void txtBusca_TextChanged(object sender, EventArgs e)
    {
        if(comboBox1.Text == "Ativo")
        {
            string strSelect = "SELECT * FROM Produto WHERE Nome LIKE (@Nome)";

            using (MySqlConnection conn = new MySqlConnection("server=127.0.0.1;database=ProdPacote; Uid=root; pwd=1234;"))
            {
                MySqlDataAdapter da = new MySqlDataAdapter(strSelect, conn);
                //Passagem por parâmetros.
                da.SelectCommand.Parameters.AddWithValue("@Nome", txtBusca.Text + "%");
                DataSet ds = new DataSet();
                da.Fill(ds, "Nome");
                dataGridView1.DataSource = ds.Tables["Nome"];
            }
        }

A: Tens que usar no teu query outro filtro para te trazer só os activos,
presumindo que isso já está marcado na tabela Produto.
string strSelect = "SELECT * FROM Produto WHERE Nome LIKE (@Nome) AND Activos=true";


text:
Q: Efficient way to store multiple values of an x,y location in Python? I am trying to read values from a stack of images and store them in a structure that will allow for easy readability. My current idea is to create a loop
for x in width:
    for y in length:
        for z in height:

and try appending the z value to a list at [x, y]. The issue with this technique is that I do not know how to prevent losing the x and y position through the iteration and it seems rather inefficient.
The input data will consist of z values extracted from tiff images. I am reading them by first creating a stack through a loop statement
for i, fname in enumerate(image_files):
img = cv2.imread(fname, cv2.CV_LOAD_IMAGE_UNCHANGED)
img_stack[:,:,i] = img

which I found here: https://stackoverflow.com/a/20056062/1342580 (CV2 is only returning nan for me but that's a different question)
After the stack is created I used to loop at the beginning of my question to go through all of the pixels (which at the moment is 3858 x 3742) and append the z value of an x,y location from each image to the x,y value (for example if I had 4 images in the stack the result at position 1, 1 would be [1, 1, Z1, Z2, Z3, Z4]. Then I append that to another list that will contain a list for every x,y position
Is there a better technique for doing this?

A: You could try this:
width = [1,2,3]
length = [4,5,6]
height = [7,8,9]
allvalues = zip(width,length,height)

this will give you -> [(1,4,7),(2,5,8),(3,6,9)]

A: I would probably store the values in nested dictionaries, with the keys corresponding to x and y coordinates. The structure would be something like the following for a set of 3x3 images (where all of the x, y and z variables would be replaced with the actual x- and y-coordinates, and corresponding z-values, respectively):
z_stack = {x1:
              {y1: [z11a, z11b, z11c],
               y2: [z12a, z12b, z12c],
               y3: [z13a, z13b, z13c]},
           x2:
              {y1: [z21a, z21b, z21c],
               y2: [z22a, z22b, z22c],
               y3: [z23a, z23b, z23c]},
           x3:
              {y1: [z31a, z31b, z31c],
               y2: [z32a, z32b, z32c],
               y3: [z33a, z33b, z33c]}}

This way, a list of all z-values for coordinates x=3, y=2 (for example), would be returned by z_stack[3][2].
To construct this dictionary, you can use a modified your existing loop like this:
z_stack = {}
for x in width:
    z_stack[x] = {}
    for y in length:
        z_stack[x][y] = []
        for z in height:
            z_stack[x][y].append(z)


text:
Q: How can I only UPDATE if the user was created? I got A cursor with some ifs like this one:
 IF @ROLE='RW'
            BEGIN
                SET @COMMAND ='
                USE '+QUOTENAME(@DATABASE)+'
                CREATE USER '+QUOTENAME(@LOGIN_ACESSO)+' FOR LOGIN '+QUOTENAME(@LOGIN_ACESSO)+' WITH DEFAULT_SCHEMA=[DBO]'+CHAR(13)+CHAR(10)+'
                USE '+QUOTENAME(@DATABASE)+'
                ALTER ROLE [DB_DATAREADER] ADD MEMBER '+QUOTENAME(@LOGIN_ACESSO)+'
                ALTER ROLE [DB_DATAWRITER] ADD MEMBER '+QUOTENAME(@LOGIN_ACESSO)
            END

PRINT @COMMAND
EXECUTE (@COMMAND)

UPDATE TBL_LOGINPERMISSAO SET CRIADO =1 WHERE [ID]=@ID

But obviously, even if the user was not created, I update TBL_LOGINPERMISSAO. How can I update only if the user was created? even copying this update on all ifs, it does not work, because even not creating the user will reach the UPDATE.
is this a case for try/catch?

A: Taking into account that you need to check the user for a specific database,
you could do something like this?
SET @COMMAND =
'USE '+@DATABASE+'
 SELECT name FROM sys.sysusers WHERE name = '''+@LOGIN_ACESSO+''''
DECLARE @t TABLE (LOGIN_ACESSO NVARCHAR(255))
INSERT INTO @t
EXECUTE  (@COMMAND)
IF exists (select LOGIN_ACESSO from @t)
BEGIN
    UPDATE TBL_LOGINPERMISSAO SET CRIADO =1 WHERE [ID]=@ID
END

A: You can perform the UPDATE only if the user EXISTS like this:
SET @COMMAND = '
    IF EXISTS (
      SELECT 1 FROM ' + QUOTENAME(@DATABASE) + '.sys.sysusers
      WHERE name = ''' + @LOGIN_ACESSO + '''
    )
    BEGIN
      UPDATE TBL_LOGINPERMISSAO SET CRIADO = 1 WHERE [ID] = ' + CAST(@ID AS nvarchar(max)) + '
    END'
EXEC (@COMMAND)

You'll need to add quotes around the @ID part if it not a numeric value, e.g. (n)varchar or guid.


text:
Q: For △ABC, prove $\frac a{h_a} + \frac b{h_b} + \frac c{h_c} \ge 2 (\tan\frac{\alpha}2+ \tan\frac{\beta}2 + \tan\frac{\gamma}2)$
Given $\triangle ABC$, (using the main parameters and notation), prove that $$ \frac{a}{h_a} + \frac{b}{h_b} + \frac{c}{h_c} \ge 2 \cdot \left(\tan\frac{\alpha}{2} + \tan\frac{\beta}{2} + \tan\frac{\gamma}{2}\right)$$

Great, another problem that already has a solution. We have many ways of expressing the area of a triangle, for example $$2 \cdot [ABC] = \frac{abc}{2R} = \sqrt{2(a + b + c) \cdot \sum_{cyc}\frac{c + a - b}{2}} = ah_a = bh_b = ch_c$$
The above equations are used in the solution I have provided below.
I would be greatly appreciated if you could come up with any other solutions.

A: In the standard notation we need to prove that:
$$\sum_{cyc}\frac{a}{\dfrac{2S}{a}}\geq2\sum_{cyc}\sqrt{\frac{1-\frac{b^2+c^2-a^2}{2bc}}{1+\frac{b^2+c^2-a^2}{2bc}}}$$ or
$$\sum_{cyc}a^2\geq4S\sum_{cyc}\sqrt{\frac{(a+b-c)(a+c-b)}{(b+c-a)(a+b+c)}}$$ or
$$\sum_{cyc}a^2\geq\sum_{cyc}(a^2-(b-c)^2),$$ which is obvious.

A: Use the sine rule and the area formuli of the triangle $\frac12 h_a a = \frac12 bc\sin\alpha$, $\frac12 h_b b = \frac12 ca\sin\beta$, $\frac12 h_c c = \frac12 ab\sin\gamma$ to express
$$\frac{a}{h_a} + \frac{b}{h_b} + \frac{c}{h_c} = \frac{\sin^2\alpha +\sin^2\beta+\sin^2\gamma}{\sin\alpha \sin\beta\sin\gamma}\tag 1$$
Then, evaluate
$$\sin^2\alpha- 2\sin\alpha \sin\beta\sin\gamma\cdot\tan\frac{\alpha}{2}$$
$$=4\sin^2\frac{\alpha}2\cos^2\frac{\alpha}2-4\sin^2\frac{\alpha}2\sin\beta\sin\gamma
=2\sin^2\frac{\alpha}2\left(2\cos^2\frac{\alpha}2-2\sin\beta\sin\gamma\right)$$
$$=2\sin^2\frac{\alpha}2\left(1+\cos\alpha-\cos(\beta-\gamma)+\cos(\beta+\gamma)\right)
= 4\sin^2\frac{\alpha}2\sin^2\frac{\beta-\gamma}2\tag 2\ge 0$$
and, similarly,
$$\sin^2\beta-2\sin\alpha\sin\beta\sin\gamma\cdot\tan\frac{\beta}{2} =4\sin^2\frac{\beta}2\sin^2\frac{\alpha-\gamma}2\ge 0 \tag 3$$
$$\sin^2\gamma-2\sin\alpha \sin\beta\sin\gamma\cdot\tan\frac{\gamma}{2}=4\sin^2\frac{\gamma}2\sin^2\frac{\alpha-\beta}2 \ge 0\tag 4$$
As a result, $(2)+(3)+(4)$ leads to
$$\sin^2\alpha +\sin^2\beta+\sin^2\gamma\ge
2\sin\alpha \sin\beta\sin\gamma\left(\tan\frac{\alpha}{2}+\tan\frac{\beta}{2}+\tan\frac{\gamma}{2}\right)$$
Substitute the inequality into $(1)$ to obtain,
$$\frac{a}{h_a} + \frac{b}{h_b} + \frac{c}{h_c} \ge 2\left(\tan\frac{\alpha}{2}+\tan\frac{\beta}{2}+\tan\frac{\gamma}{2}\right)$$

A: Using the double-angle and half-angle trigonometric identities, we have that $$2 \cdot \sum_{cyc}\tan\frac{\beta}{2} = 2 \cdot \sum_{cyc}\frac{\sin\beta}{\cos^2\dfrac{\beta}{2}} = \frac{1}{R} \cdot \sum_{cyc}\frac{b}{\cos\beta + 1} = \frac{2abc}{R} \cdot \sum_{cyc}\frac{1}{(c + a)^2 - b^2}$$
$$ = \frac{8 \cdot [ABC]}{a + b + c} \cdot \sum_{cyc}\frac{1}{c + a - b} = \frac{1}{2 \cdot [ABC]}\cdot \sum_{cyc}(a + b - c)(b + c - a)$$
$$ = \frac{1}{2\cdot [ABC]} \cdot \sum_{cyc}[b^2 - (c - a)^2] \le \frac{a^2 + b^2 + c^2}{2 \cdot [ABC]} = \sum_{cyc}\frac{b}{h_b}$$


text:
Q: Static library not working after update of Monotouch/Xamarin About two years ago I built an image viewer into my Monotouch application. See this question of mine from way back when I was looking for an image viewer for monotouch. I used the source of MTGallery and used btouch to bring this into my Monotouch application. This worked perfectly and has been working perfectly for the last two years. But at some point in the last six months one of the updates that I did to Monodevelop has broken this functionality. Now the viewer is not showing the image, it is just showing a blank screen. The source for this hasn't changed, in fact it I still have the compiled library that was compiled two years ago.
I know that at the end of last year, I could compile my Monotouch application and the image viewer would work correctly. I have a backup of the application source from December 2012. If I deploy the version that was compiled then to my iPad it works correctly. But if I recompile the same source now without making any changes to the source or the settings in Monodevelop, it doesn't work.
So, this is what I have tried: Updated Monodevelop (I had to upgrade my Mac OS to Mountain Lion to be able to do this). Installed Xamarin Studio and got a new license for this development environment. The image viewer does not work when compiled in either Monodevelop or Xamarin Studio. I have tried recompiling the Objective-C library. I tried using btouch again to recreate the C# files for inclusion in my project.
Nothing I have tried so far has helped. Does anyone have any idea what could be causing this issue and what I could try changing to get this working.
UPDATE:
I am now a step further; I have determined that the static library is in fact being called and if I rotate my iPad the image is then showing in the viewer, but is not showing before a rotation takes place. From looking at the Objective-C code it appears that the image was initially being loaded by the scrollViewDidEndDecelerating delegate method of the UIScrollView. It seems that this is now not firing when the image viewer loads, whereas previously it was firing.

A: If it did work and suddenly doesn't without any change from you, it's probably a bug in Xamarin.iOS/Studio. The best way to get this fixed is to create a bug (http://bugzilla.xamarin.com) and attach your project so we can have a look at it.


text:
Q: What is the Cartesian Product of two nonempty sets, one of which includes Ø as an element? Let $A=\{1,2,3\}$ and $B=\{a, b, \{\emptyset\}\}$. Does $A \times B = \{\emptyset\}$ or is it something more like $A \times B = \{ (1, a), (1, b), \{\emptyset\}, (2, a), (2, b),\{\emptyset\}, (3, a), (3, b), \{\emptyset\} \}$?

A: Neither are correct, but the second is closer. It should be
$$A \times B = \left\{ (1, a), (1, b), (1, \{\emptyset\}), (2, a), (2, b), (2,\{\emptyset\}), (3, a), (3, b), (3,\{\emptyset\}) \right\}.$$
After all, $\{\emptyset\}$ is an element just like any another.
Also, $\{\emptyset\}$ is not the empty set. It is a set that contains only the empty set. Make sure you are familiar with the distinction.

A:
$$(A \times B):= \{({\color{Red}y},{\color{green}z})| {\color{Red}y}
 \in A \wedge {\color{green}z} \in B\}$$

By definition we have also following:
$$\begin{array}{}
\begin{array}{c|c|c}
(A \times B)&{\color{green}a} \in B&  {\color{green}b} \in B& {\color{green}\{{\color{green}\emptyset{\color{green}\}}}} \in B\\ \hline
{\color{Red}1} \in A&({\color{Red}1},{\color{green}a})&({\color{Red}1},{\color{green}b})&({\color{Red}1},{\color{green}\{{\color{green}\emptyset{\color{green}\}}}} )\\
{\color{Red}2} \in A&({\color{Red}2},{\color{green}a})&({\color{Red}2},{\color{green}b})&({\color{Red}2},{\color{green}\{{\color{green}\emptyset{\color{green}\}}}} )\\
{\color{Red}3} \in A&({\color{Red}3},{\color{green}a})&({\color{Red}3},{\color{green}b})&({\color{Red}3},{\color{green}\{{\color{green}\emptyset{\color{green}\}}}} )\\
\end{array}&&&
\end{array}$$
 $$(A \times B)=\{({\color{Red}1},{\color{green}a}),({\color{Red}1},{\color{green}b}),({\color{Red}1},{\color{green}\{{\color{green}\emptyset{\color{green}\}}}} ),({\color{Red}2},{\color{green}a}),({\color{Red}2},{\color{green}b}),({\color{Red}2},{\color{green}\{{\color{green}\emptyset{\color{green}\}}}} ),({\color{Red}3},{\color{green}a}),({\color{Red}3},{\color{green}b}),({\color{Red}3},{\color{green}\{{\color{green}\emptyset{\color{green}\}}}} )\}$$


text:
Q: looking for context of words inside corpus categories doesn't work I wrote this little script to find the context of the 10 most frequent words in my corpus. But it doesn't work and I have no idea what I'm doing wrong.The tien_frequentste(mijn_corpus) definition works on it's own.
tienfrequentste = tien_frequentste(mijncorpus)
def context (corpus, most_freq):
   for category in corpus.categories():
     print "Context voor" , category, ":"
       for word in most_freq:
           print nltk.Text(corpus.words(categories=category)).concordance(word)

UPDATE:
I get an error message on traceback
for context(corpus, most_freq),
for category in corpus.categories(),
for self.init()
and in_init.
And an AttributeError:'NoneType' object has no attribute 'group'.
No idea what these errors mean..
Traceback (most recent call last):
 File "/Users/...document.py", line 92, in <module> context (mijn_corpus, tienfrequentste)

 File "/Users/...document.py", line 87, in context for category in corpus.categories(): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk.corpus.reader.api.py, line 317, in categories self.init().

File "/Users/...document.py", line 87, in context for category in corpus.categories(): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk.corpus.reader.api.py, line 289, in_init category = re.match(self._pattern, file id).group(1)

attributeError: 'Nonetype' object has no attribute "group"

A: Does your corpus have categories and is most_freq a list of strings? The following example works:
from nltk.corpus import reuters
for category in reuters.categories():
print "context voor", category, " : "
for word in ["get", "have", "do"]:
    print nltk.Text(reuters.words(categories=category)).concordance(word)

A: The error is coming from the regular expression that assigns corpus files to categories. It's stumbling on a filename that doesn't match the regexp pattern. If you're using a standard NLTK corpus with categories, you must have put an extra file in the corpus directory. If you're using your own corpus, it's misconfigured.
Incidentally, concordance() prints its output and returns None. If you use print with it, you'll see a whole bunch of None values.


text:
Q: changing header based on URL in Angular in my application I have two apps inside, first one is Basic which has routes like:
localhost:4200/form,
localhost:4200/reports,
localhost:4200/views,
but now I have now on the second which is Advanced, I want to set routes like:
localhost:4200/advanced/views
localhost:4200/advanced/forms
and the header should be different as well.
here is my app-routing.module.ts:
  const routes: Routes = [
      { path: 'report', component: ReportComponent },
      { path: 'form', component: RequestFormComponent},
      {
        path: 'advanced',
        component: AdvancedLevelComponent,
      },
      { path: 'aform', component: PmCustomerFormComponent }

    // I have tried:
    {
        path: 'advanced',
        component: AdvancedLevelComponent,
        childern:[
            {{ path: 'aform', component: PmCustomerFormComponent }}
        ]
      },
      // but it it asks for <router-outlet></router-outlet> in that component and hence it
render view in same page, I want it be like go to new page with URL: /advanced/aForm

and my header file:
<mat-toolbar>

   Basic

</mat-toolbar>
<mat-toolbar *ngIf="router.url==='/advanced'">

  Advanced

</mat-toolbar>

but route.url only works for the main advanced page not for it sub pages

A: I have fixed it:
in your header.ts
import {Location,LocationStrategy,PathLocationStrategy } from '@angular/common';

and
   @Component({
     providers: [
     Location,
     { provide: LocationStrategy, useClass: PathLocationStrategy }
     ]
)}

and create function like:
isAdvancedRoute(): boolean {
        return this.location.path().indexOf('/advanced') > -1;
      }

finally at
.html
*ngIf="isAdvancedRoute()"


text:
Q: Python_Pandas - Populating new row with condition I am trying to go through my Dataframe and create another row named 'Conversions'.
I would like the "Conversions" row only to populate when the "Currency" row is "EUR" and pass over if it is not EUR
Once an "EUR" currency has been identified, I would like to multiply it by the JPY object which is 2
Current DF looks like this:
Name     Currency     Amount
a        EUR          12.00
b        USD          10.00
c        EUR           8.00
d        JPY          100.00
e        EUR          567.00

Once Executed, I would want the finished product to look like this:
Name     Currency     Amount  Conversions
a        EUR          12.00      24.00
b        USD          10.00      20.00
c        EUR           8.00      16.00
d        JPY          100.00    200.00
e        EUR          567.00   1134.00

*the data is in a csv.
Please see my attempt below:
import csv
import pandas as pd
import numpy as np
JPY = (2)

df = pd.read_csv('df.csv', delimiter=";")

for i in df.iteritems():
    if df.loc[(df['Currency'] == 'EUR')]:
        df['Conversions']= (df.to_numeric(df['Amount']*(JPY)))

Shell Response -
ValueError: The truth value of a DataFrame is ambiguous.  Use a.empty, a.bool(), a.item(), a.any() or a.all()
Thanks in advance for any assistance you can provide this newb.

A: use np.select no need to use a loop:
# your condition
conditions = [
    df['Currency'] == 'EUR'
]

# if condition is met
choices = [
    df['Amount']*2
]

# create a new column and a default value if no condition is met
# you can always change the default value to np.nan if you do not want a value
df['Conversions'] = np.select(conditions, choices, default=df['Amount'])

    Name    Currency    Amount  Conversions
0   a            EUR    12.0    24.0
1   b            USD    10.0    10.0
2   c            EUR    8.0     16.0
3   d            JPY    100.0   100.0
4   e            EUR    567.0   1134.0


text:
Q: How can i replace tab spaces by ',' in a file using python? I have a file with level, equation and answer (separated by tabs), for a math game. For example:
Lvl     Eq      Ans
2       2*6     12

How can I replace the tab space by a comma , in a new file?

A: Use the str.replace() method like this:
>>> s = '2\t2*6\t12'
>>> print s
2       2*6     12
>>> s.replace('\t', ',')
2,2*6,12

A: Read the lines from the old file and replace '\t' with ',' in the new file. This should do:
with open('oldfile.txt') as fin, open('newfile.txt', 'w') as fout:
    for line in fin:
        fout.write(line.replace('\t', ','))


text:
Q: Alamofire and update for Swift 3 I just updated to Xcode 8 and to Alamofire 4.0, and I got some odd errors. The first one is a bunch of errors looking like this:

... warning: Missing file: ... is missing from working copy

This goes on for Download.swift, Manager.swift, Stream.swift, Upload.swift and Error.swift. How to solve that one?
Furthermore I got this one, only for alamofire, not for any other of my libraries:

"Use Legacy Swift Language Version" (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

And when I try to convert it, I get

Could not find test host for FieldSenseAppTests: TEST_HOST evaluates to ..."

A: I am able to fix it by setting Use Legacy Swift Language Version to "No" under Build Setting section.

A: There's no need to convert anything. Revert the changes you've made (reinstall Alamofire) and do the following:
Select your project (Pods I assume), select Alamofire as a target and go to build settings.
Wnder "Swift Compiler" you can find "Use Legacy Swift Language Version", which you need to set to "No".

A: *

*Close Xcode.

*Edit your podfile, comment out the line for alamofire.

*Save and run 'pod install'. This will remove alamofire.

*Edit your podfile, uncomment the line for alamofire. Make sure your alamofire version is 4.0

*Save and run 'pod install' to install alamofire.

*Open your Xcode workspace

*Run migrator, select alamofire target. UNCHECK the suggested changes for alamofire and save.

*Try to build.

A: I had the same exact problem and here is how I fixed it:

*

*Copy your Xcode project folder and paste it into another directory.

*Open and build the copied project to see if the missing file warnings went away.

*If they did, replace your original project with the copied one.

As far as your 'Legacy Swift' issue, see this post.


text:
Q: Following a tutorial but can't figure out why I'm getting this message: "Property 'substring' does not exist on type '() => WordArray'.ts(2339)" I'm a beginner following a yt blockchain tutorial on visual code yet i'm getting this message when using substring: Property 'substring' does not exist on type '() => WordArray'.ts(2339)
class Block {
    constructor(index, timestamp, data, previousHash = ''){
        this.index = index;
        this.timestamp = timestamp;
        this.data = data;
        this.previousHash = previousHash;
        this.hash = this.calculateHash;
        this.nonce = 0;
    }

    calculateHash(){
        return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce.toString());

    }

    mineBlock(difficulty){
        while(this.hash().substring(0, difficulty) !== Array(difficulty + 1).join("0")){
            this.nonce++;
            this.hash = this.calculateHash();
        }

        console.log("Block mined: " + this.hash);
    }

}

A: this.hash is a function that returns some kind of list. There is no substring method on the function itself, only on the result.
You need to use this.hash() to call the function to get its result. Then this.hash().substring might work.

A: The issue is you are trying to use substring method on a non String class.
I'm going to assume you're using the CryptoJS implementation of SHA256 given the capitalization. If not I'll delete the answer, but you need to convert the hash to a String class in order to use the substring method. The SHA256 does not return a string and you need to convert it to one in order to apply string methods to it.
Changing the calculateHash method to this should make the code work:
calculateHash(){
  return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce.toString()).toString();
  }

More info can be found in the docs