text:
Q: Active_admin: ArgumentError in Admin/events#index I've just installed active_admin and created the first resource - videos - perfectly find.  Everything worked like a charm.
But now that I'm trying to add 'users' and 'events' it is failing with the same message when I navigate to them in the menu.
Here is what it says:
   ArgumentError in Admin/events#index

    Showing /Users/markwalker/.rvm/gems/ruby-1.9.3-p327/gems/activeadmin-0.5.1/app/views/active_admin/resource/index.html.arb where line #1 raised:

    wrong number of arguments (3 for 1)
    Extracted source (around line #1):

    1: insert_tag renderer_for(:index)
    Rails.root: /Users/markwalker/Xavy2

    Application Trace | Framework Trace | Full Trace
    app/helpers/application_helper.rb:3:in `select_tag'
    Request

`Parameters`:

    {"order"=>"id_desc"}

Has anyone experience this before, or have an idea about what might be causing it?
Let me know if I need to add more code to make sense of the problem.
Thanks in advance for any help...

A: Couple observations, jfdimark
Shouldn't {"order"=>"id_desc"} be {"order"=>"id desc"} (no underscore)?
Apart from that, it's hard to diagnose without seeing the Full Trace.  A similar problem with ArgumentError in Admin/dashboard#index brought me to your question in the first place, but simply looking at my Full Trace I saw:
RedCloth (4.2.9) lib/redcloth/erb_extension.rb:16:intextilize'`
as the first line. I actually wasn't using RedCloth in this project, so I took it out of my Gemfile and all's good.


text:
Q: Reading from and Writing to a processes I/O? Suppose we have two programs, A and B. B prints something continuously and reads input too. (probably there are two processes in B using same I/O, I don't know if it is possible or not...)
A have to read B's output and decide about what to say to B, then sends a string to B's input. (just like that someone inputs text by keyboard to B).
I know that B uses std::cout to send messages to output and uses std::cin for read input.
How can I write A using C++ and standard library? Is this related to sockets or ipc?
Note: I'm using a i386 Linux system.

A: You can use the unofficial boost Process library, which has an excellent tutorial of exactly what you want to do and is bound to be an official part of boost any time now. It's also naturally cross-platform. HTH

redpajama_set_name: RedPajamaStackExchange


text:
Q: Method to Find Out When Users Cancelled Using Dictionaries I have created a dictionary of either {'username': 'date'} or {'date': 'username'} (I can change the order of the key: value pair to whichever I want). To set the values I need to say...
{'Jacob Rasnip': 'Apr', 'Andrew Alexander': 'Apr', 'Jacob Rasnip': 'May'}

or the opposite...
{'Apr': 'Jacob Rasnip'}

I have about 1500 of dictionary values, all users with different months assigned to them or months assigned with users.
I want a way to iterate through a dictionary of keys and values, and figure out which month was the first month a customer appeared. I also want to find the last month that the customer appeared.
Could someone please offer advice as to the best way to achieve this.

A: A dictionary cannot have duplicate keys. For example, it can only have one key 'Jacob Rasnip'. Your example shows two.
Similarly, a dictionary could only have one key 'Apr'.
If instead you had dictonary of usernames mapping to a list of datetime.dates:
{'Jacob Rasnip': [datetime.date(2011,4,1),datetime.date(2011,5,1),]...}

Then you could generate the first and last months with
for user,dates in user_dict.iteritems():
    first_date = min(dates)
    last_date = max(dates)
    print(user,first_date,last_date)

Note min and max rely on the items in dates being datetime.date objects. It would also work with simple integers representing the months (assuming all months refer to the same year). But it would not work as desired with string names for the months (e.g. 'Apr').

A: You said.

Could I have each name (as a key) have multiple values? Currently I'm combining two lists (one of names, the other of dates) like this: testdict = dict(zip(name, date))

No, but you can combine those values in a way that looks like unutbu's answer.
import collections
data = collections.defaultdict(list)

for n, d in zip(name, date):
    data[n].append(d)


text:
Q: Prevent scoreboard score from dropping below zero So I have this server I'm working on, but when a player makes a purchase, their money can drop to negative numbers.  I have researched but could not find an answer. The Name is Money. Please tell me how!

A: You have to verify the player has enough money before they are allowed to purchase the item.
The command that you use to give the player an item and the command you use to remove the money need to have the proper target selector with arguments.  The arguments will make sure they have enough money before it gives the item.  In the case of the scoreboard, you will use the argument score_*name*_min=x where *name* represents the objective name you use to store money and x represents the minimum amount.
As an example, lets say 1 diamond cost 3 units of currency and Money is the objective name that stores player's currency.   The commands to give the diamond and remove the money could be:
give @p[score_Money_min=3] minecraft:diamond 1 0

scoreboard players remove @p[score_Money_min=3] Money 3

Edit:  Response to the comment.
A quote from the wiki:

Selecting targets by score
  [score_name=SCORE] — Selects only targets with a score in objective name of no more than SCORE.
  [score_name_min=SCOREMIN] — Selects only targets with a score in objective name of no less than SCOREMIN.
  For example, @a[score_points_min=30,score_points=39] will select all players with a score in objective "points" between 30 and 39 (inclusive).


text:
Q: Scrapy follow 302 redirect immediately I'm using scrapy on an ASP site where all of the links are similar:
javascript:__doPostBack('gridID','Select$0')
javascript:__doPostBack('gridID','Select$1')
....

I am able to use a FormRequest to follow the link to the detail page for any record:
    # Let's first grab all of the Details links -- we can get everything from them that we want
    for sel in response.xpath("//table[@id='gridID']/tr[td]")[0:20]:
        thisTarget  = sel.xpath("td")[0].xpath("a/@href").extract()[0].split("'")[1]
        thisArg     = sel.xpath("td")[0].xpath("a/@href").extract()[0].split("'")[3]
        yield scrapy.FormRequest.from_response(
                response,
                formdata={'__EVENTTARGET'   : thisTarget,
                          '__EVENTARGUMENT' : thisArg,
                          '__EVENTVALIDATION': response.xpath("//input[@id='__EVENTVALIDATION']/@value").extract()[0],
                          '__VIEWSTATE': response.xpath("//input[@id='__VIEWSTATE']/@value").extract()[0]
                         },
                dont_click=True,
                callback=self.parseDetail,
                dont_filter=True
            )

But when scrapy processes multiple items at a time, it makes the requests in batches.  Five rows at once would result in:
2015-02-20 22:41:19-0500 [spider] DEBUG: Redirecting (302) to <GET http://domain.com/ListingDetail.aspx> from <POST http://domain.com/Listing.aspx>
2015-02-20 22:41:20-0500 [spider] DEBUG: Redirecting (302) to <GET http://domain.com/ListingDetail.aspx> from <POST http://domain.com/Listing.aspx>
2015-02-20 22:41:20-0500 [spider] DEBUG: Redirecting (302) to <GET http://domain.com/ListingDetail.aspx> from <POST http://domain.com/Listing.aspx>
2015-02-20 22:41:21-0500 [spider] DEBUG: Redirecting (302) to <GET http://domain.com/ListingDetail.aspx> from <POST http://domain.com/Listing.aspx>
2015-02-20 22:41:22-0500 [spider] DEBUG: Redirecting (302) to <GET http://domain.com/ListingDetail.aspx> from <POST http://domain.com/Listing.aspx>
2015-02-20 22:41:22-0500 [spider] DEBUG: Crawled (200) <GET http://domain.com/ListingDetail.aspx> (referer: http://domain.com/Listing.aspx)
### Callback executed
2015-02-20 22:41:23-0500 [spider] DEBUG: Crawled (200) <GET http://domain.com/ListingDetail.aspx> (referer: http://domain.com/Listing.aspx)
### Callback executed
2015-02-20 22:41:23-0500 [spider] DEBUG: Crawled (200) <GET http://domain.com/ListingDetail.aspx> (referer: http://domain.com/Listing.aspx)
### Callback executed
2015-02-20 22:41:24-0500 [spider] DEBUG: Crawled (200) <GET http://domain.com/ListingDetail.aspx> (referer: http://domain.com/Listing.aspx)
### Callback executed
2015-02-20 22:41:24-0500 [spider] DEBUG: Crawled (200) <GET http://domain.com/ListingDetail.aspx> (referer: http://domain.com/Listing.aspx)
### Callback executed

This seems to lead to all 5 of the responses being identical, a result of some of the ASP magic, I suppose.
I have tried to set REDIRECT_PRIORITY_ADJUST = 100 to give the redirects more priority, with limited success.  The best this has done is to stop after 16 initial requests, and do 16 of the redirects, then another batch of initial requests, and so on....
When I do things manually in scrapy shell, by fetching each of the FormRequests, the redirect is processed immediately and I get the expected response, even when fetching multiple requests in a row.
Thus, my question:
Is there any way to get scrapy to process a request all the way to a HTTP 200 response, executing any redirects along the way immediately?
Or ... any other solution to my problem that may not be obvious?

A: I got the same problem when using FormRequest and the site sends back 302 redirect. Responses are identical for many requests. It seems to be something before downloader middleware, or even between scrapy request and twisted since I put a custom downloader middleware to see the response and the request made. It has the same problem.
Found a workaround by using the following scrapy settings.
CONCURRENT_REQUESTS=1
CONCURRENT_REQUESTS_PER_DOMAIN=1

There should be a better way though.


text:
Q: Issue with TensorFlow Summary I tried to modify "mnist_with_summaries.py" for analyzing image data from my research.
When I tried to use TensorBoard for visualization, following error appeared (0x2e414f0 Compute status: Out of range: Nan in summary histogram for: HistogramSummary):
W tensorflow/core/common_runtime/executor.cc:1102] 0x2e414f0 Compute status: Out of range: Nan in summary histogram for: HistogramSummary
     [[Node: HistogramSummary = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](HistogramSummary/tag, weights/read)]]
W tensorflow/core/common_runtime/executor.cc:1102] 0x2e414f0 Compute status: Out of range: Nan in summary histogram for: HistogramSummary_1
     [[Node: HistogramSummary_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](HistogramSummary_1/tag, bias/read)]]
W tensorflow/core/common_runtime/executor.cc:1102] 0x2e414f0 Compute status: Out of range: Nan in summary histogram for: HistogramSummary
     [[Node: HistogramSummary = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](HistogramSummary/tag, weights/read)]]
     [[Node: _send_train/ScatterUpdate_0 = _Send[T=DT_FLOAT, client_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1698099469756475374, tensor_name="train/ScatterUpdate:0", _device="/job:localhost/replica:0/task:0/cpu:0"](train/ScatterUpdate)]]
