text:
Q: Amazon Web services - retrieving a wishlist I've been tinkering with Yahoo Pipes and the Amazon Product Advertising API (formerly ECS) SDK to retrieve my wishlist.
The problem is that although I can get all the items on my wishlist just fine, it seems to include items that I've deleted too.
Has anyone else used this API and noticed this? Is there a way around it?
UPDATE:
Requested additional information in comments...
Here is the URL I use to fetch the wishlist XML:
http://webservices.amazon.co.uk/onca/xml?SubscriptionId=[my subs id]&Service=AWSECommerceService&ResponseGroup=ListItems&ProductPage=1&ProductGroup=Book&Operation=ListLookup&ListType=WishList&ListId=[my list id]

And here is the relevant part of the XML response:
<ListId>[my list id]</ListId>
<ListName>Wishlist</ListName>
<TotalItems>132</TotalItems>
<TotalPages>14</TotalPages>
<ListItem>
    <ListItemId>EPIE5559HKT391</ListItemId>
    <DateAdded>2003-11-17</DateAdded>
    <QuantityDesired>1</QuantityDesired>
    <QuantityReceived>0</QuantityReceived>
    <Item>
        <ASIN>5557205521</ASIN>
        <ItemAttributes>
            <Title>Horton hears a who</Title>
        </ItemAttributes>
    </Item>
</ListItem>
...

The rest of the XML is just either more list items like that, or information about the request at the top of the response.

A: I can't find anything to indicate whether the item has been deleted from the list in either the XML or in the documented parameters to send with the request. At this point, I guess your best bet is to start stalking the forum and ask there if stalking reveals nothing. Sorry, both for the lateness of this response and the fact that it's not overly helpful.

A: Ah. This is pilot error.
I would explain what I'd done wrong, but I'm too embarassed.
Deleted items do not show up in wish-lists after all. Yay.


text:
Q: create accessible tabs using bootstrap 3 I am creating a accessible site on bootstrap 3 but my problem is that tabs are not accessible.
how can i make tabs accessible.MY code is like this.Screen Reader reading it like link list

Tab 1

Tab 2

Tab 3

Tab 4

The Markup

Code here ...

Pane 2 Content

 and so on ...

Pane 3 Content

Pane 4 Content

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS Create a transparent div Is there a way to make a div HTML element half transparent?

A: This will work with every browser
div {
 -khtml-opacity:.50;
 -moz-opacity:.50;
 -ms-filter:"alpha(opacity=50)";
  filter:alpha(opacity=50);
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
  opacity:.50;
}

If you don't want transparency to affect the entire container and it's children, check this workaround http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/

A: Using a background PNG file which is half transparent, and hoping you don't have to support IE6?

A: With CSS, this is cross browser solution
div {
    opacity: 0.5;
    filter: alpha(opacity = 0.5);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
}

A: If you only want the background of your div semi-transparent, not any text and elements inside it, you can simply set a background-color to a transparent-one (i.e. with alpha < 1).
One example is at our website, a minimized example here:

  <title>Transparency test</title>

normal text

nontransparent

normal text


text:
Q: Update --strange interaction while probing circuit I'm encountering strange behavior from this Colpitts oscillator circuit when I probe what is an "isolated" output.  Probing an isolated output is causing another otherwise good output signal (also isolated via a buffer) to get distorted.  I've yet to understand how this interaction is occurring.

I breadboarded the circuit and the buffered sinewave output looks as expected when probed by itself (10X probe) as shown in the figure below in blue.

However, when I also probe the buffered (isolated) square wave drive signal, the sinewave output is significantly distorted as shown below.  The overshoot/ringing seen on the yellow trace goes away as expected if I reduce the length the ground clip,  so it is just an artifact of the probe set up.  The jagged blue trace seems to be "real".  The yellow trace is scaled at 5V/div, while the blue trace is at 1V/div.

It is strange that probing the output of U2 affects the output of U1 (as seen at the output of U3), since U2 is providing isolation and probing its output should not be loading U1.
On the board, I have 1nF decoupling caps on the comparator U1 as well as the unity gain buffers, and the +5V comes from a +5V regulator on the board whose input is decoupled with a 10uF in parallel with a 0.1nF cap. The grounding is not "great" since it is a simple bread board built on a vector board (as opposed to a copper clad board), although I've improved it with additional copper tape---I'm thinking this (inadequate grounding) may ultimately be the underlying cause of what I'm seeing, since the signal frequency is in the 10-15MHz range.
I thought the op-amps might be struggling to drive the ~15pF probe capacitance, but that doesn't gel with the fact that probing the sinewave output alone looks fine.  I need to monitor the supply while I probe the outputs to see if somehow the regulator is going out of regulation. Although I don't know why that would be, that makes more sense to me than anything else as to why the output at U3 would be affected by something on the output of U2 (again, perhaps grounding and insufficient decoupling are the underlying cause?).
I need to confirm this tomorrow, but I think that connecting the second probe's ground clip to the circuit ground begins distorting the sinewave output slightly.  Hanging the probe on the squarewave output signal is what ultimately distorts it to the level shown in the figure above. I ruled out some strange coupling between the probes by using probes connected to different o'scopes (although maybe I'm still creating a ground loop through the earth ground connection at the outlets).
Anyway, perhaps someone on here has experienced something similar to what I'm seeing and can shed some light on what may be happening.  I'd appreciate any input.
*** UPDATE ***
I now have a 2-layer board with all components on the top side, allowing for a solid ground plane on the  bottom layer as well as ground fill on the top layer.  Decoupling is done with a 10uF  in parallel with a .1nF cap on all the ICS, as well as a 100uF on the supply to the PCB.
At 1MHz, the circuit works as expected, and I can probe the outputs of U3 and U2 without any issues.  However, when I tune the resonator to 10MHz, I again see that probing the output of U2 distorts the the output of U3.  I can't tell if it is an artifact of the scope and probes (gnd lead inductance, etc), or if it is "real" .  In fact, U2 and U3 drive a light load to gnd, and there are test points accessible to monitor the ouptut signals. Just touching the testpoint on the output of U2 with tweezers (and me acting as a capacitor(?))is enough to completely distort the signal observed at U3.  The square wave output is unaffected, which suggests that perhaps what I'm seeing at U3 is not real --but I don't know to confirm this.
I broke the circuit between C2 and U3 (I have resistors in the actual circuit to divide signals, etc as needed) and injected a 10MHz sine wave with an function generator, and proved that it is not a bandwidth issue with U3 (and AD8061 opamp).  I am completely stumped.


text:
Q: UDP, NAT and setting up "connections" I know the word "connection" isn't really appropriate when talking about UDP, but...
How does a server (the one with the known IP) get its UDP packets through the Internet to a client that is behind NAT?
For example: say a client connects and authenticates to the server using some messaging over TCP. At this point the server is ready to start streaming data to the client over UDP, but how does the server know where to address the UDP packets so that they would find their way through any NAT routers to the client?
If the client fist sends an "I'm ready for the streaming please" message over UDP, would the NAT routers keep the port open so that the server can respond with its stream of UDP data?
Or am I waay off track here?

A: Ignoring the provision of known port translation (i.e. data on this port goes to this address) in your router (providing the NAT), you can use UDP Hole Punching.
I assume you're not talking about multicasting, in which each peer joins a group and announces that to interested parties (in this case the router), which can then perform the appropriate routing. Although that's normally used for routing traffic efficiently to multiple hosts, the routing-by-group mechanism would work for you're describing above.

A: Generally the NAT in front of the client at the TCP level will be able to determine that the connection at the UDP was create.  Having said that, the NAT on the client side will have to be configured to accept UDP packets from the SRC server port, and then forward them to the internal destination IP (client).  Important thing to remember if NAT is who is the caller and who is the callee.  NATs differ in implementation and capablity so a generic easy to implement solution is probably what you might want to implement, depending on your needs.
You are correct in assuming, i think, that in your case client will not be able to receive the UDP stream in information. In your case your client will have to send its WAN IP to your server to initiate the UDP connection.  Finding your clients WAN IP can be tricky but there are websites that will aid your determing your WAN IP by returning it in a text page.
If the UDP connection is created after the TCP connection by the server opening a socket to the client to a known UDP port then, UPnP might be worth looking into it will allow you to automatically set up your port forwards on your NAT, that is only if your NAT supports UPnP as is the case of DSL routers.
A work-a-round would be to client to open both TCP and UDP sockets to the server. Since the client behind the NAT initiated the connection the states of both TCP and UDP connections will be added to the NAT's connection table.

A: If you're talking about streaming protocols like SIP or RTSP then the way it works is that the UDP port the client wants the server to send to is specified in the call set up request.
The server will send to that port and the traffic may or may not get through to the client depending on whether the NAT has translated the clien't choice of port to a different number or not.
When the server receives it's first UDP streamed packet from the client and if it is on a different port to the one it was sending on then it will switch to it. This lets the UDP from the server get through the NAT since the client has already created the NAT mapping by sending to the server.


text: Q: Best practice for MySQL search in 5.0 I work on a website which stores longer texts in a database. It runs on a Godaddy shared server which only supports MySQL 5.0, so no FULLTEXT for InnoDB. It must be innoDB because of transactions, even these text fields are involved. What's the best practice to efficiently search words or expressions in these texts?


text:
Q: Rails 4 ActiveJobs using different enqueue adapter and having NoMethodError I am trying to run an ActiveJob job from a controller method, but it fails and I can't spot the right place of the issue:
#app/controllers/users_controller.rb
1   class UsersController < ApplicationController
2       def new
3         @user = User.new
4       end1
5
6     def create
7       @user = User.create(user_params)
8       PoliciesChecksJob.new(@user.id).enqueue
9       # redirect to somewhere
10   end1
11  end

#app/jobs/policies_checks_job.rb
class PoliciesChecksJob < ActiveJob::Base
  queue_as :default

  def perform(user_id)
    SearchPoliciesCommands.new.execute(user_id)
  end
end

Logs summary:
Started POST "/users" for ::1 at 2015-03-30 15:01:03 +0100
Processing by UsersController#create as HTML
...(params)
(0.1ms)  BEGIN
... (inserts the user)
(0.3ms)  COMMIT
[ActiveJob] Enqueued PoliciesChecksJob (Job ID: da...e2) to Sneakers(default) with arguments: 1

Completed 500 Internal Server Error in 76ms

NoMethodError (private method `warn' called for nil:NilClass):
app/controllers/users_controller.rb:8:in `create'

I'd appreciate any thought.

A: Basically there was a little problem with the enqueue adapter:
I prefer to use Sneakers due the fact that it does work fine with RabbitMQ.

*

*So I had to specify that I want a different enqueue adapter than the default one:

#config/application.rb
config.active_job.queue_adapter = :sneakers

*Install RabbitMQ, and start it:
(preferible in a different terminal tab)

$ rabbitmq-server

*Install the gem sneakers and run its deamon in (preferible other terminal tab):

$ sneakers work ActiveJob::QueueAdapters::SneakersAdapter::JobWrapper
  --require app/jobs/policies_checks_job.rb


text:
Q: Trouble trying to clean a character vector in R data frame (UTF-8 encoding issue) I'm having some issues cleaning up a dataset after I manually extracted the data online - I'm guessing these are encoding issues. I have an issue trying to remove the "U+00A0" in the "Athlete" column cels along with the operator brackets. I looked up the corresponding UTF-8 code and it's for "No-Break-Space". I'm also not sure how to replace the other UTF-8 characters to make the names legible - for e.g. getting U+008A to display as Š.
Subset of data
head2007decathlon <- structure(list(Rank = 1:6, Athlete = c("<U+00A0>Roman <U+008A>ebrle<U+00A0>(CZE)", "<U+00A0>Maurice Smith<U+00A0>(JAM)", "<U+00A0>Dmitriy Karpov<U+00A0>(KAZ)", "<U+00A0>Aleksey Drozdov<U+00A0>(RUS)", "<U+00A0>Andr<e9> Niklaus<U+00A0>(GER)", "<U+00A0>Aleksey Sysoyev<U+00A0>(RUS)"), Total = c(8676L, 8644L, 8586L, 8475L, 8371L, 8357L), `100m` = c(11.04, 10.62, 10.7, 10.97, 11.12, 10.8), LJ = c(7.56, 7.5, 7.19, 7.25, 7.42, 7.01), SP = c(15.92, 17.32, 16.08, 16.49, 14.12, 16.16), HJ = c(2.12, 1.97, 2.06, 2.12, 2.06, 2.03), `400m` = c(48.8, 47.48, 47.44, 50, 49.4, 48.42), `110mh` = c(14.33, 13.91, 14.03, 14.76, 14.51, 14.59), DT = c(48.75, 52.36, 48.95, 48.62, 44.48, 49.76), PV = c(4.8, 4.8, 5, 5, 5.3, 4.9), JT = c(71.18, 53.61, 59.84, 65.51, 63.28, 57.75), `1500m` = c(275.32, 273.52, 279.68, 276.93, 272.5, 276.16), Year = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "2007", class = "factor"), Nationality = c(NA, NA, NA, NA, NA, NA)), .Names = c("Rank", "Athlete", "Total", "100m", "LJ", "SP", "HJ", "400m", "110mh", "DT", "PV", "JT", "1500m", "Year", "Nationality"), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

This is what I've tried so far to no success:
1) head2007decathlon$Athlete <- gsub(pattern="\U00A0",replacement="",x=head2007decathlon$Athlete)
2) head2007decathlon$Athlete <- gsub(pattern="<U00A0>",replacement="",x=head2007decathlon$Athlete)
3) head2007decathlon$Athlete <- iconv(head2007decathlon$Athlete, from="UTF-8", to="LATIN1")
4) Encoding(head2007decathlon$Athlete) <- "UTF-8"
5) head2007decathlon$Athlete<- enc2utf8(head2007decathlon$Athlete)

A: The following would remove the no break space.
head2007decathlon$Athlete <- gsub(pattern="<U\\+00A0>",replacement="",x=head2007decathlon$Athlete)

Not sure how to convert the other characters. One problem could be that the codes are not exactly in a format that R sees as UTF-8.
One example:
iconv('\u008A', from="UTF-8", to="LATIN1")

this seems to have an effect, contrary to trying to convert U+008A. Although
the output is:
[1] "\x8a"

not the character you want. Hope this helps somehow.


text:
Q: Power off the computer every night and hardware life I want to know if an office computer shuold be switched off every night or not to improve its hardware life.
I know that some components like magnetic disks are degraded by reboots, but I cannot evaluate if it is worse a daily switch off or a full day unuseful activity.
Thanks

A: I remember reading about this in the Google Failure Trends in a Large Disk Drive Population whitepaper. Search for 'Power Cycles'.
Though it looks like this question was asked before, in various forms:

*

***How** harmful is a hard disk spin cycle?

*http://www.hgst.com/tech/techlib.nsf/techdocs/9076679E3EE4003E86256FAB005825FB/$file/LoadUnload_white_paper_FINAL.pdf

I would assume the same applies for all moving parts... you're probably better off looking at power savings though.

A: As pointed out in the comments, the question has been asked before in relation to servers, where there is a feeling that powering off a computer at night shortens longevity. But the answers in that question are unsupported and use car analogies, taking about engine wear. In fact, one of the comments on the top answer points out that Google's big investigation into hard drive life gave inconclusive evidence that power cycles had more effect than luck-of-the-draw.
So let's instead turn the question around slightly by asking "what can we do to increase a computer's physical lifespan?", which will ignore the software side of things (malware, degraded performance etc)
Cleaning
The argument goes that if your computer is caked in dust it will significantly reduce the efficiency of heat conduction. A search reveals plenty of places advising this (eg these guys, to pick a random example); but no studies or reports that I saw in the first few pages of results. I guess this is one of these things that are treated as self-evident: overheating is extremely detrimental to lifespan; dirt and dust leads eventually to overheating.
Power Surges
Power surges are not kind to components. Searching reveals common advice is to buy a surge protector; or for even better protection, a UPS (uninterruptible power supply).
If you have no or inadequate protection in place when a power surge occurs, it'll affect the power supply first, and if you're lucky, nothing else. If you're not, the surge can affect anything- motherboard, CPU, graphics card, hard drive, etc. There's an Anandtech forums discussion where someone explains in better detail:

The real severe internal damage comes when the input power causes the power supply to push too much electricity into internal parts [...] Some really delicate components -- mainly processors and memory -- are actually damaged by this, and get bricked. Simple parts can be killed too: You take a resistor and dump too much juice into it, it heats up and burns. You dump too much power into an electrolytic capacitor, and it can burst and spew electrolyte fluid all over the place.

There is a common argument too that poor quality power supplies can decrease the longevity of other components. Certainly a faulty power supply can cause problems - plenty of anecdotes, like pins melting to a motherboard - but even those advocating good quality supplies (another example I picked) tend to rely on citing experience, or are power supply manufacturers themselves.
I've seen the argument that switching on a computer induces a degree of power surge, but I can't find much to back this up.
So is turning an office computer off at night or not likely to be harmful to hardware life?
In the time it's taken me to write this answer, I cannot find good evidence to suggest that turning a computer off once a day would significantly shorten its life. However, the evidence is not good enough to make a recommendation one way or another on the basis of longevity alone. You may want to consider other factors - such as energy savings - instead.

A: Is power cycling destructive?  Yes.  And then we include specification numbers.  For example, the disk drive specifications state it can be power cycled 7 times every day for .... 39 years.  So yes, power cycling is destructive. And the numbers say nobody cares.
Same applies to the fears of overheating.  Once we include numbers, well, it will fail in 180 years instead of 230.  Overheating at hundreds of degrees C is destructive.  Overheating due to dust (tens of degrees) is fear mostly attributed to subjective reasoning.
BTW, what is the most common reason for dust problems?  Moving too much air through a computer.  A problem rarely seen in brand name machines and often seen in computers assembled by computer techs.  The latter often do not learn what are best air flow numbers (ie cubic feet per minute); install too many fans.
Power it off when done.  Even better is to hibernate it rather than sleep or shutdown.

A: cleaning
It is claimed that the efficiency of heat conduction will decrease significantly if the computer is cured with dust. A search yields numerous places that advise on this (for example choose a random example from ITpedia ). There are no studies or reports from the first few pages of results. I think this is one of these things that is taken for granted: overheating is very detrimental to longevity. Dust and dirt eventually lead to overheating.


text:
Q: Updating a non-bound field in a form with a record source I have a form with a record source of SELECT [AccountRunInProgress] from [AccountRunSummary]. The form contains a text box with a date which is used to apply a filter on the above record source, based on the month and year (defined as two separate fields in the AccountRunSummary table).
The other field in the form is a check box bound to the AccountRunInProgress field. When ticked, the OnClick event for this box updates a date field called RunProgressStartDate in the AccountRunSummary table with the current date and time.
I then get a Write Conflict error when closing the form - almost certainly because I am trying to update the table via the OnClick event while using the table as the record source at the same time, despite not binding the date fields. The date is updated in the table but not the boolean.
What is the best practice for working around this? I thought about adding RunProgressStartDate as a hidden bound text box in the form and adding it to the record source, but I'm fairly sure that will cause more problems rather than less.

A: You are on the right track.
You can't edit a record through the bound form and with an Update query (in VBA) at the same time.
IMO the best solution is indeed to add RunProgressStartDate to the record source and as hidden control to the form.
Then (important!) set the value of this control in the OnClick event, don't write the table with an Update query:
Me!RunProgressStartDate.Value = Date()

and both fields (checkbox and date) will be saved when the record is saved.


text:
Q: How does JDBC manage data integrity I've been asked this question by someone and exploring the answers.
How does the JDBC driver ensure data integrity while transferring the data between Java and database. Anybody has link or any documentation saying how JDBC driver achieves it?

A: The driver doesn't "manage" or "ensure" data integrity at all.
That's completely in the responsibility of the database server.
It if was the driver, then all the constraints could easily be bypassed by using a different technology to connect to the database.
Plus: the driver is a client side technology and it's impossible to ensure data integrity from only the client side.