Traceback (most recent call last):
  File "NeuralNetwork_TensorFlow.py", line 102, in main
    update_op_train, train_step], feed_dict=feed)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 315, in run
    return self._run(None, fetches, feed_dict)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 511, in _run
    feed_dict_string)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 564, in _do_run
    target_list)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 586, in _do_call
    e.code)
OutOfRangeError: Nan in summary histogram for: HistogramSummary
     [[Node: HistogramSummary = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](HistogramSummary/tag, weights/read)]]
Caused by op u'HistogramSummary', defined at:
  File "NeuralNetwork_TensorFlow.py", line 124, in <module>
    main()
  File "NeuralNetwork_TensorFlow.py", line 58, in main
    w_hist = tf.histogram_summary("weights", W)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/summary_ops.py", line 60, in histogram_summary
    tag=tag, values=values, name=scope)
  File "/usr/lrflow/python/ops/gen_summary_ops.py", line 34, in _histogram_summary
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2040, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1087, in __init__
    self._traceback = _extract_stack()ocal/lib/python2.7/dist-packages/tensorflow/python/ops/gen_summary_ops.py", line 34, in _histogram_summary
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2040, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1087, in __init__
    self._traceback = _extract_stack()

I was wondering why ? what does this "Out of range" mean ?
Here is part of my modified code:
...
sess = tf.Session()

#training data
trainDS = trainds.read_data_sets(ins_size, step);
testDS = testds.read_data_sets(img, ins_size, step)

batch_num  = testDS.test.ylength
batch_size = testDS.test.xlength

# Create the model
x = tf.placeholder(tf.float32, shape=[None, ins_size**2*3], name = "x_input")
y_ = tf.placeholder(tf.float32, [None, label_option], name="y_input")
W = tf.Variable(tf.zeros([ins_size**2*3,label_option]), name = "weights")
b = tf.Variable(tf.zeros([label_option]), name = "bias")

with tf.name_scope("Wx_b") as scope:
  y = tf.nn.softmax(tf.matmul(x, W) + b)

#Add summary ops to collect data
w_hist = tf.histogram_summary("weights", W)
b_hist = tf.histogram_summary("biases", b)
... ...
merged_train = tf.merge_summary([w_hist, b_hist])
writer = tf.train.SummaryWriter("/tmp/neuralnetwork_logs", \
                   sess.graph.as_graph_def(add_shapes=True))
init = tf.initialize_all_variables()
sess.run(init)

#train
for i in range(batch_num):
  batch_xs, batch_ys = trainDS.train.next_batch(batch_size)
  feed = {x: batch_xs, y_: batch_ys, batch_index: i}
  if i % 100 == 0:  # Record summary data
    result = sess.run([merged_train, \
       update_op_train, train_step], feed_dict=feed)
    writer.add_summary(result[0], i)
  else:
    sess.run([update_op_train, train_step], feed_dict=feed)

sess.close()
... ...

Please help me!


text:
Q: Programmatically change the speed of an audio file in real-time Environment

*

*Hardware: Raspberry Pi x

*O.S.: Raspbian Jessie Lite

*Language: Qt5 / C++

Goal
Execute an audio file (wav or better mp3) changing its speed smoothly and countinuosly. The pitch should change according to the speed (playback rate).
My application updates several times per second a variable that contains the desired speed: i.e. 1.0 = normal speed. Required range is about 0.2 .. 3.0, with a resolution of 0.01.
The audio is likely music, expected format: mono, 16-bit, 11.025 Hz.
No specific constraints about latency: below 500 ms is acceptable.
Some thougths
QMediaPlayer in QtMultimedia has the playbackRate property that should do exactly this. Unfortunately I have never be able to make QtMultimedia work in my systems.
It's ok to use also an external player, and send data using pipes or any IPC.
How would you achieve this?

A: I don't know how much of this translates to C++. The work I did on this problem uses Java. Still, something of the algorithm should be of help.
Example data (made up):
sample    value
0          0.0
1          0.3
2          0.5
3          0.6
4          0.2
5         -0.1
6         -0.4

With normal speed, we send the output line a series of values where the sample number increments by 1 per output frame.
If we were going slower, say half speed, we should output twice as many values before reaching the same point in the media data. In other words, we need to include, in our output, values that are at the non-existent, intermediate sample frame locations 0.5, 1.5, 2.5, ...
To do this, it turns out that linear interpolation works quite well for audio. It is possible to use a more sophisticated curve fitting algorithm but the increase in fidelity is not considered to be worth the trouble.
So, we end up with a stream as follows (for half speed):
sample    value
0          0.0
0.5        0.15
1          0.3
1.5        0.4
2          0.5
2.5        0.55
3          0.6
etc.

If you want to play back 3/4 speed, then the positions and values used in the output would be this:
sample    value
0          0.0
0.75       0.225
1.5        0.4
2.25       0.525
3          0.6
3.75       0.525
etc.

I code this via a "cursor" that is incremented each sample frame, where the increment amount determines the "speed" of the playback. The cursor points into an array, like an integer index would, but instead, is a float (or double). If there is a fractional part to the cursor's value, the fraction is used to interpolate between sample values pointed to by the integer part and the integer part plus one.
For example, if the cursor was 6.25, and the value of soundData[6] was A and the value of soundData[6+1] was B, the sound value would be:
audioValue = A * 0.75 + B * 0.25

The degree of precision with which you can define your speed increment is quite high. I think Java's floats are considered sufficient for this purpose.
As for keeping a dynamically changing speed increment smooth, I am spreading out the changes to new speeds over a series of 4096 steps (roughly 1/10th of a second, at 44100 fps). Change requests are often asynchronous, e.g., from a GUI, and are spread out over time in a somewhat unpredictable way. The smoothing algorithm should be able to recalculate and update itself with each new speed request.
Following is a link that demonstrates both strategies, where a sound's playback speed  is altered in real time via a slider control.
SlidersTest.jar
This is a runnable copy of the jar file that also contains the source code, and executes via Java 8. You can also rename the file SlidersTest.zip and then drill in to view the source code, in context.
But links to the source files can also be navigated to directly in the two following sections of a page I posted for this code I recently wrote and made open source:
see AudioCue.java
see SlidersTest.java
AudioCue.java is a long file. The relevant parts are in the inner class at the end of the file: class AudioCuePlayer, and for the smoothing algorithm, check the setter method setSpeed which is about 3/4's of the way down. Sorry I don't have line numbers.


text:
Q: iron meteor cannot find simpl-schema I am using iron-meteor for scaffolding meteor crud apps and I am following this tutorial. I have iron meteor running but the problem arises when I install aldeed collections and other packages as follows;
iron add twbs:bootstrap aldeed:collection2 aldeed:autoform aldeed:delete-button momentjs:moment accounts-password ian:accounts-ui-bootstrap-3

I also have;
npm install -g --save simpl-schema
But I get errors when I run
iron run
W20190716-20:45:24.894(2)? (STDERR) WARNING: npm peer requirements (for aldeed:collection2) not installed:
W20190716-20:45:24.894(2)? (STDERR) - simpl-schema@>=0.0.0 not installed
I have tried changing npm directory rights and permissions to ensure that the current user has access to npm packages. I have also tried uninstalling and reinstalling aldeed:collections2 package and simpl-schema but the same error still persists

=> Started proxy.
  => Started MongoDB.                            W20190716-20:45:24.686(2)? (STDERR) Note: you are using a
  pure-JavaScript implementation of bcrypt. W20190716-20:45:24.714(2)?
  (STDERR) While this implementation will work correctly, it is known to
  be W20190716-20:45:24.714(2)? (STDERR) approximately three times
  slower than the native implementation. W20190716-20:45:24.719(2)?
  (STDERR) In order to use the native implementation instead, run
  W20190716-20:45:24.720(2)? (STDERR)  W20190716-20:45:24.720(2)?
  (STDERR)   meteor npm install --save bcrypt W20190716-20:45:24.720(2)?
  (STDERR)  W20190716-20:45:24.720(2)? (STDERR) in the root directory of
  your application. W20190716-20:45:24.894(2)? (STDERR) WARNING: npm
  peer requirements (for aldeed:collection2) not installed:
  W20190716-20:45:24.894(2)? (STDERR)  - simpl-schema@>=0.0.0 not
  installed. W20190716-20:45:24.894(2)? (STDERR)
  W20190716-20:45:24.895(2)? (STDERR) Read more about installing npm
  peer dependencies: W20190716-20:45:24.895(2)? (STDERR)
http://guide.meteor.com/using-packages.html#peer-npm-dependencies
  W20190716-20:45:24.895(2)? (STDERR)  W20190716-20:45:24.937(2)?
  (STDERR)
  /home/kingzuru/.meteor/packages/meteor-tool/.1.8.1.1ehy8qi.j0unh++os.linux.x86_64+web.browser+web.browser.legacy+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:280
  W20190716-20:45:24.940(2)? (STDERR)                       throw(ex);
  W20190716-20:45:24.941(2)? (STDERR)                       ^ W20190716-20:45:24.941(2)?
  (STDERR)  W20190716-20:45:24.941(2)? (STDERR) Error: Cannot find
  module 'simpl-schema' W20190716-20:45:24.942(2)? (STDERR)     at
  makeMissingError (packages/modules-runtime.js:222:12)
  W20190716-20:45:24.942(2)? (STDERR)     at Module.require
  (packages/modules-runtime.js:241:17) W20190716-20:45:24.942(2)?
  (STDERR)     at require (packages/modules-runtime.js:258:21)
  W20190716-20:45:24.943(2)? (STDERR)     at collection2.js
  (packages/aldeed:collection2/collection2.js:13:22)
  W20190716-20:45:24.943(2)? (STDERR)     at fileEvaluate
  (packages/modules-runtime.js:336:7) W20190716-20:45:24.943(2)?
  (STDERR)     at Module.require (packages/modules-runtime.js:238:14)
  W20190716-20:45:24.944(2)? (STDERR)     at require
  (packages/modules-runtime.js:258:21) W20190716-20:45:24.944(2)?
  (STDERR)     at
  /var/www/testapp/app/.meteor/local/build/programs/server/packages/aldeed_collection2.js:895:15
  W20190716-20:45:24.944(2)? (STDERR)     at
  /var/www/testapp/app/.meteor/local/build/programs/server/packages/aldeed_collection2.js:902:3
  W20190716-20:45:24.945(2)? (STDERR)     at
  /var/www/testapp/app/.meteor/local/build/programs/server/boot.js:419:36
  W20190716-20:45:24.945(2)? (STDERR)     at Array.forEach ()
  W20190716-20:45:24.945(2)? (STDERR)     at
  /var/www/testapp/app/.meteor/local/build/programs/server/boot.js:228:19
  W20190716-20:45:24.945(2)? (STDERR)     at
  /var/www/testapp/app/.meteor/local/build/programs/server/boot.js:479:5
  W20190716-20:45:24.945(2)? (STDERR)     at Function.run
  (/var/www/testapp/app/.meteor/local/build/programs/server/profile.js:510:12)
  W20190716-20:45:24.946(2)? (STDERR)     at
  /var/www/testapp/app/.meteor/local/build/programs/server/boot.js:478:11
  => Exited with code: 1