text:
Q: Memory Leak Error when deploying clojure ring application on tomcat 8 I'm trying to deploy a ring app war on tomcat 8. Created war with lein ring uberwar.
I suspect it is because of jdbc connection thread but not sure.
I'm using
[org.postgresql/postgresql "9.4-1206-jdbc42"] and [korma "0.4.1"]
project.clj
  :ring {:handler hello-world.handler/app
         :init    hello-world.handler/init
         :destroy hello-world.handler/destroy}

handler.clj
(korma.db/defdb db (korma.db/postgres {:db "hello_world"
                                       :user "user"
                                       :password "password"
                                       :host "localhost"}))

(defn init []
  (println "Init..."))

(defn destroy []
  (-> (korma.db/connection-pool db) :datasource .close))

Here's the error trace from tomcat logs -
org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /var/lib/tomcat7/webapps/hello-world-0.1.0-SNAPSHOT-standalone.war
org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/hello-world-0.1.0-SNAPSHOT-standalone] startup failed due to previous errors
org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/hello-world-0.1.0-SNAPSHOT-standalone] appears to have started a thread named [clojure-agent-send-off-pool-0] but has failed to stop it. This is very likely to create a memory leak.
org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/hello-world-0.1.0-SNAPSHOT-standalone] appears to have started a thread named [clojure-agent-send-off-pool-1] but has failed to stop it. This is very likely to create a memory leak.
org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/hello-world-0.1.0-SNAPSHOT-standalone] created a ThreadLocal with key of type [clojure.lang.Var$1] (value [clojure.lang.Var$1@3a2ddd4f]) and a value of type [clojure.lang.Var.Frame] (value [clojure.lang.Var$Frame@191c8b60]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [/hello-world-0.1.0-SNAPSHOT-standalone] created a ThreadLocal with key of type [clojure.lang.Var$1] (value [clojure.lang.Var$1@3a2ddd4f]) and a value of type [clojure.lang.Var.Frame] (value [clojure.lang.Var$Frame@21025881]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.


text:
Q: Too many arguments to conversion in gobot I was trying to test a LDR using gobot framework. I used AnalogSensorDriver device driver and my code is
    package main

import (
    "time"

    "gobot.io/x/gobot"
    "gobot.io/x/gobot/drivers/aio"
    "gobot.io/x/gobot/platforms/raspi"
)

func main() {
    r := raspi.NewAdaptor()
    ldr := aio.AnalogSensorDriver(r, "7")

    work := func() {
        gobot.Every(1*time.Second, func() {
            ldr.Read()
        })
    }

    robot := gobot.NewRobot("getBot",
        []gobot.Connection{r},
        []gobot.Device{ldr},
        work,
    )

    robot.Start()
}

When I execute this, I am getting this error.

./ldrtest.go:13: too many arguments to conversion to aio.AnalogSensorDriver: aio.AnalogSensorDriver(w, "7")
  ./ldrtest.go:22: undefined: w

I am totally new for golang and gobot. So any kind of help to solve this problem would be greatly appreciated.
Thanks in advance.

A: From a quick glance at gobot's source it seems to me that you cannot use aio.NewAnalogSensorDriver with the raspi.Adaptor. The aio.NewAnalogSensorDriver expects it's first argument to be an interface of type AnalogReader while the raspi.NewAdaptor returns a raspi.Adaptor that, seemingly, does not implement the AnalogRead method required for it to implement the AnalogReader interface.
That's why you get that error ./ldrtest.go:13: cannot use r (type *raspi.Adaptor) as type aio.AnalogReader in argument to aio.NewAnalogSensorDriver: *raspi.Adaptor does not implement aio.AnalogReader (missing AnalogRead method).
Update:
Making your code work depends on what you want to do. If you want to use raspi.Adaptor you cannot use aio.NewAnalogSensorDriver because the raspi.Adaptor does not have analog capabilities. If you want to use the aio.NewAnalogSensorDriver you'll need to use, as its first argument, a value whose type implements the AnalogRead method, like for example the beaglebone.Adaptor does.
package main

import (
    "time"

    "gobot.io/x/gobot"
    "gobot.io/x/gobot/drivers/aio"
    "gobot.io/x/gobot/platforms/beaglebone"
)

func main() {
    r := beaglebone.NewAdaptor()
    ldr := aio.NewAnalogSensorDriver(r, "7")

    // ...
}

This example should get you past that initial error, if the code below causes other issues you should consider consulting the documentation for both Go and gobot.

A: The raspberry pi does not have a way to connect analog devices directly, so, whatever the framework, you cannot simply attach the photoresistor (LDR) directly to the board. There are 2 ways to use photoresistors in that case:

*

*You need an analog-digital converter (ADC), such as the MCP3008, ADS1015, ADS1115.

As of April, 30th, 2017, Gobot.io supports the ADS1015/ADS1115 in the Dev branch. If you connect your device to an ADS1015 on the channel 0, then the converter to the I2C interface of the raspberry pi, the code would look like that:
package main

import (
    "fmt"
    "time"

    "gobot.io/x/gobot"
    "gobot.io/x/gobot/drivers/i2c"
    "gobot.io/x/gobot/platforms/raspi"
)

func main() {
    a := raspi.NewAdaptor()
    ads1015 := i2c.NewADS1015Driver(a)
    // Adjust the gain to be able to read values of at least 5V
    ads1015.DefaultGain, _ = ads1015.BestGainForVoltage(5.0)

    work := func() {
        gobot.Every(100*time.Millisecond, func() {
            v, _ := ads1015.ReadWithDefaults(0)
            fmt.Println("A0", v)
        })
    }

    robot := gobot.NewRobot("ads1015bot",
        []gobot.Connection{a},
        []gobot.Device{ads1015},
        work,
    )

    robot.Start()
}

*There is a solution to use such sensors without ADC converters, described here:

Because photocells are basically resistors, its possible to use them even if you don't have any analog pins on your microcontroller (or if say you want to connect more than you have analog input pins). The way we do this is by taking advantage of a basic electronic property of resistors and capacitors. It turns out that if you take a capacitor that is initially storing no voltage, and then connect it to power (like 5V) through a resistor, it will charge up to the power voltage slowly. The bigger the resistor, the slower it is.

You can find many examples on the internet on how to connect the LDR in such case. I'm not sure there is a working example with Gobot.io right now.


text:
Q: execvpe implicit declaration error I'm testing the execvpe() in c, I tried the below code, which cause the error as "implicit declaration of function 'execvpe' is invalid in C99 [-Wimplicit-function-declaration]".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _GNU_SOURCE
#include <unistd.h>

int main(int argc, char const *argv[])
{
    //execl("/bin/echo", "echo", "Hello, world", NULL);
    char *path = getenv("PATH");
    char  pathenv[strlen(path) + sizeof("PATH=")];
    sprintf(pathenv, "PATH=%s", path);
    char *envp[] = {pathenv, NULL};
    char *tests[] = {"ls", "-lR", NULL};
    execvpe(tests[0], tests, envp);
    fprintf(stderr, "failed to execute \"%s\"\n", tests[0]);
    return 0;
}

Then I test this code as below to test the existing status (which I copied from Compiler warnings for execvpe function, this time no error. Is there anyone can help me to figure out what's wrong in my above code? Thanks!
#include <unistd.h>
extern int execvpe(const char *file, char *const argv[], char *const envp[]);

A: Move the #define _GNU_SOURCE directive to before any of the #include directives, e.g.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

In Glibc, all of these headers pull in features.h which sets various macros based on the setting of _XOPEN_SOURCE, _POSIX_SOURCE, _GNU_SOURCE, etc. At the time of the first include, it is not set. When you get down to unistd.h, features.h has already been included and won't be applied again.


text:
Q: Magento loop inside another loop sub categories with products of that sub category inside I am trying to build a block in Magento (1.8 comunity edition)
In this block I want to seperate the sub categories
lets say that the parent is Power tools
and it has 3 sub categories
saws
routers
drills
so the outcome would be something like this...
Power tools
  saws
  routers
  drills
I have the parent category set to display a block, and my existing code will show the sub categories just fine. I get the sub categories output along with their wrapping divs along with the links pointing to the corret subcategory page, but the product lists inside... no joy!
So far I have this for code...
<?php

$category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$categories = $category->getCollection()
    ->addAttributeToSelect(array('name', 'thumbnail'))
    ->addAttributeToFilter('is_active', 1)
    ->addIdFilter($category->getChildren())
?>

<?php foreach ($categories as $category): ?>

        <a href="<?php echo $category->getUrl() ?>"><img src="<?php echo Mage::getBaseUrl('media') . 'catalog' . DS . 'category' . DS . $category->getThumbnail() ?>" alt="<?php echo $this->htmlEscape($category->getName()) ?>" />

test this

        <?php
        $parent_cat = Mage::getModel('catalog/layer')->getCurrentCategory();
        $_productCollection = $this->getLoadedProductCollection();
        $_helper = $this->helper('catalog/output');
        ?>

        <?php echo $parent_cat->getid() ; ?>//this shows the correct id

        <?php foreach ($_productCollection as $_product): ?>// start individual products for the sub category
        <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>

<?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></

        <?php endforeach; ?>// end product loop for the individual products

<?php endforeach; ?>

So I thought the the $this-> might be referencing the previous call for the outside loop (Not sure though if that makes sense) so I tried something like this...
        <?php
        $parent_cat = Mage::getModel('catalog/layer')->getCurrentCategory();
        $_productCollection = $parent_cat->getLoadedProductCollection();
        $_helper = $this->helper('catalog/output');
        ?>

no errors but still no joy.
I am new to loops in Magento so I am totally flailing here, would like it if someone could set me straight on what I am doing wrong.
Thank you!

A: So digging around I found some stuff that worked for me, still not sure if this is the best way to do it, but for a novice it seems to work well.
much thans to Adam Moss for his answer on another post on stack
Magento Product Listing by Category ID
The only  thing that I did was use the $category-getId(); to pull in the proper Cat id so that the sub category pulled the proper product collection!!! AWESOME!
<?php

        $categoryid = $category->getId();

        $category = new Mage_Catalog_Model_Category();
        $category->load($categoryid);
        $collection = $category->getProductCollection();
        $collection->addAttributeToSelect('*');

        foreach ($collection as $_product) { ?>

<?php
     // do stuff here, like...
      echo $_product->getShortDescription();
?>

<?php } ?>


text:
Q: Prime degree ⇒ linearly disjoint?
If F is a field of characteristic 0 with subfields K, L such that F is the compositum of K and L and [ L : L ∩ K ] is prime, must be K and L be linearly disjoint over L ∩ K?
In other words, must [ KL : K ] = [ L : L ∩ K ] if [ L : L ∩ K ] is prime?

Here K, L are fields of characteristic 0 (definitely not p), but I don't assume [ K : K ∩ L ] is finite (or normal or anything).  I think it doesn't have to be true if that index [ L : L ∩ K ] is not prime and the field extension K ∩ L ≤ K is not normal.  I am hoping it is true when the index [ L : L ∩ K ] is prime.
The motivation is to show either every non-identity p-subgroup of PGL(2, K) is reducible or every non-identity p-subgroup of PGL(2, K) is irreducible.

A: The answer is no. Let $L = \mathbb{Q}(\sqrt[3]{5})$ and $K = \mathbb{Q}(\zeta_3\sqrt[3]{5}).$ Then $[LK:L] = 2 \neq 3 = [L: K\cap L]$ and $L\otimes_{\mathbb{Q}} K$ is not a field.
Edit in responce to the comment: For any fields $L$ and $K,$ if $L/L\cap K$ is finite, Galois, then so too is $KL/K$ and $[LK : K]$ divides $[L:L\cap K].$
Consequently, if $[L:L\cap K]$ is prime then $L\neq K$ and $[LK : K] = [L:L\cap K].$
Linear disjointness follows, assume momentarily that $K/L\cap K$ is finite and set $E = L\cap K.$ Then $$\mathrm{dim}_{E}(L\otimes_{\mathbb{E}} K) = [L:E][K:E] = [LK : K][K:E] = dim_{E}(LK).$$ Hence, the natural ring epimorphism from $L\otimes_{\mathbb{E}} K$ to $LK$ is an isomorphism of $E$-vector spaces and hence a ring isomorphism. It follows $L\otimes_{\mathbb{E}} K$ is a field.
For the case where $K/E$ is infinite,
Let $\mathcal{K} :=\{K'\}$ be the collection of fields which are finite extensions of $E$ and contained in $K.$ Then
$L\otimes_{\mathbb{E}} K \cong L\otimes_{\mathbb{E}} (\displaystyle\lim_{\rightarrow}K') \cong \displaystyle\lim_{\rightarrow}(L\otimes_{\mathbb{E}} K') \cong \displaystyle\lim_{\rightarrow} LK' \cong LK.$
where colimits are taken over $\mathcal{K}.$ It follows $L\otimes_{\mathbb{E}} K$ is a field and $K$ and $L$ are linearly disjoint.


text:
Q: ERROR TypeError: Cannot read properties of undefined (reading 'initialize') I'm getting above error when i called the registerListener() function in my component ts file.
listerners.service.ts file
 eventRegistry: object = {};
  constructor() { }
  createListener(module: string, event: string, initialValue: any) {
    if (!this.eventRegistry[module]) {
      this.eventRegistry[module] = {};
    }
    if (!this.eventRegistry[module][event]) {
      this.eventRegistry[module][event] = { "initialValue": initialValue, "listeners": [] };
    } else {
      alert("event " + module + "::" + event + " is already created");
    }
  }
  registerListener(module: string, event: string, callback: CallableFunction) {
    debugger
    if (!this.eventRegistry[module][event]) {

      alert("event " + module + "::" + event + " is not created so far.");
    }
    this.eventRegistry[module][event]["listeners"].push(callback);
  }
  callListener(module: string, event: string, obj: any) {
    if (!this.eventRegistry[module]) {
      alert("event " + module + "::" + event + " is not created, module does not exist");
    }
    if (this.eventRegistry[module][event]) {

      let initialValue: any = this.eventRegistry[module][event]["initialValue"];

      for (let i = 0; i < this.eventRegistry[module][event]["listeners"].length; i++) {
        initialValue = this.eventRegistry[module][event]["listeners"][i](initialValue, obj);
      }
      return initialValue;
    } else {
      alert("event " + module + "::" + event + " is not created");
    }
  }

I'm calling above function in flight component ts file
public router:Router, private listenerService: ListenersService) {
      listenerService.registerListener("shell","initialize",function(value,obj) {
        debugger
        console.log(value +""+ obj);
      });

      listenerService.callListener("shell","initialize",{});
     }
}

enter image description here

A: In your registerListener function you do the following:
if (!this.eventRegistry[module][event]) {
  alert('event ' + module + '::' + event + ' is not created so far.');
}

When you call this function like this:
listenerService.registerListener('shell', 'initialize', function (value, obj) {...})

This means that when you call registerListener with parameters shell and initialize you essentially look inside this.eventRegistry.shell to check if initialize exists.
The error you're getting tells you your script cannot read initialize from undefined. Which basically means that this.eventRegistry.shell is undefined, thus it does not exist.
What you probably want to do is add a ? operator in your if statement to check if each element exists. Like this:
if (!this.eventRegistry?.[module]?.[event]) {

Adding this will also check if this.eventRegistry is true-ish, (meaning it contains a value other than undefined, null, or 0. It will do the same for [module].
I hope this answers your question where your undefined comes from.


text:
Q: Facebook Open Graph Protocol - pages created for admin to manage I have a website with like 50-60 dynamically generated pages, where I implemented the like button along with open graph protocol (ogp).
I want to manage this pages like a regular facebook page and post to my fans, for that I have specificed myself as page admin in the meta tags and liked my posts but I can't find this page in my manage pages section.
I tested my website by adding/removing different meta tags to make it working and tested it on facebook linter tool. Somehow I got two pages in the manage pages section but the remaining are not working.
You can view my website here:
http://freshlylike.com/view.php?id=404
Please help.
Thanks,
happyhardik

A: That's because in order to see those pages in you Manage Pages section, the admin listed in the open graph tag has to actually click the link - according to Facebook

Each listed user must click Like on
  the URL to be approved as an admin.
  This is to prevent users being made
  admins without their consent.

I encountered the same problem too, so might have to work around that.


text:
Q: Semi-transparent splash screen bevel A Zune splash screen:

has a square, semi-transparent border around splash screen image.
How can one get such semi-transparent border on .net app's splash screen?

A: Here are the steps for a partly transparent WPF splashscreen:
1) Create a PNG with the desired semi-transparent parts
2) In your SplashScreen.xaml (or whatever the name of it), do this:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" WindowStartupLocation="CenterScreen" WindowStyle="None" AllowsTransparency="True">
    <Grid>
        <Image Source="MyPngImagePath" />
    </Grid>
</Window>

If you want to use a regular image with no transparency and put a semi-transparent border around it, simply put the Image in the XAML above into a <Border /> with BorderBrush set to a semi-transparent color (i.e: a color like #AABBBBBB where AA defines transparency)

A: Look at Transparency Properties on .NET forms
On your image border put this square in a specific color, then use the Transparency property to  apply a MaskColor
Once i found a code exemple taht takes a PNG image and apply the transparency component on the form...
This code project tutorial can help:
Transparency Tutorial with C# - Part 1
Transparency Tutorial with C# - Part 2
Transparency Tutorial with C# - Part 3


text:
Q: Creating Forms In a ForEach - PHP I am working with an array in PHP. For each thing in the array, I want to create a form and button attached to it. In addition to that, an action when the button is pushed. I fear it may have something to do with timing or such.
Here is my code:
foreach($projects as $proj){
echo "<form action='post'><input type='button' name='forminput' Value ='Yup'></form>";
$name = $_POST['forminput'];
}

if($name){
echo "ye";
}

Thanks!

A: Something like this?
<?php

$arrayName = array('test1' => '1', 'test2' => '2', 'test3' => '3', 'test4' => '4');

foreach ($arrayName as $key => $value) {
  $$key = $value;
  echo '
  <form action="" method="post" enctype="multipart/form-data">
    <input type="submit" name="forminput" Value ="'.$$key.'">
  </form>
  ';
}

foreach ($_POST as $key => $value) {
$key = strip_tags($key); // to prevent scripts being injected into the page
$value = strip_tags($value);

  echo $key . ' ' . $value;
}

 ?>


text:
Q: Input Transformer: handle special characters in AWS Event Bridge I am having a hard time understanding why my input transformation is not working in Event Bridge.
The following is the default input to a step function, which will intentionally cause my state machine to fail:
{
    "Comment": "Insert your JSON here"
}

I have configured a rule in EventBridge to notify the failure using the following Input Transformer:
{
    "executionArn": "$.detail.executionArn",
    "inputs": "$.detail.input",
    "startDate": "$.detail.startDate",
    "status": "$.detail.status"
}

It uses the above input in this template:
"Flow Execution Failure! More information: <executionArn> Status: <status> Started On: <startDate> Flow Input: <inputs>"

The problem is no matter however I try to include <inputs>, it fails. I believe it is because the event will contain the following newline characters \n:
{
    ...
    "detail": {
        "status": "FAILED",
        "input": "{\n    \"Comment\": \"Insert your JSON here\"\n}"
    }
}

I have tried escaping <input> in the following manners, none of which worked so far:

*

*Flow Input: \"<inputs>\"

*Flow Input: `<inputs>`

*Flow Input: \"\`<inputs>\`\"

A: Since $.detail.input is already an escaped json string, I'm not sure it's going to be possible to nest that value within in another string.
Unless the InputTemplate must be a single string, it may be easier to change the template to something like:
{
    "executionArn": <executionArn>,
    "inputs": <inputs>,
    "startDate": <startDate>,
    "status": <status>
}


text:
Q: how to record the score in a database I'm designing a database to record and analyse data about a sports game
one of my tables will be 'matches' which records details about a match (the team ids, location, date etc) and includes the final score. I also have another table which records a specific score in a match (i.e. who scored it and the number of points) called 'scores'. My question is whether I should record the score in 'matches' or, if I want to know the score, just add up all the points in 'scores'? Is there a way such that if a 'scores' row is updated then it will recalculate the score in 'matches'?
Thanks

A: There is a way and it is called a "trigger".  You can set up a trigger on the scores table so whenever a new record is inserted, the appropriate value in the scores table is updated.
The place to start is with the documentation on triggers, which is here.
If your data is not large, then you can create a view that has the same information.  Something like:
create view v_matchscores as
    select m.*, sum(case s.team = m.teama then score else 0 end) as ascore,
           sum(case when s.team = m.teamb then score else 0 end) as bscore
    from matches m join
         scores s
         on m.matchid = s.matchid
    group by m.matchid


text:
Q: API call getting timed out for large amout of data I am having trouble in fetching XML data from through API in large amount. Has anyone a better solution in fetching XML data in ASP.net application?
Maybe the issue is might be garbage collection memory not sure but earlier it was not working for any user so I added manual memory release code and closing web response connection after each call.
Any suggestion to improve the fetching of large amount of data are welcome?
   public static XmlDocument LoadXmlFromUrl(string url, bool keepAlive = true, bool throwException = false, int timeout = 15000)
    {
        Log(url, "*** start ***" + url);

        ServicePointManager.DefaultConnectionLimit = 2000;
        string xmlAsText = null;
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.KeepAlive = keepAlive;
        req.Timeout = timeout; // 30,000ms = 30 sec default
        try
        {
            bool retried = false;
        retry:
            try
            {
                using (HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse())
                {
                    using (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        xmlAsText = responseStream.ReadToEnd();
                        responseStream.Close();
                    }
                    webResponse.Close();

                    Log(url, "stream reader (responseStream.ReadToEnd) completed to string.");
                }
            }
            catch (WebException webEx)
            {
                if (!retried)
                {
                    if (webEx.Status == WebExceptionStatus.Timeout || webEx.Status == WebExceptionStatus.KeepAliveFailure)
                    {
                        Log(url, "About to retry for url (6 sec wait): " + url);
                        System.Threading.Thread.Sleep(6000);
                        retried = true;
                        goto retry;
                    }
                }
                else
                {
                    throw webEx;
                }
            }
        }
        catch (Exception ex)
        {
            Log(url, "exception while loading responseStream.ReadToEnd. " + ex.ToString());
        }
        XmlDocument xdoc = null;
        if (!string.IsNullOrEmpty(xmlAsText))
        {
            try
            {
                xdoc = new XmlDocument();
                xdoc.LoadXml(xmlAsText);
                Log(url, "string added to xml (xdoc.LoadXml) completed.");
            }
            catch (Exception ex)
            {
                Log(url, "exception while loading xdoc.LoadXml. " + ex.ToString());
            }
        }
        return xdoc;
    }

Exception 1:
5/01/2017 12:27:01 p.m. exception while loading responseStream.ReadToEnd.     System.Net.WebException: The operation has timed out**

Exception 2:
6/01/2017 8:35:59 a.m. exception while loading responseStream.ReadToEnd. System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

A: Exception #1 may occur if

*

*request is huge. In this case you can try to increase value of HttpWebRequest.ReadWriteTimeout to something relatively big, for example, 3600000 (1 hour).

*value of header ContentLength does not match real response size and server does not force connection to close.
To track down the problem I would suggest you to set up tracing. You can follow https://msdn.microsoft.com/en-us/library/ty48b824(v=vs.110).aspx or find similar here on StackOverflow.
Exception #2 definitely occurs just because the response does not fit to memory allocated for application or its size exceeded 2Gb. (It must be really big response). The possible solution is to buffer stream to a file or process it on-fly (if possible).
For example:
...
using (HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse())
{
    String tempFile = Path.GetTempFileName();
    using (var stream = webResponse.GetResponseStream())
    {
        if (stream != null)
        {
            using (FileStream file = File.Create(tempFile))
            {
                stream.CopyTo(file);
            }
        }
    }

    Log(url, "stream reader (responseStream.ReadToEnd) completed to string.");
}


text:
Q: Strange problem with Java FlatLAF - java.lang.Error: no ComponentUI class for JLabel I've created a maven-based Java Swing project in Netbeans 12.1. I added some dependencies in pom.xml:
com.formdev.flatlaf 0.43
com.formdev.flatlaf-swingx 0.43
com.formdev.flatlaf-extras 0.43

I initialize the use of FlatLAF in my main form like this:
public static void main(String args[]) {
    FlatLightLaf.install();
}

When I start my program in Netbeans, it all works perfectly. Netbeans uses this command to run the program:
cd /Users/rene/htdocs/my-program; JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-
12.0.1.jdk/Contents/Home "/Applications/NetBeans/Apache NetBeans
12.1.app/Contents/Resources/NetBeans/netbeans/java/maven/bin/mvn" "-Dexec.args=-classpath
%classpath de.renepoepperl.my-program.Login" -
Dexec.executable=/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java
org.codehaus.mojo:exec-maven-plugin:1.5.0:exec

But when I build the program "with dependencies" and try to run java -jar my-program.jar I get multiple errors saying: java.lang.Error: no ComponentUI class for
I guess that, FlatLAF misses some configuration. But I don't know why.
What can I do to get FlatLAF working?

A: This happens in case that the FlatLaf classes were renamed by obfuscation or by other class minimizer tools (e.g. Maven Shade Plugin).
See https://github.com/JFormDesigner/FlatLaf/issues/104
Check whether the jar contains all files from the flatlaf.jar.


text:
Q: Node.js debugger not working I have express.js with ejs templating.
I can see that for first request, debugger stops at break point.
But after ejs serves page on browser, any further requests never stops at break point.
I tried lot of things in frustation -> webstorm, eclipse, node-inspector,etc
Is there some config for ejs or experss that I am missing?
Even console.log is not printing anything. I know flow works for sure.

A: Actually it was my bad.
I was trying to debug js in public folder which is client side js.
So i have debug using chrome developer tools instead of server side debugging.


text:
Q: Elasticsearch Aggregation for nested generic properties in Spring Boot I have the following Spring Elasticsearch document class:
public class Entity
{
    @Id
    @Field(type = FieldType.Keyword)
    private String id;

    @Field
    private Map<String, Metric> values;
}

and class Metric consists of the following:
public class Metric<T>
{
    private String description;
    private T value;
}

The generic type T could be either an Integer or a Map<String,Integer>.
as an example of the document's data:
{
  "values":
  {
    "fans":{
      "description":"Fans",
      "value":100
    },
    "unlikes":{
      "description":"Unlikes",
      "value":823
    },
    "reaction_type":{
      "description":"Reaction by type",
      "value":{
        "like":40,
        "sad":20,
        "wow":15
      }
    }
  }
}

My objective to do a sum aggregation on the value property inside Metric class.
If T is an Integer the aggregation will be sum of Integer values. and if T is of type Map<String,Integer>, the aggregation will be sum sum of values grouped by Map key.
is there any approach to do so in Spring boot?


text:
Q: adding metadata in Image file created from base64 string javascript I have an existing code which converts base64 string to corresponding image file. Now, I want to add some metadata like last modified date, photographer, copyright, credits etc. Tried below which did not work. Is there a way I could add the metadata?
here base64Source is the dataUri from which I am getting base 64 content.
function (base64Source, name) {
        var base64Content = base64Source.substr(base64Source.indexOf(',') + 1);

        var byteString = window.atob(base64Content);
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        var file = new Blob([ia], {type: 'image/jpeg'});
        return new File([the_file], name);
    };

I modified this piece of code as
function (base64Source, name) {
        var base64Content = base64Source.substr(base64Source.indexOf(',') + 1);

        var byteString = window.atob(base64Content);
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        var file = new Blob([ia], {type: 'image/jpeg'});
        return new File([the_file], name,{
            lastModified: new Date().getTime(),
            tooltip : 'test tooltip',
            caption : 'test caption',
            copyright : 'Test',
            credits : 'Test'
        });
    };

A: These metadata should be part of the file's data itself.
The javascript File object will not change the file's data (apart from the EOL endings option of the Blob constructor that File does inherit from).
So you'd have to actually modify your file's data (i.e the bytes contained in ia's ArrayBuffer).
The way you will do it depends on the type of image you are dealing with. Different image formats have different rules as to what metadata they can accept and how it should be stored in the file.
For instance, for JPEG files, TIFF and webp formats it is common to have it in EXIF data, stored in an Application Segment, identifiable by the 0xFFE1 marker for JPEG. webp marks it with a chunkHeader('EXIF'). They also all support XMP.
PNG also allows some text-info metadata.
Other file formats may support other metadata formats, and writing you an universal encoder would be ... a very hard work.
But some libraries do exist for the most common formats (JPEG's EXIF ones are easily found using your favorite web search tool).


text:
Q: Bootstrap 4 layout row first vs column first? Most grid layout examples in Bootstrap 4 put columns inside rows.  Is it wrong to put rows inside columns ? Like this,

A: Yes, it's totally valid to use nested columns/row. Just be sure to always use a column inside a row. Else you'll get unexpected layouts.

A: It's a perfectly valid approach. Consider the example below:

A: The [x]-col-[y] classes are all percentage based for widths. Go nuts with the nesting! Just make sure you wrap them in a row div else you'll get some funky margins


text:
Q: Some Images is not shown when upload by mobile in django application but work always perfectly when upload throw laptop? I am stuck in the very serious problem without any solution. This is my models.py file

class Report_item(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
    item_type = models.CharField(default="", max_length=100,
                                 help_text='*Enter the item name you found e.g. Marksheet,key,wallet')
    location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item')
    city = models.CharField(max_length=60, help_text='*Enter the city name')
    date = models.DateTimeField(default=timezone.now)
    Description = models.TextField(blank=True,null=True,help_text='*Enter full description about item')
    publish = models.BooleanField(default=False)

    image = models.FileField(default="add Item image",
                             help_text='*Please uplocad a item image to identify by the owner')

    def __str__(self):
        return self.title + "      " + str(self.publish)

    def get_absolute_url(self):
        return reverse('feed:detail', kwargs={'pk': self.pk})

    class Meta:
        ordering = ["-date"]

When I upload an image from my laptop then it is uploaded successfully and also shown in the feed. But when I uploaded using a mobile phone then it always uploads but does not show in feed or profile page. Although the image with the same name is available in admin panel but when I try to open it then it shows the 404 not found an error.


text:
Q: AttributeError: Can't get attribute 'journalerReader' on I tried to implement Lmax in python .I tried to handle data in 4 processes
import disruptor
import multiprocessing
import random

if __name__ == '__main__':

    cb = disruptor.CircularBuffer(5)

    def receiveWriter():
        while(True):
            n = random.randint(5,20)
            cb.receive(n)

    def ReplicatorReader():
        while(True):
            cb.replicator()

    def journalerReader():
        while(True):
            cb.journaler()

    def unmarshallerReader():
        while(True):
            cb.unmarshaller()

    def consumeReader():
        while(True):
            print(cb.consume())

    p1 = multiprocessing.Process(name="p1",target=ReplicatorReader)
    p1.start()

    p0 = multiprocessing.Process(name="p0",target=receiveWriter)
    p0.start()

    p1 = multiprocessing.Process(name="p1",target=ReplicatorReader)
    p1.start()

    p2 = multiprocessing.Process(name="p2",target=journalerReader)
    p2.start()

    p3 = multiprocessing.Process(name="p3",target=unmarshallerReader)
    p3.start()

    p4 = multiprocessing.Process(name="p4",target=consumeReader)
    p4.start()

but I get this Error in my code :
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "C:\Program Files\Python39\lib\multiprocessing\spawn.py", line 116, in spawn_main
  File "C:\Program Files\Python39\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
    exitcode = _main(fd, parent_sentinel)
  File "C:\Program Files\Python39\lib\multiprocessing\spawn.py", line 126, in _main
  File "C:\Program Files\Python39\lib\multiprocessing\spawn.py", line 126, in _main
    self = reduction.pickle.load(from_parent)
    self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'unmarshallerReader' on <module '__mp_main__' from 'd:\\python\\RunDisruptor.py'>
AttributeError: Can't get attribute 'consumeReader' on <module '__mp_main__' from 'd:\\python\\RunDisruptor.py'>

A: Your first problem is that the target of a Process call cannot be within the if __name__ == '__main__': block. But:
As I mentioned in an earlier post of yours, the only way I see that you can share an instance of CircularBuffer across multiple processess is to implement a managed class, which surprisingly is not all that difficult to do. But when you create a managed class and create an instance of that class, what you have is actually a proxy reference to the object. This has two implications:

*

*Each method call is more like a remote procedure call to a special server process created by the manager you will start up and therefore has more overhead than a local method call.

*If you print the reference, the class's __str__ method will not be called; you will be printing a representation of the proxy pointer. You should probably rename method __str__ to something like dump and call that explicitly whenever you want a representation of the instance.

You should also explicitly wait for the completion of the processes you are creating so that the manager service does not shutdown prematurely, which means that each process should be assigned to a unique variable and have a unique name.
import disruptor
import multiprocessing
from multiprocessing.managers import BaseManager
import random

class CircularBufferManager(BaseManager):
    pass

def receiveWriter(cb):
    while(True):
        n = random.randint(5,20)
        cb.receive(n)

def ReplicatorReader(cb):
    while(True):
        cb.replicator()

def journalerReader(cb):
    while(True):
        cb.journaler()

def unmarshallerReader(cb):
    while(True):
        cb.unmarshaller()

def consumeReader(cb):
    while(True):
        print(cb.consume())

if __name__ == '__main__':
    # Create managed class
    CircularBufferManager.register('CircularBuffer', disruptor.CircularBuffer)
    # create and start manager:
    with CircularBufferManager() as manager:
        cb = manager.CircularBuffer(5)

        p1 = multiprocessing.Process(name="p1", target=ReplicatorReader, args=(cb,))
        p1.start()

        p0 = multiprocessing.Process(name="p0",target=receiveWriter, args=(cb,))
        p0.start()

        p1a = multiprocessing.Process(name="p1a",target=ReplicatorReader, args=(cb,))
        p1a.start()

        p2 = multiprocessing.Process(name="p2",target=journalerReader, args=(cb,))
        p2.start()

        p3 = multiprocessing.Process(name="p3",target=unmarshallerReader, args=(cb,))
        p3.start()

        p4 = multiprocessing.Process(name="p4",target=consumeReader, args=(cb,))
        p4.start()

        p1.join()
        p0.join()
        p1a.join()
        p2.join()
        p3.join()
        p4.join()


text:
Q: how dynamically generate excel from dataframe and send as a Email in Python? I have data in the form of nested list. i am converting this data into dataframe. Now i want to convert this dataframe into excel (without storing on local system) and attach/dynamically send mail with this excel file as a attachment
i can download the excel file on local system and then attach to mail and send this mail

but i dont want to store locally it is directly generate and attach to mail and send
data = [['1', 'Ram', 'PL', 'NA', '04/24/19'];['2', 'Dhana', 'PL', 'NA', '04/24/19'],['3', 'Nares', 'A', 'NA', '04/24/19']]

df = pd.DataFrame(data, columns=['ad_id','ename','shift','status','date'])

output
    ad_id   ename   shift   status  date
0   458435  Ram     PL      NA  04/24/19
1   471611  Dhana   PL      NA  04/24/19
2   476934  Naresh  A       NA  04/24/19

I expect it directly generate the excel file and attach to mail and send


text:
Q: Creating time card template in Excel. Over time issues I am trying to formulate a time card template so that once work times are entered regular hours and Overtime hours are separated. I have something like this.
=B3-TIME(8,0,0)

This finds the difference. So if they work 9 hours it shows the difference of 1 which is the correct amount of over time worked. Now my problem is if there is no overtime worked I get an error in this cell. How do I fix it to show 0 or blank if the result is 0 or negative?

A: The easiest is to just wrap your formula in an IF() so you can control what the result is if your test above is <= 0 or not.
So take =B3-TIME(8,0,0) and switch to =IF(B3-TIME(8,0,0)<=0,0,B3-TIME(8,0,0))

A: You can also use an IFERROR function instead of an IF function if you get an Excel error.
That will handle all of the Excel errors you might get and will allow you to specify return values that won't make calculations (SUM, AVG, etc.) on the range return strange results.


text:
Q: Opening a Dialog with text input from within a View in Android I have an app with a View based on the SurfaceHolder (similar to the Lunar Lander tutorial).
The whole GUI is drawn on a canvas, and I want to be able to prompt for user text input at a given moment using a custom layout Dialog, that is then taken care of and rendered to the canvas using standard procedure.
My problem, however, is that it seems that best practice is to open Dialogs from the Activity.
This is no problem either, since i thought i might create a Handler and then pass it to the View that could in turn use it to pass Messages from the GUI thread in the View on to the Activity, that in turn could fetch the input, and send a reply back, etc.
Problem is, after I call setContentView(R.layout.main), which contains the whole app, i want to call MyAppView mMyAppView = (MyAppView) findViewById(R.id.app_view_id).
This call returns null.
What is considered to be best practice here? I can't find any good examples and the API is turning up, well, not much.
I would appreciate any help here.

A: Create a dialog themed activity to display over your current activity.
public class TextEntryActivity extends Activity {
    private EditText et;

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_text_entry);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
        // title
        try {
            String s = getIntent().getExtras().getString("title");
            if (s.length() > 0) {
                this.setTitle(s);
            }
        } catch (Exception e) {
        }
        // value

        try {
            et = ((EditText) findViewById(R.id.txtValue));
            et.setText(getIntent().getExtras().getString("value"));
        } catch (Exception e) {
        }
        // button
        ((Button) findViewById(R.id.btnDone)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                executeDone();
            }
        });
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        executeDone();
        super.onBackPressed();
    }

    /**
     *
     */
    private void executeDone() {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("value", TextEntryActivity.this.et.getText().toString());
        setResult(Activity.RESULT_OK, resultIntent);
        finish();
    }

}

Launch by:
Intent foo = new Intent(this, TextEntryActivity.class);
foo.putExtra("value", "old value to edit");
this.startActivityForResult(foo, EDIT_ACTION);

then catch the response on onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case EDIT_ACTION:
                try {
                    String value = data.getStringExtra("value");
                    if (value != null && value.length() > 0) {
                        //do something with value
                    }
                } catch (Exception e) {
                }
                break;
            default:
                break;
        }
    }

Manifest is defined as:
<activity
            android:name=".utils.TextEntryActivity"
            android:label="Type in the value"
            android:theme="@android:style/Theme.Dialog" />

A: I am also looking to answer this question for myself.  The answer already here is a good one.  The android developer page as alter dialog samples.
I haven't read it completely yet, but if you search for the tag
DIALOG_TEXT_ENTRY
this would seem to be what you (and I) need.
I'm going to investigate that example first.


text:
Q: How to get only some of the elements of an object using only for-in and if-else For example, if we have the following object in javascript:
var person,
    property;

    person = {
        firstName: "John",
        lastName:"Doe",
        age: 50,
        eyeColor: "blue",
        hairColor: "black",
        profession: "doctor"
    }

How do I print out only the second and fourth property of this object with for-in and if-else?

A: another way would be.
var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue",
    hairColor: "black",
    profession: "doctor"
  }

  for(key in person){
    var index = Object.keys(person).indexOf(key);
    if(index === 1 || index === 3){
      console.log("Key:", key, ", Value:", person[key]);
    }
  }


text:
Q: Dados não são salvos no banco de dados Estou usando Java, JPA, PrimeFaces, Wildfly e Mysql, não tem muito a ver, mas é bom informar.
Eu preencho todos os campos, tudo certo a verificação é realizada. Quando clico em salvar a mensagem de sucesso é exibida, mas nada é salvo no banco, alguém pode me ajudar a identificar onde está o erro?
Eu tenho a minha página xhtml:
<!DOCTYPE html >
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets" template="template.xhtml">

    <ui:define name="conteudoForm">