A: The command npm install -g --save simpl-schema installs Simple Schema on a global level (-g option means install globally) and thus it won't be usable on your local project.
You should rather do meteor npm install --save simpl-schema inside your project.
Note, that aldeed:simple-schema is deprecated, as well as aldeed:collection2-core (which is why you should use aldeed:collection2).


text:
Q: Oracle apex create read only breadcrumb entry I want to create a breadcrumb when one of the entries is shown but not clickable.
for example:
page1 \ page2 \ page3 \ page4

page1 and page3 are clickable but page2 is not (page4 is the current page).
Defining the breadcrumb entry's target as "No target" keeps it clickable (redirect to the same page)

so this solution not good enough for me.
Apex version is 19.1.
Thanks.

A: On the page where you have the breadcrumbs rendered, you could remove the href using jquery.
In the page attributes > execute when page loads, put:
$('a.t-Breadcrumb-label').filter(function(){
    return this.innerHTML == 'page2';
}).removeAttr("href");


text:
Q: Attachment in a Custom List Form at different position I am trying to create a custom form having 5 buttons on it at different sections. on click of button i have to attach "n" number of document, and show at the same section. In the same way have to do for reset of the section.
Anyone has done such thing earlier. If so, pl. suggest the solution.


text:
Q: Can we print some div of a page? I want to create a print button so I can print my page content, except the print preview is not what I would like to print at all.
I would like to print only this visualization

When I click the print button it also shows me the sidebar.

Do you think it is possible to retrieve some div? Because I don't know how to do this.

Portfolio Securities

                  <button type="button" class="btn btn-secondary mb-2" (click)="printPage()">Print</button>

                  Amount

                  Denomination

                  Dev

                  Course

                  Average

                  Var en %

                  Interest

                  Estimate

                  Weight

                  Variation

                  Order

               <ng-container *ngFor="let instrument of instruments">
                  <ng-container *ngIf="instrument.TYPEVALUE === 11 || instrument.TYPEVALUE === 21 || instrument.TYPEVALUE === 31">

                         {{ instrument.ASSETCATLABEL }}
                         {{ instrument.AMOUNT | FormatNum:'1.2-2' }}%
                         {{ instrument.PERCENTAGE | FormatNum:'1.2-2' }} %

                  </ng-container>
                  <ng-container *ngFor="let item of instrument.ELEMENT">

                        {{ item.QUANTITY | FormatNum:'1.2-2' }}
                         {{ item.LABEL }}
                        {{ item.CURRENCYVALO }}
                        {{ item.LASTPRICE | FormatNum:'1.2-2' }}
                        {{ item.AVERAGEDPRICE | FormatNum:'1.2-2' }}

                           = 0 ? 'positive-arrow' : 'negative-arrow']">

                         {{ item.PRICEVARIATION | mathAbs | FormatNum:'1.2-2' }} %
                        {{ item.ACCRUEDINTERESTS | FormatNum:'1.2-2' }}
                        {{ item.VALORIZATION | FormatNum:'1.2-2' }}
                        {{ item.PERCENTAGE | FormatNum:'1.2-2' }} %

                           {{ item.DIFFEREUR | FormatNum: "1.2-2" }} {{ item.CURRENCYVALO   }}

                           {{ item.DIFFEREUR | FormatNum: "1.2-2"}} EUR

                           <button type="button" *ngIf="hasAccess$ | async" [routerLink]="['/orders/newOrder/' + item.SVM]" class="btn btn-success outline">Sale</button>

                  </ng-container>
                  <ng-container *ngIf="instrument.TYPEVALUE === 92">

                         {{ instrument.ASSETCATLABEL }}

                        {{ item.QUANTITY | FormatNum:'1.2-2' }}

                        Coupon {{ item.COUPONNUMBER }} title {{ item.LABEL }}

                  </ng-container>
               </ng-container>

My TS file
printPage() {
  window.print();
}

A: In CSS you can target the print mode, and hide anything you don't want on the final result. In a global CSS file :
@media print {
  .hide-on-print {
    display: none;
  }
}


text:
Q: Pagination with graphql and django I am using react(fe), Django (be) and graphql. Currently I send request when I reach bottom of my page to fetch more "posts" to my infinite scrolling feed.
In django-graphene, this would work like
Return Post.objects.all() [offset, offset+limit]. But what should I do if for example, my return statement weren't as easy as just fetching all posts? What if I need to return the posts in a sorted way that they aren't already in the DB? Right now, I am doing it like
Return custom_sort(Post.objects.all())[offset, offset+limit]. Still working, but I need to sort them on every request (I think, if Django isn't cashing it). How would one do this so I only need to sort them once, and then save those values for say a minute so I don't need to sort them every time I request?


text:
Q: Hypergraph with networkx is anyone familiar with networkx?
I try to get a hypergraph, where i want to set the Hyperedges as other colored nodes (size dependent on their value) out of an list. And i want to set the Nodes out of an other list.
The documentation and examples on the networkx website are really spare, but i am sure it is possible.
I started with this example, but this is only an example for different edges. Can someone tell me how i can put up two different set of nodes with different color/size in networkx?

A: Did you want something like this use nx.draw_networkx_nodes using nodelist parameter:
# Author: Aric Hagberg (hagberg@lanl.gov)
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()

G.add_edge('a', 'b', weight=0.6)
G.add_edge('a', 'c', weight=0.2)
G.add_edge('c', 'd', weight=0.1)
G.add_edge('c', 'e', weight=0.7)
G.add_edge('c', 'f', weight=0.9)
G.add_edge('a', 'd', weight=0.3)

elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5]

pos = nx.spring_layout(G)  # positions for all nodes

# nodes
nx.draw_networkx_nodes(G, pos, node_size=700, nodelist=['e','f','b'])
nx.draw_networkx_nodes(G, pos, node_size=1400, nodelist=['c','a','d'], node_color='blue')

# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge,
                       width=6)
nx.draw_networkx_edges(G, pos, edgelist=esmall,
                       width=6, alpha=0.5, edge_color='b', style='dashed')

# labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')

plt.axis('off')
plt.show()

Output:

And changing labels and shapes too:
# Author: Aric Hagberg (hagberg@lanl.gov)
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()

G.add_edge('a', 'b', weight=0.6)
G.add_edge('a', 'c', weight=0.2)
G.add_edge('c', 'd', weight=0.1)
G.add_edge('c', 'e', weight=0.7)
G.add_edge('c', 'f', weight=0.9)
G.add_edge('a', 'd', weight=0.3)

elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5]

pos = nx.spring_layout(G)  # positions for all nodes

# nodes
nx.draw_networkx_nodes(G, pos, node_size=700, nodelist=['e','f','b'])
nx.draw_networkx_nodes(G, pos, node_size=1400, nodelist=['c','a','d'],
                       node_color='blue', node_shape='^')

# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge,
                       width=6)
nx.draw_networkx_edges(G, pos, edgelist=esmall,
                       width=6, alpha=0.5, edge_color='b', style='dashed')

# labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif',
                        labels={'f':'f','e':'e','b':'b'})
nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif', font_color='white',
                        labels={'d':'d','a':'a','c':'c'})

plt.axis('off')
plt.show()

Output:


text:
Q: Build JSON from 2 aggregated columns in Postgres using a Postgres-Db as source for json-documents, I need to convert two columns from a table to an JSON-object.
So I have the columns "color_id", "language" and "name" in a table of colors:

    color_id |   language  | name
    1        |      "de"   |  "blau"
    1        |      "en"   |  "blue"
    1        |      "fr"   |  "bleu"

And I'd like to produce a JSON-object like:

    {
      "de": "blau",
      "fr": "bleu",
      "en": "blue"
    }

I started with

    SELECT
      array_to_json(array_agg((language::text, name::text))),
      color_id
    FROM colors
    GROUP BY color_id;

which unfortunately produced

    array to json                 | color_id
    "[{"f1":"de","f2":"blau"}     |
      , {"f1":"en","f2":"blue"}   | 1
      , {"f1":"fr","f2":"bleu"}]" |

I'd think it would be simple - more or less -, but found myself at a dead end of misleading results and syntax errors.
Kind regards, Dominik

A: Use jsonb_object_agg():
with data(color_id, language, name) as (
values
    (1, 'de', 'blau'),
    (1, 'en', 'blue'),
    (1, 'fr', 'bleu')
)
select color_id, jsonb_object_agg(language, name)
from data
group by 1;

 color_id |              jsonb_object_agg
----------+--------------------------------------------
        1 | {"de": "blau", "en": "blue", "fr": "bleu"}
(1 row)

The function jsonb_object_agg() was introduced in Postgres 9.5.
In Postgres 9.4 use json_object_agg() instead.
In Postgres 9.3 you have to construct the result using string functions:
select
    color_id,
    format('{%s}', string_agg(format('"%s": "%s"', language, name), ', '))::json
from data
group by 1;

A: For key value pair and Proper JSON data this can be used
with data(color_id, language, name) as (
values
    (1, 'de', 'blau'),
    (1, 'en', 'blue'),
    (1, 'fr', 'bleu')
)
    SELECT color_id,
     json_agg((SELECT x FROM (SELECT language, name) AS x)) AS json_data
FROM data
group by "data".color_id;


text:
Q: What are the London and Chicago schools of TDD? I've been hearing about the London style vs. Chicago style (sometimes called Detroit style) of Test Driven Development (TDD).
Workshop of Utah Extreme Programming User's Group:

Interaction-style TDD is also called mockist-style, or London-style after London's Extreme Tuesday club where it became popular. It is usually contrasted with Detroit-style or classic
  TDD which is more state-based.

Jason Gorman's workshop:

The workshop covers both the Chicago school of TDD (state-based
  behaviour testing and triangulation), and the London school, which
  focuses more on interaction testing, mocking and end-to-end TDD, with
  particular emphasis on Responsibility-Driven Design and the Tell,
  Don't Ask approach to OO recently re-popularized by Steve Freeman's
  and Nat Pryce's excellent Growing Object-Oriented Software Guided By
  Tests book.

The post Classic TDD or "London School"? by Jason Gorman was helpful, but his examples confused me, because he uses two different examples instead of one example with both approaches. What are the differences? When do you use each style?