Cadastro de solicitação

        <h:panelGrid columns="1">
            <h:panelGrid columns="1">
                <h:panelGrid columns="2">

                </h:panelGrid>
                <h:panelGrid columns="2" style="margin-bottom:10px">

                        <f:selectItem itemLabel="Selecione..." itemValue="Selecione" />
                        <f:selectItem itemLabel="Alta" itemValue="Alta" />
                        <f:selectItem itemLabel="Média" itemValue="Média" />
                        <f:selectItem itemLabel="Baixa" itemValue="baixa" />

                </h:panelGrid>
                <h:panelGrid>

Descrição da Solicitação

                    <h:panelGrid columns="3" style="margin-top: 10px">
                        <h:panelGroup>

                        </h:panelGroup>

                    </h:panelGrid>
                </h:panelGrid>
            </h:panelGrid>
        </h:panelGrid>
    </ui:define>

</ui:composition>

Este é o meu DAO:
package br.com.sicoob.DAO;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.sicoob.Service.CadastroService;
import br.com.sicoob.entidades.Cadastro;

@Stateless
public class CadastroDAO implements Serializable, CadastroService {

    private static final long serialVersionUID = 1L;

    @PersistenceContext
    private EntityManager em;

    public void salvar(Cadastro c) {
        if (c.getId() == null) {
            em.persist(c);
        } else {
            em.merge(c);
        }
    }

    public void remover(Cadastro c) {
        c = em.merge(c);
        em.remove(c);
    }

    @SuppressWarnings("unchecked")
    public List<Cadastro> listarTodos() {
        List<Cadastro> cadastro = new ArrayList<Cadastro>();
        Query q = em.createQuery("select obj from Cadastro obj");
        cadastro = q.getResultList();
        return cadastro;
    }

    public Cadastro buscarPorId(Long id) {
        return em.find(Cadastro.class, id);
    }

    public Cadastro carregarEntidade(Cadastro c) {
        return em.merge(c);
    }

    @Override
    public void salvarUsuario(Cadastro cadastro) {
        // TODO Auto-generated method stub

    }

    @Override
    public void salvarCadastro(Cadastro cadastro) {
        // TODO Auto-generated method stub

    }
}

Minha entidade:
package br.com.sicoob.entidades;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;

/**
 * The persistent class for the cadastro database table.
 *
 */
@Entity
@Table(name="cadastro")
@NamedQuery(name="Cadastro.findAll", query="SELECT c FROM Cadastro c")
public class Cadastro implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @Temporal(TemporalType.DATE)
    private Date data;

    private String descricao;

    private String prioridade;

    private String setor;

    private String solicitante;

    private String titulo;

    // getters e setters

}