A: The article Mocks Aren't Stubs, by Martin Fowler is a good introduction to the topic.
Depending on the design style you choose (and the design principles upon which you build your programs), there are at least two ways of seeing an object:

*

*As a unit that performs computations based on inputs. As a result of this computation the object can return a value or change its state.

*As an active element that communicates with other elements in the system by message passing.

In the first case, you are interested in what comes out of the processing or in which state the object is left after that processing. This is where methods such as assertEquals() enter the picture. In this case, it does not matter much what other objects were involved in the processing, which methods were called, etc. This kind of verification is called state-based verification and is the "classical" style.
In the second case, since most objects do not even return any result (e.g. void methods in Java), you are more interested in how the objects communicate with each other and if they pass the right messages under the circumstances imposed by the test. These interactions are usually verified with the aid of mock frameworks. This kind of verification is called behavior-based or interaction-based verification. One of its implications is the technique called Behavior Driven Development, by which you develop a class assuming that its collaborators already exist (even though they might not exist yet), so you can code against their interfaces.
Note that this is not an either/or choice. You can have a design style that mix both approaches to get the best out of each.

A: Suppose you have class called "ledger" a method called "calculate" that uses a "Calculator" to do different types of calculations depending on the arguments passed to "calculate", for example "multiply(x, y)" or "subtract(x, y)".
Now, suppose you want to test what happens when you call ledger.calculate("5 * 7").
The London/Interaction school would have you assert whether Calculator.multiply(5,7) got called.  The various mocking frameworks are useful for this, and it can be very useful if, for example, you don't have ownership of the "Calculator" object (suppose it is an external component or service that you cannot test directly, but you do know you have to call in a particular way).
The Chicago/State school would have you assert whether the result is 35. The jUnit/nUnit frameworks are generally geared towards doing this.
Both are valid and important tests.


text:
Q: Start activity on boot I'd like to start my app just after the phone boot. Apparently the app is started after the boot but it immediately crashes (just to be clear the app normally works fine). I have already read and tried different solutions (link1, link2) and actually the same code works fine with another app I was developing. Here's the code:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetoothx10y"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="6"
        android:targetSdkVersion="15" />

    <uses-feature android:name="android.hardware.usb.accessory"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <receiver
            android:name=".StartMyActivityAtBootReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
               <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"/>
            </intent-filter>

            <meta-data
                android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
                android:resource="@xml/accessory_filter">
            </meta-data>

        </activity>

        <activity android:name=".DeviceListActivity"
              android:label="@string/app_name"
              android:theme="@android:style/Theme.Dialog"
              android:screenOrientation="landscape" />
    </application>

</manifest>

StartMyActivityAtBootReceiver.java:
    public class StartMyActivityAtBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {

                Intent myStarterIntent = new Intent(context, MainActivity.class);
                myStarterIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(myStarterIntent);

            }
    }
}

Could it be related the fact that I'm using the a lot of user permissions?

A: <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".StartMyActivityAtBootReceiver"
                      android:enabled="true"
                      android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED"/>
                    <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
                </intent-filter>
            </receiver>

A: do it like this in if condition
 if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))

A: Try this:

1] In AndroidManifest.xml file:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

 <application
 ...
    <receiver
        android:name=".StartMyActivityAtBootReceiver"
        android:enabled="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
 </application>

2] Inside BroadcastReciever class with StartMyActivityAtBootReceiver as class name.

@Override
public void onReceive(Context context, Intent intent) {

    Intent i = new Intent(context, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);

}

This worked for me. The difference in code is as follows:

*

*android:permission="android.permission.RECEIVE_BOOT_COMPLETED" inside receiver.

*included "category android:name="android.intent.category.DEFAULT" " inside intent filter.

*I am not checking the intent in onRecieve, as i know that code will be executed only if its true

A: I managed to solve the problem. Inside the OnCreate() I had this code (related to the USB communication) which was causing the crash:
    act_string = getIntent().getAction();
    if( -1 != act_string.indexOf("android.intent.action.MAIN")){
        restorePreference();
    }
    else if( -1 != act_string.indexOf("android.hardware.usb.action.USB_ACCESSORY_ATTACHED")){
        cleanPreference();
    }

Deleting this code solved the start after boot issue.

A: in place of
 <action android:name="android.intent.action.BOOT_COMPLETED" />

add also this
<action android:name="android.intent.action.QUICKBOOT_POWERON" />

some devices like HTC don't catch BOOT_COMPLETED

A: I would like to add the whole manifest file which workedv for me on oppo neo 5.
And,even take care that some phone requires special access to achieve boot start or other special permissions.So,don't forgot to allow the accesses to your app!!.
Here's the code -
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javacodegeeks.androidserviceonbootexample"
    android:installLocation="internalOnly">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="SilversithService"
        android:theme="@style/AppTheme">
        <receiver
            android:name="com.javacodegeeks.androidserviceonbootexample.BroadcastReceiverOnBootComplete">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.REBOOT"/>
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>
        <service android:name="com.javacodegeeks.androidserviceonbootexample.AndroidServiceStartOnBoot"
            android:enabled="true"></service>
        <activity
            android:name="com.javacodegeeks.androidserviceonbootexample.MainActivity"
            android:label="SilversithService">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

A:    <receiver
        android:name="tv.usa.rytek.services.BootReceiver"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

public class BootReceiver extends BroadcastReceiver {
SharedPreferenceHelper sharedPreferenceHelper;
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
    sharedPreferenceHelper = new SharedPreferenceHelper(context);
    Log.e(TAG,""+intent.getAction());
    if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
        if(sharedPreferenceHelper.getSharedPreferenceAutoPosition()==1){
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }
}

}


text:
Q: Dynamically adding SVG to DOM I have looked all over this site and the internet and I cant seem to find a way that I understand to add an svg to the dom using javascript. Can anyone help me please? The svg I want to add it below.
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="450px" height="450px" viewBox="0 0 450 450" style="enable-background:new 0 0 450 450;" xml:space="preserve">

    <line class="path" fill="none" stroke="#000000" x1="0" y1="154.5" x2="450" y2="154.5"/>
    <line class="path" fill="none" stroke="#000000" x1="450" y1="304.5" x2="0" y2="304.5"/>
    <line class="path" fill="none" stroke="#000000" x1="145.5" y1="0" x2="145.5" y2="450"/>
    <line class="path" fill="none" stroke="#000000" x1="295.5" y1="450" x2="295.5" y2="0"/>
</svg>

A: You can work with SVG elements like with a simple DOM structure.
For example, you can edit it using .html() jQuery function:

$("#mySvgContainer").html("<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" width=\"450px\" height=\"450px\" viewBox=\"0 0 450 450\" style=\"enable-background:new 0 0 450 450;\" xml:space=\"preserve\"><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=\"0\" y1=\"154.5\" x2=\"450\" y2=\"154.5\"/><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=450\" y1=\"304.5\" x2=\"0\" y2=\"304.5\"/><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=\"145.5\" y1=\"0\" x2=\"145.5\" y2=\"450\"/><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=\"295.5\" y1=\"450\" x2=\"295.5\" y2=\"0\"/></svg>");

Also, you can dynamically create DOM SVG element and append it like you do it with HTML elements.


text:
Q: Repeating Data after web scraping using python and beautiful soup4 I am trying to scrape data from the Garmin site for golf. I would want to get the name of the golf course and the address but I after running the script. I have noticed that my codes just repeats the first page data over and over again. I also noticed that the page numbers on the website do not start at 1 but at 10 for the second page. How do I go about extracting data from this website and getting all and instead of a repeat of just the first page.
import csv
import codecs
import requests
from bs4 import BeautifulSoup

courses_list= []
for i in range(10):
    url = "http://sites.garmin.com/clsearch/courses?browse=1&country=US&lang=en&per_page={}".format(i)
    r = requests.get(url)

    soup = BeautifulSoup(r.content)

    g_data2=soup.find_all("div",{"class":"result"})

    for item in g_data2:
     try:
        name= item.contents[3].find_all("div",{"class":"name"})[0].text
        print name
     except:
        name=''
    try:
        address= item.contents[3].find_all("div",{"class":"location"})[0].text
    except:
        address=''

    course=[name,address]
    courses_list.append(course)

with open ('G_Final.csv','a') as file:
    writer=csv.writer(file)
    for row in courses_list:
        writer.writerow([s.encode("utf-8") for s in row])

A: You discovered the problem.
Then change
url = "http://...?browse=1&country=US&lang=en&per_page={}".format(i)

to
url = "http://...?browse=1&country=US&lang=en&per_page={}".format(i*20)


text:
Q: X,Y are independent exponentially distributed then what is the distribution of X/(X+Y) Been crushing my head with this exercise. I know how to get the distribution of a ratio of exponential variables and of the sum of them, but i can't piece everything together.
The exercise goes as this:
If X,Y are independent exponentially distributed with beta = 1 (parameter of the exponential distribution = 1) then what is the distribution of X/(X+Y)
Any ideas?
Thanks a lot.

A: Obviously $X/(X+Y)$ is between $0$ and $1$.  Let (lower-case) $w$ be a number between $0$ and $1$.
$$
\frac{X}{X+Y} \le w \text{ if and only if } (1-w)X \le wY.
$$
We will find this probability.
The conditional probability that $Y\ge\dfrac{(1-w)}{w}X$, given the value of $X$, is
$$
e^{-(1-w)X/w}.
$$
The probability we seek is then the expected value of that:
\begin{align}
\operatorname{E} e^{-(1-w)X/w} & = \int_0^\infty e^{-(1-w)x/w} \Big(e^{-x}\,dx\Big) \\[10pt]
& = \int_0^\infty e^{-x/w} \, dx \\[10pt]
& = w.
\end{align}
In other words, this random variable is uniformly distributed between $0$ and $1$.
Second method:  The equality $Y=\frac{1-w}{w}X$ is a straight line through the $(X,Y)$-plane, passing through $(0,0)$ and having positive slope.
We can let $y$ go from $0$ to $\infty$ and then for any fixed value of $y$, let $x$ go from $0$ to $\frac{w}{1-w}y$
\begin{align}
& \int_0^\infty \left(\int_0^{wy/(1-w)} e^{-y} e^{-x} \,dx \right) \, dy \\[10pt]
= {} & \int_0^\infty e^{-y}\left(1-e^{-wy/(1-w)}\right) \, dy \\[10pt]
= {} & \int_0^\infty e^{-y} - e^{-y/(1-w)} \, dy  \\[10pt]
= {} & 1 - (1-w) \\[10pt]
= {} & w.
\end{align}