Meu MB:
package br.com.sicoob.ManagedBeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import br.com.sicoob.Service.CadastroService;
import br.com.sicoob.entidades.Cadastro;

@ManagedBean(name = "cadastroMB")
@ViewScoped
public class CadastroMB implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private CadastroService cadastroService;

    private Cadastro cadastro = new Cadastro();
    private List<Cadastro> listaCadastro = new ArrayList<Cadastro>();
    private boolean edicao = false;

    @PostConstruct
    public void init() {
        listaCadastro = cadastroService.listarTodos();
    }

    /**
     * Método responsavel por adicionar cadastro
     */

    public void salvar() {

        if (validarCadastro(cadastro) == false) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Favor preencher todos os campos"));
            return;
        }
        cadastroService.salvarCadastro(cadastro);
        listaCadastro = cadastroService.listarTodos();

        cadastro = new Cadastro();
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "", "cadastro adicionado com sucesso"));
    }

    private boolean validarCadastro(Cadastro cadastro) {
        if (cadastro.getSolicitante() == null || "".equals(cadastro.getSolicitante())) {
            return false;
        }
        if (cadastro.getTitulo() == null || "".equals(cadastro.getTitulo())) {
            return false;
        }
        if (cadastro.getSetor() == null || "".equals(cadastro.getSetor())) {
            return false;
        }

        if (cadastro.getTitulo() == null || "".equals(cadastro.getTitulo())) {
            return false;
        }
        if (cadastro.getData() == null || "".equals(cadastro.getData())) {
            return false;

        }

        return true;
    }

    public String redirecionar() {
        return "perfil";

    }

    /**
     * Método responsavel por adicionar cadastro
     */
    public void atualizar() {
        cadastroService.salvarCadastro(cadastro);
        cadastro = new Cadastro();
        edicao = false;
    }

    public void remover(Cadastro c) {
        cadastroService.remover(c);
        listaCadastro = cadastroService.listarTodos();
        c = new Cadastro();
    }

    public void editar(Cadastro c) {
        this.cadastro = c;
        edicao = true;
    }

    public List<Cadastro> getListaCadastro() {
        return listaCadastro;
    }

    public void setListaCadastro(List<Cadastro> listaCadastro) {
        this.listaCadastro = listaCadastro;
    }

    public Cadastro getCadastro() {
        return cadastro;
    }

    public void setCadastro(Cadastro cadastro) {
        this.cadastro = cadastro;
    }

    public boolean isEdicao() {
        return edicao;
    }

    public void setEdicao(boolean edicao) {
        this.edicao = edicao;
    }
}

e o Service:
package br.com.sicoob.Service;

import java.util.List;

import br.com.sicoob.entidades.Cadastro;

public interface CadastroService {

    public List<Cadastro> listarTodos();

    public void salvarUsuario(Cadastro cadastro);

    public void salvarCadastro(Cadastro cadastro);

    public void remover(Cadastro c);

}

A: Não trabalho com JPA, mas pela descrição que voce deu do comportamento e pelo seu método salvar. Creio que está faltando um commit. Se sua conexão estiver configurada com setAutoCommit(false).
Voce tem que dar o commit no final da execução.
de uma olhada aqui, explica qual o procedimento para commit com jpa
http://www.java2s.com/Code/Java/JPA/StartTransactionandCommit.htm


text:
Q: Spring Data JPA - Hibernate - OneToMany, ManytoOne bidirectional Have 2 Entities: Orders and Products. 1 Order can have Many Products and Many Products can belong to 1 Order (Each Product only belongs to 1 Order).
With unidirectional association at Order Entity, I am able to retrieve product details when performing orderRepo.findAll(); In similar fashion, need order details when performing productRepo.findAll();
Tried code:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "order_details")
public class OrderData {

    @Id
    @Column(name = "order_id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long orderId;

    @NotNull
    @Column(name = "customer_name", nullable = false)
    private String customerName;

    @OneToMany(mappedBy = "productId", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<ProductData> products;

}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "product_details")
public class ProductData {

    @Id
    @Column(name = "product_id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long productId;

    @NotNull
    @Column(name = "product_name", nullable = false)
    private String productName;

    @ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.ALL)
    @JoinColumn(name = "order_id", nullable = false)
    private OrderData orderData;
}

While inserting at products; we are getting error: "insert or update on table violates foreign key constraint jpa"
While performing productRep.findAll(): infinite loop for hibernate select queries
Tried @JsonIgnore. This not returning child or parent elements.
Tried @JsonManagedReference vs @JsonBackReference - still no luck.
Please guide me on this

A: The mappedBy attribute points to the wrong field:
@OneToMany(mappedBy = "productId", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<ProductData> products;

This must be the back reference:
@OneToMany(mappedBy = "orderData", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<ProductData> products;


text:
Q: How to find ASCII value of a character in wtx In a string, I want to replace all the characters between ASCII value of 0-32 and 127-255 to spaces. I have been breaking my head for 4 days and but not able to find the solution.

A: There is no shortcut for replacing ranges, but you can use the SUBSTITUTE function to replace each individual character.
=SUBSTITUTE(string,
SYMBOL(0), " ",
SYMBOL(1), " ",
// etc.
SYMBOL(254), " ",
SYMBOL(255), " ")


text:
Q: how to call javascript variables in jQuery? I basically made a program that generates random ball numbers based on how many balls the user wants to display on the screen and then the user has to type in the ball numbers in order and if he guesses it right, he wins or else he loses. However, jQuery is a bit confusing for me. How exactly do I call the x[i] variable with its values assigned to it to the jQuery at the bottom of the program? Oh and also, the number of balls and input bars are supposed to display based on the maximun number of balls the user types in but is it really possible for me to use array with html and jQuery? So that if the user types in 3, only 3 inputs get displayed or when he types in 6 only 6 gets displayed? Thanks

<canvas id="canvas" width="800" height="800" style="border: 2px solid #000000">
</canvas>

<<form name="guessForm" id="guessForm" method="POST" action="">
Enter a number:
<input type="text" name="userNumber" id="userNumber">
<input type="button" id="verifyBtn" value="verify">
</form>
<form name="guessForm" id="guessForm2" method="POST" action="">
Enter a number:
<input type="text" name="userNumber2" id="userNumber2">
<input type="button" id="verifyBtn2" value="verify">
</form>
<form name="guessForm" id="guessForm3" method="POST" action="">
Enter a number:
<input type="text" name="userNumber3" id="userNumber3">
<input type="button" id="verifyBtn3" value="verify">
</form>
<form name="guessForm" id="guessForm4" method="POST" action="">
Enter a number:
<input type="text" name="userNumber4" id="userNumber4">
<input type="button" id="verifyBtn4" value="verify">
</form>
<form name="guessForm" id="guessForm5" method="POST" action="">
Enter a number:
<input type="text" name="userNumber5" id="userNumber5">
<input type="button" id="verifyBtn5" value="verify">
</form>
<form name="guessForm" id="guessForm6" method="POST" action="">
Enter a number:
<input type="text" name="userNumber6" id="userNumber6">
<input type="button" id="verifyBtn6" value="verify">
</form>

the result is:

A: I cannot really look through your whole code for you. Try to be as specific and generic as possible so others can use your question as well. As for jquery this is how you get the value of an input and store it to variable x.

      <input type="text" name="userNumber" id="userNumber" value="5">
      </form>

I put in a   $(function(){}); (https://api.jquery.com/ready/) because i want the DOM to be ready or else input is undefined.

A: Firstable - your x variable cannot be reach in jQuery section.
In your code it is a local variable.
Your code is quite messy but first and dirty fix you can do and come up to my mind is to make a global variable and at the end of draw function set it's value to be like x
window.onload=draw;
var xArr;

and then at the end of draw function
xArr = x;

After that you should replace all "x" occurances in your jQuery code to xArr.
It is fast fix to your code.
And also it is fast fix to get correct number of balls and user input validation.
It should look something like this
window.onload=draw;
    var xArr
  var BallsNumber = 0;
 function draw(){
    var canvas= document.getElementById('canvas');
    var ctx=canvas.getContext('2d');
    var id;
    var x;
    var y;
    var r;
    var i;

    var balls=[{"id":1,"x":85,"y":90,"r":40},{"id":2,"x":180,"y":90,"r":40},{"id":3,"x":270,"y":90,"r":40},{"id":4,"x":360,"y":90,"r":40},{"id":5,"x":450,"y":90,"r":40},{"id":6,"x":535,"y":90,"r":40},{"id":7,"x":623,"y":90,"r":40},{"id":8,"x":710,"y":90,"r":40},{"id":9,"x":85,"y":190,"r":40},{"id":10,"x":180,"y":190,"r":40},{"id":11,"x":270,"y":190,"r":40},{"id":12,"x":360,"y":190,"r":40},{"id":13,"x":450,"y":190,"r":40},{"id":14,"x":535,"y":190,"r":40},{"id":15,"x":623,"y":190,"r":40},{"id":16,"x":710,"y":190,"r":40},{"id":17,"x":450,"y":190,"r":40},{"id":18,"x":535,"y":190,"r":40},{"id":19,"x":623,"y":190,"r":40},{"id":20,"x":710,"y":190,"r":40}];
    var texts=[];
    for(i=0;i<balls.length;i++){
      texts[i]=i;
    }
        var x=[];
    var choose;

while(true){
    choose=parseFloat(prompt("enter the number of balls u want to see (less than 20)"));
    if(choose < 20){
        break;
    }else{
        alert("Please enter a valid number");
    }
}

while(BallsNumber<choose){
    for (i=0; i<choose; i++) {
       x[i]=Math.floor((Math.random() * 19) + 1);
      for (var k=0; k<balls.length; k++) {

        var b=balls[k];
        if(b.id==x[i]){                  /*here is the issue*/
          ctx.fillStyle="#800000";
          ctx.strokeStyle="#000000";
          ctx.beginPath();
          ctx.arc(b.x,b.y,b.r,0, 2 * Math.PI);
          ctx.stroke();
          ctx.fill();
          ctx.fillStyle = 'black';
          ctx.fillText(b.id, b.x, b.y);
          BallsNumber++;
        }
      }

    }
}

    xArr = x;
  }

draw()

    $(document).ready(function(){

            $("#verifyBtn").click(function(){

                if($("#userNumber").val()==xArr[0]){
                        $("#result").css({color:'green'});
                        $("#result").text("correct");
                    }

                    else{
                        $("#result").css({color:'red'});
                        $("#result").text("sorry: try again"+ " correct number was "+ xArr);
                    }

            })
            $("#verifyBtn2").click(function(){

                if($("#userNumber2").val()==xArr[1]){
                        $("#result").css({color:'green'});
                        $("#result").text("yeah");
                    }

                    else{
                        $("#result").css({color:'red'});
                        $("#result").text("sorry: try again"+ " correct number was "+ systemNumber);
                    }

            })
            $("#verifyBtn3").click(function(){

                if($("#userNumber3").val()==xArr[2]){
                        $("#result").css({color:'green'});
                        $("#result").text("yeah");
                    }

                    else{
                        $("#result").css({color:'red'});
                        $("#result").text("sorry: try again"+ " correct number was "+ xArr);
                    }

            })
            $("#verifyBtn4").click(function(){

                if($("#userNumber4").val()==x[3]){
                        $("#result").css({color:'green'});
                        $("#result").text("yeah");
                    }

                    else{
                        $("#result").css({color:'red'});
                        $("#result").text("sorry: try again"+ " correct number was "+ xArr[3]);
                    }

            })
            $("#verifyBtn5").click(function(){

                if($("#userNumber5").val()==x[4]){
                        $("#result").css({color:'green'});
                        $("#result").text("yeah");
                    }

                    else{
                        $("#result").css({color:'red'});
                        $("#result").text("sorry: try again"+ " correct number was "+ xArr[4]);
                    }

            })
            $("#verifyBtn6").click(function(){

                if($("#userNumber6").val()==xArr[5]){
                        $("#result").css({color:'green'});
                        $("#result").text("yeah");
                    }

                    else{
                        $("#result").css({color:'red'});
                        $("#result").text("sorry: try again"+ " correct number was "+ xArr[5]);
                    }

            })
    })

You have a global variable BallsNumber so you can find a solution to make a loop and create a correct number of "verify" inputs


text:
Q: How can I add mail from a local host to the list of Outlook _Safe Senders_? We have an application (Bugzilla) running on a server local to our network. The email that is send out is from bugzilla-daemon@ourprojbugz (notice that there are no domain qualifiers such as .com or .org). When I try to add this address to the list of Safe Senders I get a warning popup that says:

The e-mail address or domain name you entered is not valid.
  Valid entries include: someone@example.com or example.com

Microsoft is trying to be helpful here (because most email comes from hosts that have some sort of top level domain identifier).
Our network is set up so that we get to the bugzilla database using the URL:

http://ourprojbugz/cgi-bin/bugzilla3/index.cgi

I have tried using the Never Block Sender option from the Delete section of the Home menu, and also tried adding it manually in the Safe Senders tab of the Junk E-mail Options form.
Is there some way to add email from a local host (one that is not qualified by a Top Level Domain name)?

A: It is stored in the registry:
HKCU\Software\Microsoft\Windows NT\Current Version\Windows Messaging Subsystem\Profiles\Outlook
(Or the profile name). It is stored in binary – I confirmed that there was a write to this location via ProcMon against OUTLOOK.EXE.
Your host should have an FQDN if its going to send email anyways even local, can you not add .local or .lan to this host's name? If using a Red Hat derivitive it would be in /etc/sysconfig/network.

A: Instead of using the Junk filters, you can create a rule to do this.
Rules (in the Move section of the Home menu) can be used to move mail from a specific sender to a specified mail folder.
Open a message from the sender (in this example, bugzilla-daemon@ourprojbugz). When the message is open, select the Rules in the Move section of the Home menu and create a rule.
In the When I get e-mail ... section of the Create Rule form, check the box to select From bugzilla-daemon@ourprojbugz
In the Do the following section of the Create Rule form, check the box for Move the item to folder:, and select the folder you want the mail to go into.


text:
Q: CoreLocation stops monitoring after few minutes Device (iPhone 4s, iOS 8.4) situated in Region with 3 iBeacon devices. After 4-9 minutes of laying CoreLocation generate ExitRegion. After few minutes generate ExitRegion and continues working. All this time application in the foreground and connected to x-code.
UPD: It does not reproduce in (iOS>9 and iPhones 5).
On my device, it reproduces in 1 minute if I browser in facebook


text:
Q: hyperlink with % does not work inside a marginote? In preparing answer for some mathematics question, I link the answer to some Wolfram Alpha link for checking. The error appears when I put some Wolfram Alpha link in inside a \href, in turn, inside a \marginnote. I just guess the reason is somme % character in the link.
Could anyone help me about these?

\documentclass{article}
\usepackage{hyperref}
\usepackage{lipsum}
\usepackage{marginnote}
\begin{document}
\lipsum[1]
\hfill \href{https://www.wolframalpha.com/input/?i=%5B%5B4%2C6%2C6%5D%2C%5B1%2C3%2C2%5D%2C%5B-1%2C-5%2C-2%5D%5D}{Check Wolfram Alpha} % not sure working properly, but seems OK!

\lipsum[2]
\marginnote{\href{www.ams.org}{www.ams.org}} % OK!

\lipsum[3]
\marginnote{\href{https://www.wolframalpha.com/input/?i=%5B%5B4%2C6%2C6%5D%2C%5B1%2C3%2C2%5D%2C%5B-1%2C-5%2C-2%5D%5D}{Check Wolfram Alpha}} %<<< error. Comment this line to get a MWE.

\end{document}

A: href has no chance to change the catcode of % if you use it in the argument of another command. But you could store the url first in a macro:
\documentclass{article}
\usepackage{hyperref}
\usepackage{lipsum}
\usepackage{marginnote}

\makeatletter
\newcommand\saveurl[1]{\begingroup\catcode`\%=12 \catcode`\#=12  \@saveurl#1}
\newcommand\@saveurl[2]{\endgroup\newcommand#1{#2}}
\makeatother

\saveurl\myurl{https://www.wolframalpha.com/input/?i=%5B%5B4%2C6%2C6%5D%2C%5B1%2C3%2C2%5D%2C%5B-1%2C-5%2C-2%5D%5D}

\begin{document}
\lipsum[1]

\hfill \href{\myurl}{Check Wolfram Alpha} %

\lipsum[2]
\marginnote{\href{www.ams.org}{www.ams.org}} % OK!

\lipsum[3]
\marginnote{\href{\myurl}{Check Wolfram Alpha}} %

\end{document}

A: You can define a \marginhref command:
\documentclass{article}

\usepackage{marginnote}
\usepackage{hyperref}

\makeatletter % we want to use private commands
\newcommand{\marginhref}{%
  \begingroup
  \@makeother\%\@makeother\#%
  \@makemarginhref
}
\def\@makemarginhref#1#2{%
  \marginnote{\href{#1}{#2}}%
  \endgroup
}
\makeatother

\begin{document}
This has a link
\href{https://www.wolframalpha.com/input/?i=%5B%5B4%2C6%2C6%5D%2C%5B1%2C3%2C2%5D%2C%5B-1%2C-5%2C-2%5D%5D}{Check Wolfram Alpha} % not sure working properly, but seems OK!

This has a link in the margin\marginnote{\href{www.ams.org}{www.ams.org}} % OK!

Also this has a link in the margin
\marginhref{https://www.wolframalpha.com/input/?i=%5B%5B4%2C6%2C6%5D%2C%5B1%2C3%2C2%5D%2C%5B-1%2C-5%2C-2%5D%5D}{Check Wolfram Alpha}

\end{document}


text:
Q: workflow_run is never trigged by pull_request I have two very simple GitHub workflows for testing proposes. deploy-test-first which runs always on pull_request and deploy-test-second which should run on completion of deploy-test-first
The deploy-test-second however never runs. What Am I missing? How do I make it work?
name: deploy-test-first

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  deploy-test-first:
    runs-on: ubuntu-20.04
    steps:
      - name: deploy-test-first
        run: echo 'deploy-test-first'

name: deploy-test-second

on:
  workflow_run:
    workflows: [deploy-test-first]
    types: [completed]
    branches: [develop]

jobs:
  test-deploy-second:
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-20.04
    steps:
      - name: test-deploy-second
        run: echo 'deploy-test-second'

Both workflows are suppose to run on non-default branch develop in PR.