A: Another way is to do it is to perform the following transformation. Let \begin{align*} U&=\frac{X}{X+Y} \\ V&=X+Y.\end{align*} Then \begin{align*} x(u,v)&=uv\\y(u,v)&=v-uv. \end{align*}
The determinant of the Jacobian of the transformation is
$$\left| \begin{matrix} v & u\\ -v & 1-u \end{matrix} \right|=v.
$$
Then, the joint pdf of $U$ and $V$ is
$$f_{U,V}(u,v)=f_{X,Y}(uv,v-uv)|v|=ve^{-v}, \hspace{2mm} \text{for } v\geq0, 0\leq u\leq1.
$$
Finally, "integrate out" the $v$ to obtain the marginal pdf of $U=X/(X+Y)$ as
$$f_U(u)=\int_0^{\infty}f_{U,V}(u,v)dv=\int_0^{\infty}ve^{-v}dv=1, \hspace{2mm} \text{for } 0\leq u\leq 1.$$
Hence, as Michael Hardy showed, $X/(X+Y)$ is uniformly distributed on $[0,1].$

A: In other words, for each $a > 0$, you want to compute $P\left(\frac{X}{X+Y} < a \right)$.
Outline: Find the joint density of $(X,Y)$, and integrate it over the subset of the plane $\left\{ (x,y) : \frac{x}{x+y} < a \right\}$.


text:
Q: Android: MVVM - RecyclerView dynamic data load My case is as following: Supposing that I have an app where I show a list of users, and their profile pics (similar to whatsapp).
First I load the list of users, and observer the LiveData of users. The problem is, that the url of their profile pic, doesn't come with the getUsersList API. Instead, I have to do another network call on fly (while rendering the list), in order to retrieve the profile pic for a given User, let's say getUserPicByUserId.
Using, MVVM design pattern, I did this implementation:

*

*In Fragment class I load the list of Users from getUsersList API. For each user item, profilePicUrl is Null.

*In Adapter/ViewHolder class I check if profilePicUrl is null. If so, using a listener(MyAdapterListener), I do a call to getUserPic API for the given User.

*When the response of getUserPic API is ready, I update the user item in ViewHolder (see the lambda function onUrlLoaded: (url: String) -> Unit) and load the image.
Problems: This approach is causing that all items get the same image, because the observer of userProfilePicLiveData is always listening for each user item. And every item will load the last retrieven url.
Adding:
viewModel.userProfilePicLiveData.removeObservers(lifecycleOwner) after callback onUrlLoaded(profilePicUrl) in Fragment will not work either.
I spent some time on this problem, but cannot find a solution.
What would be the appropriate approach for this scenario? How to perform a network call when rendering each RecyclerView item, and send the result back to the Adapter to update the view?
Here there is the simplified code of what I have done so far:
Model User
data class User(
  val id: String,
  val name: String,
  val profilePicUrl: String? = null, // By default is null
  ...
)

profilePicUrl doesn't come with getUsersList API, so by default is Null.
Model UserProfilePic:
data class UserProfilePic(
  val url: String
  ...
)

Implementation example of ViewModel class:
class MyViewModel: ViewModel() {
  val usersListLiveData = LiveData<List<User>>
  val userProfilePicLiveData = LiveData<UserProfilePic>

  fun loadUsers() {
    // Network call...
    usersListLiveData.value = usersList
  }

  fun loadProfilePicByUserId(userId: String) {
    // Network call...
    userProfilePicLiveData.value = userProfilePic
  }

}

Adapter class:
class RecyclerViewAdapter(val usersList: List<User>): RecyclerView.Adapter<MyViewHolder>() {

interface MyAdapterListener {
        fun onLoadProfilePicUrl(
            user: User,
            onUrlLoaded: (url: String) -> Unit
        )
    }

class HomeVenueViewHolder(
 val listener: MyAdapterListener
) : RecyclerView.ViewHolder() {
      fun bind(user: User) {
        // Fill view list item ...

        if (user.profilePicUrl is Null ) {
          listener.onLoadProfilePicUrl(user) { url ->
            user.profilePicUrl = url

            // Load Image From the Url
          }
        } else {
          // Valid url: Load image
        }
      }
    }
}

Fragment class:
class MyFragment: Fragment(), MyAdapterListener {

  val viewModel: MyViewModel

  viewModel.usersListLiveData.observe(viewLifecycleOwner, { usersList ->
    // Setup adapter and show list
  })

  fun loadUsers() {
    viewModel.loadUsers()
  }

  override fun onLoadProfilePicUrl(
      user: User,
      onUrlLoaded: (url: String) -> Unit
  ) {
    viewModel.loadProfilePicByUserId(user.id)

    viewModel.userProfilePicLiveData.observe(viewLifecycleOwner, { profilePicUrl ->
      // This is a callback to Adapter
       onUrlLoaded(profilePicUrl)
    })
  }

}

A: Your ViewModel should update the list stored in usersListLiveData every time loadProfilePicByUserId(userId: String) pulls a new profile image from the API. Your Fragment should observe usersListLiveData and notify the adapter when the data changes (using adapter.notifyDataSetChanged() or an equivalent).
One caveat is that User is a complex object, and usersListLiveData is a list of these complex objects. You can't get away with just changing the one property profilePicUrl in the relevant list item. You need to call something like usersListLiveData.value = newUserListor else the observer of the MutableLiveData won't fire. Observers won't fire when you just change a single property of a complex object. You need to call setValue() or postValue().


text:
Q: Does NSUserDefaults handle automatic termination safely? Apple's documentation says

NSUserDefaults temporarily disables sudden termination to prevent process killing between the time at which a default has been set and the time at which the preferences file including that default has been written to disk.

Does it also do this for automatic termination, or must I synchronize manually when I suspect automatic termination may occur (e.g. when the application gets hidden)?

A: It doesn't need to do anything specifically for automatic termination. The reason why is that automatic termination doesn't behave differently than ⌘Q (i.e. -[NSApp terminate:] is called if sudden termination is not enabled), and NSUserDefaults already handles ⌘Q just fine.
Apple's 2011 WWDC presentation on automatic termination (registration required, starting around 34:00) has more information.


text:
Q: WhatsApp Web like Content Editable Div I am looking for a way to have a WhatsApp Web like content editable div which expands upwards when pressing SHIFT+ENTER and also minimizes the div above it accordingly (See purple area in the attached screenshots).
What would be the best way to implement this?
Thanks a lot.
Edit: I use vuejs along with vuetify.

A: I am using variables in css to clac the height of .converstion div :https://www.w3schools.com/css/css3_variables.asp
I am using Jquery but you can do it using Vue JS
See JSFiddle:https://jsfiddle.net/8feswyau/

$('textarea').on({input: function(){
    var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
    $(this).css({'height':totalHeight});
    $('.conversation').get(0).style.setProperty("--number",totalHeight+'px')
}
});
 textarea{
 width:243px;

 }
.warp{
height:300px;
width:250px;
}
.conversation{
 height: calc(100% - var(--number));
    position: relative;
    background: #efe7dd url(https://cloud.githubusercontent.com/assets/398893/15136779/4e765036-1639-11e6-9201-67e728e86f39.jpg) repeat;
 }

<textarea></textarea>

A: This can be done pretty easily with <v-text-field textarea auto-grow> and some basic flexbox: https://codepen.io/anon/pen/jKaVZO

A: I recently had to make a floating button to send messages to a certain number using the whatsapp api. I created a chat box that simulates whatsapp chat.
Basically it was made with vue and the incredible components of vuetify
Add quick whatsapp floating button with message box to connect with your users. If you click on that button, the chat box will open with prefilled message.
See Codepen
JS
new Vue({
  el: '#app',
  data: () => ({
    fab: false,
    fav: true,
    menu: false,
    message: false,
    hints: true,
    phone: '5521997642382',
    text: "",
    apilink: ""
  }),
  watch: {
        text(val) {
            this.apilink = 'http://';
      this.apilink += this.isMobile() ? 'api' : 'web';
      this.apilink += '.whatsapp.com/send?phone=' + this.phone + '&text=' + encodeURI(this.text);
        }
    },
  created: function () {
    this.apilink = 'http://';
    this.apilink += this.isMobile() ? 'api' : 'web';
    this.apilink += '.whatsapp.com/send?phone=' + this.phone + '&text=' + encodeURI("Hello!");
  },
    methods: {
    isMobile() {
      var check = false;
      (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
      return check;
    }
  }
})

CSS
.my-input.v-input .v-input__slot {
  border-radius: 100px;
}
.chat-background {
  background-color: #ECE5DD !important
}
.chat-header {
  background-color: #075E54 !important
}
.chip-chat {
  background-color: #DCF8C6 !important
}

html

  <v-app id="inspire">

      <v-menu
        min-width = 300
        top
        v-model="menu"
        :close-on-click="false"
        :close-on-content-click="false"
        :nudge-top="60"
        offset-x
      >
        <template v-slot:activator="{ on }">
          <v-fab-transition>
            <v-btn
              v-model="fab"
              v-on="on"
              color='green darken-1'
              @click="fab = !fab; menu = false"
              dark
              fixed
              bottom
              right
              fab
            >
              <v-icon>comment</v-icon>
              <v-icon>close</v-icon>
            </v-btn>
          </v-fab-transition>
        </template>
        <v-card>
          <v-list dark class="chat-header">
            <v-list-tile>
              <v-list-tile-content>
                <v-list-tile-title>Contact me</v-list-tile-title>
              </v-list-tile-content>
              <v-list-tile-action>
                <v-btn
                  icon
                  @click="fab = !fab; menu = false"
                >
                  <v-icon>cancel</v-icon>
                </v-btn>
              </v-list-tile-action>
            </v-list-tile>
          </v-list>
          <v-divider></v-divider>
          <v-container class="chat-background">
            <v-layout row wrap >
              <v-flex class="text-xs-right" xs12 mb-4>
                <v-chip class="chip-chat ">
                  Hello, how can we help you? <v-icon right>done_all</v-icon>
                </v-chip>
              </v-flex>
              <v-flex xs10>
                <v-text-field
                  single-line
                  color="teal"
                  class="my-input"
                  v-model="text"
                  outline
                ></v-text-field>
              </v-flex>
              <v-flex xs2>
                <v-btn
                  large
                  class="teal--text"
                  icon
                  @click="fab = !fab; menu = false"
                  :href="apilink"
                  target="_blank"
                >
                  <v-icon large>send</v-icon>
                </v-btn>
               </v-flex>
             </v-layout>
          </v-container>
        </v-card>
      </v-menu>

  </v-app>

Image example


text:
Q: Comparing dataframes to Rows in Excel [Someone suggested that this is a duplicate of Pandas Merging 101.  I disagree.  That page talks only about merging two existing pandas.  It does not explain how to do a comparison between excel and an existing panda.  Even if i did a join with two dataframes, it appears that that would require even more work. I was trying to find a way to reduce how much code I need to write.]
i'm extremely new to Pandas and Dataframes, so i'm hoping I could get some suggestions on how to improve a script I wrote.
I'm trying to write a program that will find rows in a dataframe which correspond to rows on an excel sheet.  The rows in the dataframe won't be in order with the rows in excel, and in many cases may not even exist.  The important thing is that the values in the appropriate columns match.  Once these matches are identified, I want to then add only the matching rows in the dataframe to the excel sheet.
I do have a script that works, but its not pretty, and I know there has to be a better way to do this.
Here is an example of the code I wrote with the corresponding information.  Any suggestions on how to make this better would be appreciated.
import pandas as pd
import openpyxl
from openpyxl import load_workbook

wb =load_workbook("test.xlsx")
ws = wb["testsheet"]

data = {'ColA':['BA', 'AG', 'BC', 'AS', 'BW', 'AA'],
        'ColB':['BA', 'AH', 'BC', 'AS', 'BW', 'AB'],
        'ColC':['BA', 'AI', 'BC', 'AS', 'BW', 'AC']}

df = pd.DataFrame(data)

row_count = len(ws['A'])
for i in range(2, row_count +1):
    for k in range(len(df)):
        if ((ws.cell(i,1).value == df.iloc[k]['ColA']) and
            (ws.cell(i,2).value == df.iloc[k]['ColB']) and
            (ws.cell(i,3).value == df.iloc[k]['ColC'])):
            for j in range(0,3):
                ws.cell(i, j + 5).value = df.iloc[k][j]

wb.save("test.xlsx")

Here's the excel sheet "testsheet":

A: *

*Similar to how you checked the length of rows to see how many iterations you need to do... you could also check the length of the columns len(df.columns) to make this script more generalizable and shorter.

*Also, you could access 'ColA' by column number rather than by an explicit string.


text:
Q: How to embebed javafx 2.1 in an installation package I need to distribute a javafx 2.1 application but the client doesn't want to be asked if he wants to install javafx 2.1. It should be automatically installed. Does someone know how to wrap it in a dmg and in an exe package??
Thank you very much in advance.

A: There is a tutorial here: http://fxexperience.com/2012/03/packaging-javafx-applications-as-native/
and there (although for 2.2): https://blogs.oracle.com/talkingjavadeployment/entry/native_packaging_for_javafx

A: Finally I got it !!!!
I'm going to explain how I got it from my perspective. Sorry if it sounds a little bit dummy but I'm not used to build desktop applications and with a new technology as javafx is even more difficult for me.

*

*Download the latest version of the jdk (in this case the 7.0 one).

*Follow the steps from the tutorial and include your .jar and the jfxrt.jar

*As a main class I set com.javafx.main.Main

*Create the application and now, the most important part:

*Once the application has been created, open it (right click on the app and "show package content". Go to the folder: Content/Resources/Java.

*Do the same operation with the vm: go to /Java/JavaVirtualMachines and right click on the 1.7.0.jdk to open the Contents folder.

*Copy ALL the .jar and .dylib from the jdk to the java resources in your application

*Run the application and it will work :)


text:
Q: CefSharp Chromium 43 Our Chromium log files are riddled with warnings like this:

[1007/095721:WARNING:resource_bundle.cc(483)] locale resources are not loaded
  [1007/095721:WARNING:resource_bundle.cc(483)] locale resources are not loaded
  [1007/095730:WARNING:resource_bundle.cc(483)] locale resources are not loaded
  [1007/095730:WARNING:resource_bundle.cc(483)] locale resources are not loaded

Does anybody know exactly what they mean?
I have included the en-GB.pak in the installation directory.

A: The default locale is en-US, have you specified en-GB explicitly? Does adding locales\en-US.pak to your installation directory help?
Is the en-GB.pak file in a locales directory? by default that's where it's looked for.


text:
Q: What does Amazon's MP3 downloader do that can't be done with a normal download? I just bought a new album from Amazon and found out they want me to download and install some custom program just to download some mp3's.  This does not make sense to me from a technical standpoint - I purchase and download albums and songs from other vendors without a problem - usually they will provide a zip file if you get an entire album, or a plain mp3 if you buy one song.  What is so special about Amazon's MP3's that they won't transfer over normal http?

A: This is what Amazon has to say about it

Why is the Amazon MP3 Downloader required to download albums but not songs?
  The Amazon MP3 Downloader queues up all content from an album for download, saves them all to a specific folder on your computer, and can import them automatically to your iTunes or Windows Media Player library. The Amazon MP3 Downloader offers customers the simplest way to download and import multiple content in one easy step.

Amazon mp3 download FAQ


text:
Q: using node.js http with a godaddy site I have been looking around for this question and all of the answers seem to deal with localhost not an actual hosted website. I am trying to recreate socket.io's example chat application on my website. My website is hosted on godaddy and it's public IP address is 107.180.63.56 and since it is an https site I assume the port it is listening on is 443. this is my code to try to recreate the app:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/webmessenger.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});
io.on('connection', function(socket){
    socket.on('chat message', function(msg){
      console.log('message: ' + msg);
    });
  });

http.listen(443,'107.180.63.56', function(){
  console.log('listening on *:443');
});

the app then throws the error:
Error: listen EADDRNOTAVAIL 107.180.63.56:443
which I assume means this IP address or port is not valid. any help on whatI am doing wrong would be appreciated I have tried changing the port and I have obtained the public Ip by pinging my site and just looking on go-daddy. there is also a script in my index.html file which runs the messenger but that should not effect this aspect of the application.
thanks in advance


text:
Q: How can i get Tabbar Item Button's Click event by clicking on TabbarItem button? I have taken UITabbar on that i have used two buttons as TabItem.I want to perform two different Action by clicking on that two button so how can i get particular Action on clicking on particular Tabbar button.

A: You most likely want to take advantage of the UITabBarControllerDelegate, and then handle the didSelectViewController method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController

See here for more details: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITabBarControllerDelegate_Protocol/Reference/Reference.html

A: -(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    if(item.tag==1)
    {
        //your code
    }
    else
    {
       //your code
    }
}

You can use UITabBarDelegate for keeping the track of which button is pressed by assigning the tag or title for title you can use item.title.


text:
Q: return a number between 3 to 5 by get a number between 1 until 10000! I want  to have a math math formulas to do this operation:
A:get a number between 1 to 10000
B:reteun a number between 3.00 until 5 for example 3.89
for greater number return greater number too!
A:500 ---> 3.45
B:9000 ---> 4.70
C:10000 -->5
can anybody help me? I need it for a php algorithm.

A: One solution might be $f(x) = \frac{x}{5000}+3$.


text:
Q: What is the difference between Key-Point, Tie-Point in Photogrammetry? I'm looking into the reports & the Mechanism of UAV Photogrammetry software like Pix4D and AgiSoft.
These two words are mentioned in a lot of support documentation, but they are defined no-where.
From my studies, I remember that tie-points are points marking the same physical feature in two or more images.
What does key-point mean? Is it the same?

A: I found this page in the Pix4D documentation which states:

Keypoints are points of interest (high contrast, interesting texture)
on the images that can be easily recognized. The number of keypoints
depends on:

*

*The size of the images.

*The visual content.

A 14MP image will generate between 5'000 and 50'000 keypoints per
image.

And this page which defines manual and automatic tie points.

An Automatic Tie Points is a 3D point and its corresponding 2D
keypoints that were automatically detected in the images and used to
compute its 3D position.
A Manual Tie Point is a point without 3D
coordinates that is marked by the user in the images. It can be used
to asses and improve the reconstruction accuracy.

A: Key-Points are what is being recognized between the images. In Pix4D for example if there are dominant features in the images, it would be easier for software to recognize and tie them together, which would generally result higher key-points.
Therefore for snow, high-densed vegetation and water, you usually end up with lower key-points because it is difficult for software to tie the images with each other.
Moreover in Pix4D processing options like image scale and calibration method also affects the number of key-points. You can also force Pix4D to limit the number of key-points.


text:
Q: nginx dynamic HTTP/S resolves to https://_ I'm trying to let all traffic for my nginx be redirected to HTTPS, independent of server name. So, any other vhost should be redirected to its HTTPS counterpart.
example.com -> https://example.com
test.com -> https://test.com
...
Yet, instead of using the incoming $server_name or $host (tried both), it keeps redirecting to a plain https://_. Is my config incorrect?
server {
  listen        80 default_server;
  listen        [::]:80 default_server;
  server_name   _;
  return        301 https://$server_name$request_uri;
}

A: Okay, rather silly. If you have previously setup any non-working configuration (e.g. one which will result in the faulty redirect), the browser will remember this redirect without asking the server again (as according to HTTP 301 - permanently moved). So, either clear the browser's data or try with a different one.


text:
Q: Why do I get a typeorder for str and int here? My assignment is:

Write a program to fetch employee  name and the salary.  Calculate the
  Federal tax and state tax based on the following criteria:   If the
  salary is greater than 100000 then calculate the federal tax at 20%
  otherwise calculate the federal tax at 15%   Calculate the state tax
  at 5%   Calculate the net salary of the employee. To calculate the net
  salary, subtract federal and state tax from the gross salary.

My code:
employeename = input("Enter the employee's name:")
grosssalary = input("Enter the employee's gross salary: $")
if grosssalary > 100000:
    federaltax = 0.20
else:
    federaltax = 0.15
statetax = 0.05
netsalary = float(grosssalary) - float(grosssalary * federaltax) - float(grosssalary * statetax)
print (employeename,"'s net salary is $",netsalary)

The output:
Enter the employee's name:Ali
Enter the employee's gross salary: $1000
Traceback (most recent call last):
  File "/home/ubuntu/workspace/Untitled4", line 3, in <module>
    if grosssalary > 100000:
TypeError: unorderable types: str() > int()
Process exited with code: 1

A: input() returns type str in Python 3.x.
So you are doing grosssalary > 100000 which is str > int.
To solve, use:
gross_salary = int(input("Enter the employee's gross salary: $"))

A: In Python 3.x, return value of input() is always of type str, so you are comparing a str object to an int object, which yields a TypeError. You cannot do that, you have to convert it to int or float before comparison.
Try this:
grosssalary = float(input("Enter the employee's gross salary: $"))

A: The error is clear, That you try to check if a string is greater than an int and that is not acceptable.
You should first convert your string into int and then make your check, your code should looks like:
employeename = input("Enter the employee's name:")
grosssalary = input("Enter the employee's gross salary: $")
if int(grosssalary) > 100000:
    federaltax = 0.20
else:
    federaltax = 0.15
statetax = 0.05
netsalary = float(grosssalary) - float(grosssalary * federaltax) - float(grosssalary * statetax)
print (employeename,"'s net salary is $",netsalary)

And you should also check first if the string is an int, To do that your check should looks like:
if grosssalary.isdigit()

    if int(grosssalary) > 100000:

        federaltax = 0.20
    else:
        federaltax = 0.15
else:
    print("bad entry")


text:
Q: Sum similar subsequent cells and put total in another column I have two columns A and B like that

A
B

5
Up

3
Up

2
Up

4
Down

1
Up

3
Up

6
Down

8
Down

And I have the following code that sums the total for each group and put the total at the end of each group. I could do it with loops by this code
Sub Test()
    Dim r As Long, x As Double
    For r = 1 To Cells(Rows.Count, 1).End(xlUp).Row
        If Cells(r, 2).Value = Cells(r + 1, 2).Value Then
            x = x + Cells(r, 1).Value
        Else
            Cells(r, 3).Value = x + Cells(r, 1).Value
            x = 0
        End If
    Next r
End Sub

Is it possible to do such a task using formulas?
I got a solution of doing that by formulas through a helper column, but I am curious if it is possible to do that by one formula?

A: What about using =SUMIF(B:B,"Up",A:A) this will sum all Up.
If you want the sum of every group until Up changes to Down and so on like below

then put the following formula into C2 and pull it down
=IF(B3<>B2,SUM($A$1:A2)-SUM($C$1:C1),"")


text:
Q: Multiple Combinations with Try-Catch Blocks - Java What I am doing is taking String timestamps and parsing them using the SimpleDateFormat class for use in a calendar. However there are multiple formats these timestamps could be in, for this example time (10:30am vs 10am).
There are start and end times on this calendar I'm creating, so not only will I have to handle ParseExceptions for if the start time isn't formatted our typical hh:mmaa, but I've got to worry about the combination of the two. Here's what would work but I feel is utterly inefficient.
// Combination #1 -----------------------------------------------------
DateFormat format = new SimpleDateFormat("EEE MMM dd, yyyy hh:mmaa zzz");
DateFormat endTimeFormat = new SimpleDateFormat("EEE MMM dd, yyyy hh:mmaa  zzz");
Calendar date = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
try {
    date.setTime(format.parse(rawStartDate));
    endTime.setTime(endTimeFormat.parse(rawEndDate)));
} catch (ParseException e) {
    try {
        // Combination #2 ----------------------------------------
        format = new SimpleDateFormat("EEE MMM dd, yyyy hhaa zzz");
        endTimeFormat = new SimpleDateFormat("EEE MMM dd, yyyy hhaa  zzz");
        date.setTime(format.parse(rawStartDate));
        endTime.setTime(endTimeFormat.parse(rawEndDate)));
    } catch (ParseException ee) {
        //onto another iteration until our combination runs out THEN report the exception
        // start being hh:mmaa
        // end being hhaa -- etc etc
    }
}

Sure as this code is odd, probably not the correct use of the Calendar; Regardless, I'm wanting to know if there's a better way of going about this.
Obviously I need to only change the format and the endTimeFormat variables, but I cannot leave out the seemingly redundant date.setTime otherwise we wouldn't know if it worked.

A: I would use a variable for the two SimpleDateFormats.  This way it can be created just once. Note: if you make it a field, you need to lock it if you use in multiple thread, or you can use the JSR-310 library added to Java 8 which doesn't need a lock.
Rather than trial and error you could look for the : e.g. format.contains(":") which would determine which format it has to match.  This would allow you to have one common try-catch block.


text:
Q: Ember - controller actions not found from view Okay, read all the updated guides and still cannot figure out why my controller actions are not being called from the view. My ember app has a navigation view inserted in application.handlebars like this:
{{view App.NavigationView}}
{{outlet}}

Navigation controller looks like this:
App.NavigationController = Ember.ObjectController.extend({
  navAction: function() {
    console.log('navAction');
  }
});

Navigation template:

{{#linkTo "dashboard"}}Dashboard{{/linkTo}}

{{#linkTo "contacts"}}Contacts{{/linkTo}}

{{#linkTo "campaigns"}}Campaigns{{/linkTo}}

{{#linkTo "transactions"}}Transactions{{/linkTo}}

navAction

Any ideas? Thanks in advance.

A: I think the first mistake is to use {{view App.NavigationView}} because the NavigationController is not injected into it.
try to use the new {{render}} helper, like {{render navigation}}. It will lookup both NavigationView, NavigationController, the template 'navigation' and should be wired all together.
Then, the {{action}} helper now acts as explained in the documentation: http://emberjs.com/guides/templates/actions/
Here is a short example, (just miss the use of {{render}} http://jsfiddle.net/JLHuG/40/
Here I defined the action in the current route, but if you define it in the controller (uncomment it), this will be handled by the controller

A: Maybe have a look at the following post:
{{action}} with a click event doesn't trigger the function in the v2 Ember router
It talks about using a new helper called {{linkTo}}

A: Specify the target option in  {{action}} helper to tell, which object should receive the method call. For example:

{{action "navAction" target="controller"}}

If the target option is unspecified , then it will point to controller.target property which is usually set to the router.  However, the target can be set to the controller itself like this;

App.NavigationController = Ember.ObjectController.extend({
       init : function(){
        this._super();
        this.set("target", this);
  },

navAction: function() {
console.log('navAction');

} });

You can  refer the following gist  which clearly explains about {{action}} helper in depth:
https://gist.github.com/3595069


text:
Q: Bound for the equation $a^2 = b^2 + 4n$ For a fixed natural number $n$, I want to study the integer solutions of $$a^2 = b^2 + 4n.$$ There is always at least one solution, namely $$(n+1)^2 = (n-1)^2 + 4n.$$ There can be others; for example, the solutions of $a^2 = b^2 + 24$ are $$(a,b)
 = (\pm 7, \pm 5), \; \; (\pm 5, \pm 1).$$
Conjecture: there are no solutions $(a,b)$ with $|a| > n+1$.
I thought of factoring $4n = a^2 - b^2 = (a-b)(a+b)$. So there should definitely not be solutions $|a| > 4n$ since at least one of the factors would be greater than $4n$. Can we get all the way down to $n+1$?

A: If $|a|=n+2$ then $b^2=(n+2)^2-4n$, which is strictly greater than $n^2$ but less than $(n+2)^2$, hence it must be $(n+1)^2$, so $n^2+4=n^2+2n+1$ so $n=3/2$(not possible)
Now if $|a|=n+3$ then  $(n+3)^2-4n$ is a perfect square, which is strictly greater than $(n+1)^2$ but less than $(n+3)^2$, hence it must be $(n+2)^2$, so $n^2+2n+9=n^2+4n+4$ so $n=5/2$(not possible)
Now if $|a|>n+3$
$a^2>a^2-4n>(a-1)^2$
Hence it is never a perfect square as it's lying between two consecutive perfect squares, hence your conjecture is true.


text:
Q: How to solve for m given that: 1/(1+m) = (1−m) +... How to solve for m given that:
$$ \frac{1}{1+m} = 1-m+ [m_1 ]$$
where $m_1$ is a correction that follows the same pattern as its parent i.e.
$$ \frac{1}{1+m_1} = 1-m_1+[m_2] $$
and so on...
$$ \frac{1}{1+m_2} = 1-m_2+[m_3] $$
all m, $m_i$ <1 and $m_i$ are all successive corrections. And a follow up question is: is it possible to get a generalized solution to go deeper -- up to $m_i$? I guess I am trying to write the equation for m that follows the above pattern...

A: We have the standard geometric series result
$$\frac 1{1+m}=1-m+m^2-m^3+\ldots$$
The general term is $(-1)^im^i$
You can certainly write
$$\frac 1{1+m}=1-m+\frac {m^2}{1+m}\\
m_1=\frac{m^2}{1+m}\\
\frac 1{1+m_1}=\frac 1{1+\frac{m^2}{1+m}}=\frac {1+m}{1+m+m^2}=1-\frac{m^2}{1+m+m^2}$$


text:
Q: DocuSign API account creation with multiple tenants If I were to create a multi-tenant application I am trying to figure out how many accounts would need to be created on the DocuSign end.
As a DocuSign developer I have a single sandbox account. I am assuming if my app went to production I would have a single production account.
Can someone help me understand how DocuSign would manage the structure below. Would a DocuSign account need to be made per tenant, per administrator, or per customer?
Tenant 1 (companyA.myapp.com)
     Administrator 1 (someone who will upload documents that need to be signed) - will have a login to the Tenant 1 app
     Customer 1 (someone who will sign the documents) - will have a login to the Tenant 1 app
Tenant 2 (companyB.myapp.com)
     Administrator 1 (someone who will upload documents that need to be signed) - will have a login to the Tenant 1 app
     Customer 1 (someone who will sign the documents) - will have a login to the Tenant 1 app
I am thinking about billing here. Would I need a DocuSign developer account per tenant or can I handle this all under a single DocuSign account.
Will the administrators and customers of the tenant app all need to create their own personal DocuSign accounts at some point? If so will everything that happens still be stored under my developer account?
It would be ideal if the mappings we're exact:
For example it would be great if my developer account would let me add multiple apps to it. 1 per tenant. Then within each app I would be able to list all of the administrator accounts where each administrators uploaded documents would be stored. Then finally for the customers I am not sure if I would need to do anything if they are just signing the docs.
Something like this:
Tenant 1
     Administrator 1
          Uploaded docs for signing
     Administrator 2
          Uploaded docs for signing
Tenant 2
     Administrator 1
          Uploaded docs for signing
     Administrator 2
          Uploaded docs for signing
I would like to know how all of this would get broken out in the DocuSign world under a single developer account.

A: we call "tenants" accounts. Your app is developed under your personal account, but when it's ready to be used - it can be used with any account. You can add more users to your account if you want to test different scenarios. Sandbox accounts are free even if you add as many users as you want.


text:
Q: How to create .aar file of Android project in eclipse? I want to create .aar file for using our project with all activity and resource to other project just like .jar file, but jar file does not contain resource folder that's why i am unable to get xml files.
Please help me.


text:
Q: npm run build fails when using webcomponents and @sveltejs/adapter-static@next I'm trying to build a test application using shoelace webcomponents but when I execute npm run build command it fails. This code currently works while using npm run dev and has been tested with other webcomponent libraries like ui5-webcomponents and in both cases the command failed.
My code is the following:
<script>
    import { onMount } from 'svelte';
    import "@shoelace-style/shoelace/dist/themes/base.css";
    onMount(async () => {
        await import('@shoelace-style/shoelace/dist/components/button/button');
    });
</script>

<sl-button>Test</sl-button>

And the error I get is:
> npm run build

> ~TODO~@0.0.1 build /home/jorge/Code/xprmnt/svelte-shoelace-config
> svelte-kit build

vite v2.3.3 building for production...
✓ 28 modules transformed.
.svelte-kit/output/client/_app/manifest.json                            1.77kb
.svelte-kit/output/client/_app/pages/index.svelte-464950c5.js           0.53kb / brotli: 0.33kb
.svelte-kit/output/client/_app/layout.svelte-904f1151.js                0.49kb / brotli: 0.29kb
.svelte-kit/output/client/_app/error.svelte-ec464882.js                 1.19kb / brotli: 0.57kb
.svelte-kit/output/client/_app/chunks/preload-helper-9f12a5fd.js        0.61kb / brotli: 0.31kb
.svelte-kit/output/client/_app/assets/start-a8cd1609.css                0.16kb / brotli: 0.10kb
.svelte-kit/output/client/_app/chunks/vendor-43cd886a.js                5.05kb / brotli: 1.98kb
.svelte-kit/output/client/_app/assets/pages/index.svelte-a2c9796c.css   7.29kb / brotli: 1.43kb
.svelte-kit/output/client/_app/start-2c597637.js                        16.71kb / brotli: 5.32kb
.svelte-kit/output/client/_app/chunks/button-4ff57d8f.js                33.65kb / brotli: 8.11kb
vite v2.3.3 building SSR bundle for production...
✓ 23 modules transformed.
.svelte-kit/output/server/app.js   62.07kb

Run npm run preview to preview your production build locally.

> Using @sveltejs/adapter-static
> document is not defined
ReferenceError: document is not defined
    at file:///home/jorge/Code/xprmnt/svelte-shoelace-config/.svelte-kit/output/server/app.js:249:9
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:177:24)
    at async prerender (file:///home/jorge/Code/xprmnt/svelte-shoelace-config/node_modules/@sveltejs/kit/dist/chunks/index5.js:79:14)
    at async Object.prerender (file:///home/jorge/Code/xprmnt/svelte-shoelace-config/node_modules/@sveltejs/kit/dist/chunks/index5.js:296:5)
    at async adapt (file:///home/jorge/Code/xprmnt/svelte-shoelace-config/node_modules/@sveltejs/adapter-static/index.js:17:4)
    at async adapt (file:///home/jorge/Code/xprmnt/svelte-shoelace-config/node_modules/@sveltejs/kit/dist/chunks/index5.js:322:2)
    at async file:///home/jorge/Code/xprmnt/svelte-shoelace-config/node_modules/@sveltejs/kit/dist/cli.js:616:5
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ~TODO~@0.0.1 build: `svelte-kit build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ~TODO~@0.0.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/jorge/.npm/_logs/2021-05-24T17_08_03_058Z-debug.log

I've also created a small repo with my existing code. How can I fix this error?

A: You can fix this problem by just moving your webcomponent libraries to devDependencies inside your package.json. Doing this it should work properly.


text:
Q: View with sorting and paging Is there any ASP view that has paging like listview and sorting like dataview?
I was trying to avoid the implementation of one of those two manually.

A: GridView automatically implements these two abilities. Make sure the AllowSorting and AllowPaging properties are set to true. If you're using a sqlDataSource or objectDataSource the functionality is automatically taken care for your.
GridView AllowPaging property description
GridView AllowSorting property description
By default the GridView displays 10 records at a time but you can change that by setting the PageSize property.

A: If you're looking for something for ASP you're better off using a jQuery component. In ASP.NET, GridView does both, see this article:
http://msdn.microsoft.com/en-us/library/aa479347.aspx


text:
Q: Updating every X ms image source impacts the memory [memory leak] The problem:
When I want to update one image every 50ms and display it on screen (firefox, chrome), I noticed that the memory is growing up rapidly.
What I have:

*

*One server which serve a new image each time I call the request /carto (for example http://192.168.0.190:3000/carto?a=XXXXXX)

*I had this part ?a=XXXXXX ONLY to avoid the cache (otherwise the first image loaded will always be displayed). Adding ?a=XXXXXX (XXXXXXX is the timestamp) will not have any impact on the destination to reach

My minimalist source code which calls every 50ms my server and display each loaded image:

Welcome to a problem

What are the results:

*

*I notice the memory is growing rapidly

What I would like to understand:

*

*Why is this happening ?

*How to solve this problem which impacts all browsers ?

If you have any idea, don't hesitate to comment this post :)


text:
Q: How to add new values to key in a dict? If I had a sample dict:
mydict = {1:{2:'A'}}

how can I add new data to key 1 so that it can be like:
mydict = {1:{2:'A'},{3:'B'}}

When I do mydict.update({3:'B'})
I get:
{1: {2: 'A'}, 3: 'B'} not {1: {2: 'A'}, {3: 'B'}}
If I try .update using the same key it just replaces the data:
mydict.update({1:{3:'B'}}) becomes
{1: {3: 'B'}}

A: There already have a good library for you:
from collections import defaultdict

d = defaultdict(dict)
d['person']['name']='frank'
d['person']['age']='age'

and then you can easily get the data from your 2 key! like:
print d['person']['name']

A: When you do mydict.update({3:'B'}) you are updating the wrong dictionary.
It looks like you want to update the dictionary in mydict[1]
This is assuming you actually want a result of {1: {2: 'A', 3: 'B'}} as your example {1: {2: 'A'}, {3: 'B'}} is not valid python.
So try mydict[1].update({3:'B'})

A: Simply add
 mydict[1].update({3:'B'})

A:

 mydict ={2:'a',3:'b'}
 d={1:mydict}
 print (d)
 {1: {2: 'a', 3: 'b'}}

 to update more key:values you can add to mydict


text:
Q: Cloud function triggered by cloud storage crashes - ValueError: Invalid call for scalar access (getting) When I upload a xls file on CS to trigger the cloud function I get ValueError: Invalid call for scalar access (getting)!
Could you please help me find out where the problem is?
This is the function:
    bucketName = event['bucket']
    file = event['name']
    filePath = "gs://" + bucketName + "/" + file
    print(filePath)

    df = pd.read_excel(filePath, header=0, skiprows=2, engine='openpyxl')
    df.columns = df.columns.str.normalize('NFKD').str.encode('ascii',errors='ignore').str.decode('utf-8').str.replace('#', 'num', regex=True).str.replace('\)|\(', '', regex=True).str.replace(' ', '_', regex=True).str.replace('.1', '', regex=True)

    # Construct a BigQuery client object.
    client = bigquery.Client()
    # Set table_id to the ID of the table to create.
    table_id = "project.dataset.table"
    bigqueryJob = client.load_table_from_dataframe(df, table_id)
    bigqueryJob.result()

```

A: Finally, the problem was I have two columns with the same name
Thanks!


text:
Q: Deferred Rendering: Performance issues I've just implemented deferred rendering/shading for the first time and I was surprised to see the big perfomance gap between forward and deferred rendering.
When I run my application with forward rendering I get a pretty decent frame rate while running in Release mode
FORWARD RENDERING

However when I ran it with deferred rendering it gave me a rather surprising output
DEFERRED RENDERING

I'm well aware of that deferred rendering is NOT something you coat an application with to make it go "faster". I consider it to be a performance optimization technique that can be optimized in a numerous ways and I understand that the technique has a larger memory footprint than forward rendering.
However...
I've currently got ONE point light in the scene and one hundred cubes created with hardware instancing. The light is moving back and forth on the Z-axis casting light on the cubes.
The problem is that the light is very laggy when moving. It's so laggy that the application doesn't register the keyboard input. Honestly, I was not prepared for this and I assume that I'm doing something terrible bad in my implementation.
So far I've changed the texture format on the gbuffers from DXGI_FORMAT_R32G32B32A32_FLOAT to DXGI_FORMAT_R16G16B16A16_FLOAT jsut to see if it had any visual impact but it did not.
Any suggestions? Thank you!
SIDE NOTE
I'm using the Visual Studio Graphics Diagnostics for debugging my DirectX applications

A: Solved it!
I enabled the DirectX debug layer and I got a sea of D3D11 warnings
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets: Resource being set to OM RenderTarget slot 1 is still bound on input! [ STATE_SETTING WARNING #9: DEVICE_OMSETRENDERTARGETS_HAZARD]
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing PS shader resource slot 1 to NULL. [ STATE_SETTING WARNING #7: DEVICE_PSSETSHADERRESOURCES_HAZARD]
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets: Resource being set to OM RenderTarget slot 2 is still bound on input! [ STATE_SETTING WARNING #9: DEVICE_OMSETRENDERTARGETS_HAZARD]
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing PS shader resource slot 2 to NULL. [ STATE_SETTING WARNING #7: DEVICE_PSSETSHADERRESOURCES_HAZARD]
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets: Resource being set to OM RenderTarget slot 3 is still bound on input! [ STATE_SETTING WARNING #9: DEVICE_OMSETRENDERTARGETS_HAZARD]
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing PS shader resource slot 3 to NULL. [ STATE_SETTING WARNING #7: DEVICE_PSSETSHADERRESOURCES_HAZARD]

So at the end of the render function i.e. after
mSwapChain->Present( 0, 0 );

I added
mDeviceContext->ClearState();

Just to reset the device context which sets all input/output resource slots to NULL as explained on MSDN


text:
Q: Photo & Video Thumbnail Gallery I've been after a simple plugin for my portfolio site so I can include photos and videos of my work.
I currently have this implemented in my website concept ; Simple Thumbnail Gallery but I wouldn't know where to start if I wanted to add video in this? even if its possible? I want 5 image thumbnails and 1 video thumbnail and when you click on any they appear in a larger viewport with fade transition. I can't believe how difficult it is to find something like this, surely people have wanted this before?

A: I had a need of something like this.
Did some research on the net & jsfiddle & modified & came up with this code.
WORKING DEMO
$(".fancybox").find("img").stop(true, true).animate({
            "opacity": 0.2
        }, "slow");

$(".fancybox").on("mouseenter", function () {
            $(this).find("img").stop(true, true).animate({
                "opacity": 1
            }, "slow");
}).on("mouseleave", function () {
        $(this).find("img").stop(true, true).animate({
            "opacity": 0.2
        }, "fast");
}).fancybox({
padding: 0,
openEffect: 'elastic',
openSpeed: 250,

closeEffect: 'elastic',
closeSpeed: 450,
closeClick: false,

helpers: {
    overlay: {
        css: {
            'background': 'rgba(0, 0, 0, 0.9)'
        }
    }
}
});

It is using fancy box plugin.
I know i might be already late in replying but just might help someone out there looking for the same query.