text:
Q: Where store css and js in symfony im using symfony ad i read that the best practice to store image js and images is /web
<link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}" />

if I want use assetic i found example like
    {% javascripts '@AppBundle/Resources/public/js/*' output='js/compiled/main.js' %}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}

where @AppBundle is logical name of Bundle

Logical File Names¶
When you want to reference a file from a bundle, use this notation:
  @BUNDLE_NAME/path/to/file; Symfony will resolve @BUNDLE_NAME to the
  real path to the bundle. For instance, the logical path
  @AppBundle/Controller/DefaultController.php would be converted to
  src/AppBundle/Controller/DefaultController.php, because Symfony knows
  the location of the AppBundle.

Where Do I Have To store my assets?

A: If you are NOT using assetic, you should place your publicly accessible images and js in the /web directory.
If you are USING assetic, you should place your publicly accessible images and js in your @AppBundle/Resources/public/css and @AppBundle/Resources/public/js respectively. Then you will have to use assetic, assetic will automatically take care of making it accessible to the public. You don't need to worry about that, usually it will filter and copy your files into your /web directory.
Example:
{% block javascripts %}
    {% javascripts '@AppBundle/Resources/public/js/*' %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

In this example, all files in the Resources/public/js/ directory of the AppBundle will be loaded and served from a different location. The actual rendered tag might simply look like:
<script src="/app_dev.php/js/abcd123.js"></script>

For more info, read this:
http://symfony.com/doc/2.8/cookbook/assetic/asset_management.html#installing-and-enabling-assetic

A: you should put your css/js files under app/Resources/assets/css and app/Resources/assets/js (asset folder can be "public" folder)
And later you shoud use assetic to put the final app.css and app.js under the web folder (this is the public folder in symfony projects)
Documentation here (contradiction?) and here

A: Since Symfony4.0, the Best Practice is now in a new /assets directory in the root directory.
This makes it much easier for your Frontend developers and designers to work without having to get into the backend mess.


text:
Q: RedHat machine will not boot when video card is removed I "inherited" RH 6.4 on a computer with an nVidia video card.  I took the image and dd'd it to another computer that has the same hardware.
By design, the second computer will be headless.  This second computer boots and runs just fine.  However, when I remove the video card from the second computer so that it's headless, it hangs and does not boot.  There is little debugging I can do to determine why.  The BIOS seems to post just fine.
I really don't want to reinstall the system from scratch.  My assumption is that the kernel module for the video card is trying to do something to the hardware but it fails to find it and hangs.
So short of a reinstall, what can I do to get this to boot?  I can do whatever I need to do with the video card in, so I can get it to boot up to make the changes.
Thanks!
Edit: This is RHEL 6.5, not 6.4.
The content of /var/log/messages is:

*

*Feb 11 10:34:06 MDCS-Server kernel: device virbr0-nic entered promiscuous mode

*Feb 11 10:34:06 MDCS-Server kernel: virbr0: starting userspace STP failed, starting kernel STP

*Feb 11 10:34:07 MDCS-Server kernel: ip_tables: (C) 2000-2006 Netfilter Core Team

*Feb 11 10:34:07 MDCS-Server kernel: nf_conntrack version 0.5.0 (16384 buckets, 65536 max)

*Feb 11 10:34:08 MDCS-Server dnsmasq[1972]: started, version 2.48 cachesize 150

*Feb 11 10:34:08 MDCS-Server dnsmasq[1972]: compile time options: IPv6 GNU-getopt DBus no-I18N DHCP TFTP "--bind-interfaces with SO_BINDTODEVICE"

*Feb 11 10:34:08 MDCS-Server dnsmasq-dhcp[1972]: DHCP, IP range 192.168.122.2 -- 192.168.122.254, lease time 1h

*Feb 11 10:34:08 MDCS-Server dnsmasq[1972]: no servers found in /etc/resolv.conf, will retry

*Feb 11 10:34:08 MDCS-Server dnsmasq[1972]: read /etc/hosts - 2 addresses

*Feb 11 10:34:08 MDCS-Server dnsmasq[1972]: read /var/lib/libvirt/dnsmasq/default.addnhosts - 0 addresses

*Feb 11 10:34:08 MDCS-Server dnsmasq[1972]: read /var/lib/libvirt/dnsmasq/default.hostsfile

*Feb 11 10:34:08 MDCS-Server kernel: Ebtables v2.0 registered

*Feb 11 10:34:08 MDCS-Server kernel: ip6_tables: (C) 2000-2006 Netfilter Core Team

*Feb 11 10:34:10 MDCS-Server kernel: lo: Disabled Privacy Extensions

*Feb 11 10:34:22 MDCS-Server init: tty (/dev/tty2) main process (1941) killed by TERM signal

*Feb 11 10:34:22 MDCS-Server init: tty (/dev/tty3) main process (1943) killed by TERM signal

*Feb 11 10:34:22 MDCS-Server init: tty (/dev/tty4) main process (1945) killed by TERM signal

*Feb 11 10:34:22 MDCS-Server init: tty (/dev/tty5) main process (1949) killed by TERM signal

*Feb 11 10:34:22 MDCS-Server init: tty (/dev/tty6) main process (1951) killed by TERM signal

*Feb 11 10:34:23 MDCS-Server abrtd: Got signal 15, exiting

*Feb 11 10:34:27 MDCS-Server init: Disconnected from system bus

*Feb 11 10:34:27 MDCS-Server console-kit-daemon[2031]: WARNING: no sender#012

*Feb 11 10:34:27 MDCS-Server rpcbind: rpcbind terminating on signal. Restart with "rpcbind -w"

*Feb 11 10:34:27 MDCS-Server auditd[1279]: The audit daemon is exiting.

*Feb 11 10:34:27 MDCS-Server kernel: type=1305 audit(1423672467.509:38): audit_pid=0 old=1279 auid=4294967295 ses=4294967295 subj=system_u:system_r:auditd_t:s0 res=1

*Feb 11 10:34:27 MDCS-Server kernel: type=1305 audit(1423672467.606:39): audit_enabled=0 old=1 auid=4294967295 ses=4294967295 subj=system_u:system_r:auditctl_t:s0 res=1

*Feb 11 10:34:27 MDCS-Server kernel: Kernel logging (proc) stopped.

*Feb 11 10:34:27 MDCS-Server rsyslogd: [origin software="rsyslogd" swVersion="5.8.10" x-pid="1304" x-info="http://www.rsyslog.com"] exiting on signal 15

I've tried various combinations of all the options below.  I can't get this thing to boot.  NUM-LOCK also does not work, so the system really is out to lunch.
SOLVED: Finally, it is solved.  The log above is at shutdown, not boot.  It never got to the kernel, apparently.  (No one ever accused me of being smart, though in my defense it's hard to debug it when you can't see anything useful like, you know, the clock.)
In any event, it was a GRUB problem.  I removed 'rhbg' from the kernel parameters and commented out the splashimage line, which is spelled out nicely here, and everything started working splendidly.
Many thanks to those who tried to help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any "official" guidance to upgrading from Lubuntu 18.04 LTS (LXDE) to Lubuntu 18.10 (LXQt) Since there are major differences between Lubuntu 18.04 LTS and Lubuntu 18.10 primarily involving the change from LXDE to LXQt is there any guidance available for those who wish to upgrade from 18.04 LTS to 18.10, as opposed to performing a clean installtion of 18.10?

A: From the release notes for Lubuntu 18.10:

The most major and notable problem is that upgrading Lubuntu from 18.04 to 18.10 causes a fair amount of issues. Therefore, we are not officially supporting this upgrade path at this time, however we have prepared a page in the Lubuntu Manual which can help address the problems that arise after the upgrade.

Appendix D Upgrading from previous releases deals precisely with this issue.
Guidance is provided for those who want a GUI route and for those who prefer to use the command-line. Anyone considering upgrading can consult the link for full details.
Of note is the caution that, at some point during the upgrade, the user will be asked to choose between display managers:

You will be asked to select a display manager, the new default is Simple Desktop Display Manager (SDDM). This will happen in the middle of the install, so don't walk away until after you have done this.

Another point to note is this:

Many of the old applications will not be removed. Newer and often times more featureful, Qt-based applications with the same functionality are installed during the upgrade. Having many unnecessary applications could bloat your system and isn't the true Lubuntu experience, so uninstalling them may be a good idea.

There's a terminal command to remove what the Lubuntu team regard as unnecessary software:
sudo apt purge leafpad file-roller galculator gpicview xpad xfburn simple-scan mtpaint pidgin sylpheed transmission-gtk abiword evince gnumeric audacious gnome-mpv guvcview pcmanfm gdebi lxterminal hardinfo lightdm lxpanel lxsession obconf gnome-software gnome-disk-utility system-config-printer-gnome lxhotkey-gtk synaptic update-manager lxpolkit lxtask lxshortcut blueman usb-creator-gtk evince-common

Running
sudo apt autoremove

after the removal of the packages listed above would clean up further.


text:
Q: Using the YouTube Data API V3 – quota very quickly runs out I am making a discord bot using discord.js and am using the YouTube API for music commands.
However, I managed to use up all of my quota just in testing. It can load playlists, search for songs and use urls and uses ytdl-core module to download the videos. Is it normal to use this much of a quota or is something wrong. I also noticed that you cannot get an extension for your quota without having an organisation, which I do not.

A: I'm running into the same problem. The YouTube Data API has a crazy low quota/limit. While the quota sounds reasonable, 10,000 queries per day, it's actually much lower. First, they count each query as 100. So take 10,000 and divide it by 100 and that's how many queries you are really allowed to make. Furthermore, they paginate their results with a maximum of 50 results (videos) per page. So in reality, YouTube will let you access data on 5,000 videos per day using the YouTube Data APIs search functionality. To confirm my math, I just checked my quota for the day. After querying the API for 10 pages of results (50 videos per page, 500 videos total) my quota/usage is listed at 1,000 out of the 10,000 allotment per day. Essentially, the YouTube Data API is useless.


text:
Q: Why the java sessions are not ending once the cronjob has been executed in AIX OS I have set a crontab for execute a java service in every 8 hours in AIX(7.1) operating system. Once the crontab has done the job, the JAVA service should be end. This cronjob is working properly. But java service has not been closing its session at the end. Also this java service takes 3-4 hours to process the files.
Java sessions are accumulating day by day and eventually it leads to idle the application server.
Java Version 1.8
AIX 7.1
Crontab entry:
00 8 * * * cd /ibl/qnb/uat/app/adm/ADM_AUTOMATE_SERV && ./RUN.sh > /ibl/qnb/uat/logs/adm/ADM_AUTOMATE_SERV/run.log

If I execute the above statement manually, cronjob runs properly and closing the session at the end.
RUN.sh file:
/usr/java8_64/bin/java -Xmx1024m -jar ADM_AUTOMATE_SERV.jar

Below are the java sessions still running in the application server. Please have a look and advise  what I'm going wrong?

Highly appreciate your time and efforts for this matter.


text:
Q: Datatypes and order of constructors Is there a difference between the following definitions?
datatype Nat = S(Nat) | Z

And
datatype Nat = Z | S(Nat)

I would expect no, but interestingly enough, the following code compiles fine with the first definition, but not with the second.
function natToDay(n : Nat) : Day
  decreases n
{
  match n {
    case Z                      => Monday
    case S(Z)                   => Tuesday
    case S(S(Z))                => Wednesday
    case S(S(S(Z)))             => Thursday
    case S(S(S(S(Z))))          => Friday
    case S(S(S(S(S(Z)))))       => Saturday
    case S(S(S(S(S(S(Z))))))    => Sunday
    case S(S(S(S(S(S(S(k))))))) => natToDay(k)
  }
}

lemma {:induction n} proof(n : Nat)
  ensures natToDay(n) == Sunday    ==> natToDay(n) == Sunday
  ensures natToDay(n) == Saturday  ==> natToDay(S(n)) == Sunday
  ensures natToDay(n) == Friday    ==> natToDay(S(S(n))) == Sunday
  ensures natToDay(n) == Thursday  ==> natToDay(S(S(S(n)))) == Sunday
  ensures natToDay(n) == Wednesday ==> natToDay(S(S(S(S(n))))) == Sunday
  ensures natToDay(n) == Tuesday   ==> natToDay(S(S(S(S(S(n)))))) == Sunday
  ensures natToDay(n) == Monday    ==> natToDay(S(S(S(S(S(S(n))))))) == Sunday
{}

The first datatype definition produces:
Dafny program verifier finished with 2 verified, 0 errors
Wrote textual form of target program to test.cs

The second one produces:
/Users/boro/Desktop/dafny/test.dfy(27,0): Error: A postcondition might not hold on this return path.
/Users/boro/Desktop/dafny/test.dfy(21,54): Related location: This is the postcondition that might not hold.
Execution trace:
...

A: There's not supposed to be any difference between the two. Please report this problem on https://github.com/dafny-lang/dafny/issues.


text:
Q: update all the nodes with same data on a single update Basically i owns 3 systems where one act as a Balancer Node , and the data for the websites resides over the other two.
The Problem is :
i want to update all the 2 nodes with the same data (means .php files , which my website is designed) when i update either one of them . note: .php source files have to be updated
what can i do?
Doubt :
i have also one doubt to ask can i basically call the group (balancer system and the nodes ) as a cloud ?

A: You can try using a git repo...
basically what we do is we create a GIT repo and push our code to it, and on the webserver, we clone that repository on deployment path e.g. /var/www/html/xyz
and evry time a developer commits to the repo, there is a custom script that is triggered to pull new files from git to target webservers...


text:
Q: Bubble Sort Recursively I have searched Google and I cannot find anything for this. I was looking for various types of sorts (as you can see in a previous question of mine) and I was wondering if anyone knew of a recursive bubble sort code. To me, the idea sounds ridiculous, but I want to be prepared for things and I'm curious as to whether or not this can be done. I'm sure it can, as a professor of mine has asked this of his students in the past. I don't think he'll repeat questions, but I became curious and wanted to know if there was code for a bubble sort recursively.

A: It's certainly possible to do this, since any iterative algorithm can be converted to a recursive one and vice-versa.
Here's one way that we can do this. For simplicity, I'm using C++ and assuming the inputs are all integers.
void bubbleSort(std::vector<int>& list) {
    /* Make one pass of swapping elements. If anything was swapped,
     * repeat this process.
     */
    if (swapPass(list)) {
        bubbleSort(list);
    }
}

/* Does a pass over the array, swapping adjacent elements if they're
 * out of place. Returns true if anything was swapped and false
 * otherwise.
 */
bool swapPass(std::vector<int>& list) {
    return recSwapPass(list, 0, false);
}

/* Does a swap pass starting from index given information about
 * whether a swap was made on the pass so far. Returns true if across
 * the entire pass a swap was made and false otherwise.
 */
bool recSwapPass(std::vector<int>& list, unsigned index,
                 bool wasSwapped) {
    /* Base case: If we're at the end of the array, then there's
     * nothing to do and we didn't swap anything.
     */
    if (index + 1 >= list.size()) return wasSwapped;

    /* Compare the current element against the next one and see if
     * they need to swap.
     */
    if (list[index] > list[index + 1]) {
        std::swap(list[index], list[index + 1]);
        return recSwapPass(list, index + 1, true);
    } else {
        return recSwapPass(list, index + 1, wasSwapped);
    }
}

Interestingly, every recursive function here is tail-recursive, so a good optimizing compiler should be able to generate non-recursive code. In other words, a good compiler should generate pretty much the same code as if we'd written this iteratively. If I get the time, I'll check out whether this actually happens. :-)


text:
Q: Handling sessions for scalability I'm currently making a site that is very database oriented somewhat like Stack Overflow. My question is how to handle sessions that will travel across several servers(I plan on using AWS servers for auto scaling).
Currently I am under the belief that I should not use Forms Authentication for scalability and speed purposes. Instead I would have a table in the database called sessions that stores the following information: SessionID, UserID, ExpDate, CreateDate, IP, Status('LogedIn', 'LogedOut', 'Expired').
My biggest concern would be security from the stand point of cookies and not having the experience to see a bottle neck scenario when I have a lot of server running.
Please provide me with your insight. I'd also like to know how others and Stack Overflow are handling this dilemma.
FYI: For the same reasons I'm using PetaPoco instead of Entity Framework as I was able to shave off around 600ms by doing so.
Thank you for your help!

A: I am not aware of any scalability issues with using Forms Authentication. Essentially, it encrypts an authorization token into a cookie and the cookie is presented to the server on each request. Using cookies instead of in-process session does allow for scalability as it is not tied to any one specific server.
The encryption uses a machineKey value that is stored on the server so breaking the encryption would require getting a hold of the machineKey.
In general, I try not to implement my own authorization and instead try to stick with out-of-the-box solutions that have been tested.
Your approach of using a session store still requires the use of a cookie to store some kind of pointer to the session store. Depending on your implementation, it might be easy to guess this information and easily impersonate someone else.
EDIT:
Since you are running on AWS, I would suggest you take advantage of ElastiCache to reduce the number of DB hits.

A: I know from a caching perspective that StackOverflow was built using Redis.
Check out Which tools and technologies are used to build the Stack Exchange Network?.


text:
Q: Disable WooCommerce order email notification for orders with custom status I have searched the web and checked the WooCommerce docs for a solution to disable the "confirmation email" that is sent to the customer when they place an order in WooCoomerce.
I also want to disable the "new order" mail that goes to the admin.
But only if the order has a custom status "mystatus", which some orders are getting based on what the customers are ordering.
Tried adding it like this, but it did not work:
remove_action( 'woocommerce_order_status_mystatus_notification', array($email_class->emails['WC_Email_New_Order'], 'trigger' ) );?>
Any advice?

This is how I change the order status for specific orders:
add_action( 'woocommerce_thankyou','woocommerce_thankyou_change_order_status', 10, 1 );
function woocommerce_thankyou_change_order_status( $order_id ){
if( ! $order_id ) return;

$order = wc_get_order( $order_id );
$user_id = $order->get_user_id();

if( ($order->get_status() == 'processing'  || $order->get_status() == 'pending' || $order->get_status() == 'on-hold' ) && dokan_is_user_seller( $user_id ) && is_user_logged_in()) {
    $order->update_status( 'mystatus' );
  }
}

A: No real need to make any changes to WooCommerce settings.
No email-notifications will be sent for a custom order status, unless you effectively provide this.
However, the default email-notifications are sent, because the woocommerce_thankyou hook is executed after the email-notifications have been sent.
So use the woocommerce_checkout_order_created hook (that is executed, before the e-mail notifications are sent) opposite woocommerce_thankyou to change the order status, and no emails will be sent anyway.
function action_woocommerce_checkout_order_created( $order ) {
    // Get user ID
    $user_id = $order->get_user_id();

    // Compare
    if ( ( $order->get_status() == 'processing'  || $order->get_status() == 'pending' || $order->get_status() == 'on-hold' ) && dokan_is_user_seller( $user_id ) && is_user_logged_in() ) {
        // Update status
        $order->update_status( 'mystatus' );
    }
}
add_action( 'woocommerce_checkout_order_created', 'action_woocommerce_checkout_order_created', 10, 1 );

Note: If you want to disable emails in any other case, you can use the woocommerce_email_recipient_{$email_id} filter composite hook and with the right email ID set, you have the option to disable email notifications.
For instance:
// Admin - new order email notification
// Customer - on hold
// Customer - processing
// Customer - pending
function filter_woocommerce_email_recipient( $recipient, $order, $email ) {
    if ( ! $order || ! is_a( $order, 'WC_Order' ) ) return $recipient;

    // Has order status
    if ( $order->has_status( 'your-order-status' ) ) {
        $recipient = '';
    }

    return $recipient;
}
add_filter( 'woocommerce_email_recipient_new_order', 'filter_woocommerce_email_recipient', 10, 3 );
add_filter( 'woocommerce_email_recipient_customer_on_hold_order', 'filter_woocommerce_email_recipient', 10, 3 );
add_filter( 'woocommerce_email_recipient_customer_processing_order', 'filter_woocommerce_email_recipient', 10, 3 );
add_filter( 'woocommerce_email_recipient_customer_pending_order', 'filter_woocommerce_email_recipient', 10, 3 );

A: Disable the mail under WooCommerce >> Settings >> Emails you want to only sent in case your order has a custom status.
Now just sent it in case your order has the correct status:
add_action( 'woocommerce_thankyou', 'woocommerce_thankyou_change_order_status', 10, 1 );
function woocommerce_thankyou_change_order_status( $order_id ) {
    if ( ! $order_id ) {
        return;
    }

    $order   = wc_get_order( $order_id );
    $user_id = $order->get_user_id();

    if ( ( $order->get_status() == 'processing' || $order->get_status() == 'pending' || $order->get_status() == 'on-hold' ) && dokan_is_user_seller( $user_id ) && is_user_logged_in() ) {
        $order->update_status( 'mystatus' );

        $email_oc = new WC_Email_Customer_Completed_Order();
        $email_oc->trigger($order_id);
    }
}

You can just sent every WooCommerce mail from PHP you want.


text:
Q: Knockout - How can I bind an observable by the element's ID? I'm building a mechanism to automatically display validation messages in a form field and would like to discuss about this.
I have an observable array with the error message and its respective properties.
How can I bind an element of the observable array to its respective form field?
The observable has the following data (i.e):
messages = ko.observableArray();
- Property: Reference, Message: Already exists a product with this reference.
- Property: Name, Message: The product's name is mandatory.
- Property: Bar Code, Message: The Bars Code does not matches the EAN13 format.
- ...

My form fields' IDs have the same names of the properties in the array:

            Reference
            <input class="text-box single-line" id="Reference" name="Reference" type="text" value="" data-bind="value: selected().Reference" />

            Name
            <input class="text-box single-line" id="Name" name="Name" type="text" value="" data-bind="value: selected().Name" />

            Bars Code (EAN13)
            <input class="text-box single-line" id="BarCode" name="BarCode" type="text" value="" data-bind="value: selected().BarCode" />

I'm very new to Knockout.js but I think that I'll need to use a ´computed observable´, which returns the respective message for each span.
What you say?
/// UPDATE ////////////////////////////////////////////////////
The Products View Model:
function mainmodel(baseUri) {

var m = this;
    m.baseUri = baseUri;

/// PRODUCTS VIEW MODEL ******************************************* *

    m.products = new function () {

        var p = this;
            p.baseUri = baseUri;
            p.items = ko.observableArray();
            p.selected = ko.observable();
            p.messages = ko.observableArray([]);

The Products Loading
        /// LIST
            p.list = function () {
                $.getJSON(p.baseUri + "/list" + "?page=" + p.currentpage(), p.items);
            }

The Product Creation (where the validation messages are loaded)
        /// CREATE
            p.create = function (formElement) {
                //$.post(p.baseUri + "/create", $(formElement).serialize(), null, "json")
                $.ajax({
                    type: 'POST',
                    url: p.baseUri + "/create",
                    data: $(formElement).serialize(),
                    success: null,
                    dataType: "json",
                    statusCode: {
                        400: function (o) {
                            p.messages($.parseJSON(o.responseText));
                        }
                    }
                });
            }

Running this, p.messages contains validation messages for each of the product's properties.

A: I think that there are a couple of approaches that you could use for this one.  If you are receiving these validation messages back from a request to the server, then you could loop through them and populate observables directly based on the results.
A nice way to do this is to create a "sub" observable to hold the validation message like:
this.myObservable = ko.observable();
this.myObservable.validationMessage = ko.observable();

Now you can bind against myObservable and myObservable.validationMessage.
So, if you received an array of messages back you could loop through them and apply the messages like:
        var messages = [
            { Property: "Reference", Message: "Can't find a reference to this reference" },
            { Property: "Name", Message: "Pick a better name" },
            { Property: "BarCode", Message: "Not a valid code" }
        ];

        //apply messages to each observable
        ko.utils.arrayForEach(messages, function(message) {
            if (ko.isObservable(self[message.Property])) {
               self[message.Property].error(message.Message);
            }
        });

I don't know your application flow, but you might want to clear the errors first.
Here is a sample: http://jsfiddle.net/rniemeyer/mk2Ed/
Here is an alternate that uses computed observables (the first would be slightly more efficient): http://jsfiddle.net/rniemeyer/R6mL8/


text:
Q: How to invoke a function in jQuery file from Android Java code? The content of jQuery file is listed as below, some of the content is ignored.
(function ($){
...
...
...
function hideDiv()
{
    // "vodmain" is the id of a div
    $("#vodmain").hide();
}
})(jQuery);

some of html code:

    ...

the Java code(in an Activity) which invoke the function 'hideDiv' is listed as below:
public boolean onKeyUp(int keyCode, KeyEvent event) {

    if(keyCode == 4 && webView.canGoBack())
    {
        webView.goBack();
        return true;
    }
    if(keyCode == 18 || keyCode == 19 || keyCode == 20 || keyCode == 21 || keyCode == 22)
    {
        webView.loadUrl("javascript:hideDiv()");
        //webView.dispatchKeyEvent(event);
        return false;
    }
    return super.onKeyUp(keyCode, event);
}

my problem is: if JS function is written in html file, I can invoke it from the Activity, but if it is written in a jQuery file, I can't invoke it. And I don't know why, that's because it just call a function in jQuery or some reason else?


text:
Q: Can't calculate cumulative distrubtion Given $X$ continuous random variable
$f(x) =$
\begin{cases}
\frac{k^3}{2} x^2 e^{-kx},       & {x \geq 0 , k \gt 0} \\
0, & { x \lt 0, k \gt 0}
\end{cases}
For this function i need to calculate the cumultative distribution (i.e. $P(X \leq x$) ).  I got this:
$F(x) =$
\begin{cases}
0,       & {x \lt 0 , k \gt 0} \\
1 - \frac{k^2x^2+2kx+2}{2} e^{-kx}, & { x \geq 0, k \gt 0}
\end{cases}
But i can't obtain $F(x) = 1$, so where am I wrong?

A: You want to show your CDF $\to1$ as $x\to\infty$. This follows from the famous result $\lim_{x\to\infty}x^ne^{-kx}$ for $k>0$.
Incidentally, this is a Gamma distribution with $\alpha=3,\,\beta=k$. In fact, it's an Erlang distribution.


text:
Q: Edit permission for ssh key users in Virtual Studio Team Service I added my user the ssh based authentication but i don't know how to set the permission for that user. Anybody know?

A: Permissions for the users who use ssh protocol is accordance with what the permissions set for the user in VSTS web page. And you can use below aspects to set permissions for the user:

*

*Set permission for the user which projects (git repositories in the projects) can be access
In Users page (https://account.visualstudio.com/_settings/users) -> click … button for the user -> Manage projects -> select the project you want the user to access -> save changes.

So the user with ssh protocol can only access to the git repositories in the select project(s).

*Set permission for the user for repositories and branches
In a certain project, set permission for the repo(s) and branch in Repositories Page (https://account.visualstudio.com/project/_settings/repositories) as below:
Select a certain level (all repositories, a repository or a branch) you want to set permission for the user -> Add the user -> then set detail permissions for the user -> save changes.

Such as if I set the permission (deny to force push to product1 repo's f branch in Git2 project) for a user who use ssh protocol as below:

When the user try to force push changes to product1's f branch, it will be failed:


text:
Q: How to change my code from applet to JFrame? Really need help!!! wondering how i could change my applet into a JFrame. Im not liking the applet the guy used in his tutorial and i would like to switch to a JFrame. I am very new to java and yes i have very little knowledge. Any help would be greatly appreciated! The game is a snake game.
TUTORIAL: https://www.youtube.com/watch?v=FABTl1Q1byw
APPLET CLASS:
import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Color;

public class snakeApplet extends Applet{

  private SnakeCanvas c;//410x310

    public void init(){
    c = new SnakeCanvas();
    c.setPreferredSize(new Dimension(410, 310));
    c.setVisible(true);
    c.setFocusable(true);
    this.add(c);
    this.setVisible(true);
    this.setSize(new Dimension(410, 310));

 }

 public void paint(Graphics g){
  this.setSize(new Dimension(410, 310));
 }
 }

GAME CLASS:
public class SnakeCanvas extends Canvas implements Runnable, KeyListener{
private final int BOX_HEIGHT = 10;
private final int BOX_WIDTH = 10;
private final int GRID_WIDTH = 25;
private final int GRID_HEIGHT = 25;

private LinkedList<Point> snake;
private Point fruit;
private int direction = Direction.NO_DIRECTION;

private Thread runThread;
private int score = 0;
private String highscore = "";

public void init() {

}

public void paint(Graphics g) {
    if (snake == null) {
        snake = new LinkedList<Point>();
        GenerateDefaultSnake();
        PlaceFruit();
    }

if (runThread == null) {
    this.setPreferredSize(new Dimension(640, 480));
    this.addKeyListener(this);
    runThread = new Thread(this);
    runThread.start();
}

if (highscore.equals("")) {
    highscore = this.GetHighScore();
}

drawFruit(g);
drawGrid(g);
drawSnake(g);
drawScore(g);

}

public void update(Graphics g) {
Graphics offScreenGraphics; //Graphics used to draw offscreen
BufferedImage offscreen = null;
Dimension d = this.getSize();

offscreen = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
offScreenGraphics = offscreen.getGraphics();
offScreenGraphics.setColor(this.getBackground());//CHANGE BACKGROUND COLOR
offScreenGraphics.fillRect(0, 0, d.width, d.height);
offScreenGraphics.setColor(this.getForeground());
paint(offScreenGraphics);

//flip
g.drawImage(offscreen, 0, 0, this);
}

public void GenerateDefaultSnake() {
score = 0;
snake.clear();

snake.add(new Point(0,2));
snake.add(new Point(0,1));
snake.add(new Point(0,0));
direction = Direction.NO_DIRECTION;

}

public void Move() {
Point head = snake.peekFirst();
Point newPoint = head;
switch(direction) {
    case Direction.NORTH:
        newPoint = new Point(head.x, head.y - 1);
        break;
    case Direction.SOUTH:
        newPoint = new Point (head.x, head.y + 1);
        break;
    case Direction.WEST:
        newPoint = new Point (head.x - 1, head.y);
        break;
    case Direction.EAST:
        newPoint = new Point (head.x + 1, head.y);
        break;
}

snake.remove(snake.peekLast());

if(newPoint.equals(fruit)){
score+=10;
//the snake has hit fruit
Point addPoint = (Point) newPoint.clone();

switch(direction){
case Direction.NORTH:
newPoint = new Point(head.x, head.y-1);
break;
case Direction.SOUTH:
newPoint = new Point (head.x, head.y+1);
break;
case Direction.WEST:
newPoint = new Point (head.x-1, head.y);
break;
case Direction.EAST:
newPoint = new Point (head.x+1, head.y);
break;
}
snake.push(addPoint);
PlaceFruit();
}
else if(newPoint.x < 0 || newPoint.x > GRID_WIDTH - 1){
//we went out of bounce, reset game
CheckScore();
GenerateDefaultSnake();
return;
}
else if(newPoint.y < 0 || newPoint.y > GRID_HEIGHT - 1){
//we went out of bounce, reset game
CheckScore();
GenerateDefaultSnake();
return;
}
else if(snake.contains(newPoint)){
//we ran into ourselves, reset game
CheckScore();
GenerateDefaultSnake();
return;
}

 //if we reach this point in code, we're still alive
 snake.push(newPoint);
 }

 public void drawScore(Graphics g){
 g.drawString("Score: " + score, 0, BOX_HEIGHT * GRID_HEIGHT + 10);
 g.drawString("HighScore: " + highscore, 0, BOX_HEIGHT * GRID_HEIGHT + 20);
 }

 public void CheckScore(){
 if(highscore.equals(""))
 return;

 if(score > Integer.parseInt((highscore.split(":")[1]))){
 String name = JOptionPane.showInputDialog("NEW HIGHSCORE! PLEASE ENTER YOUR NAME.");
 highscore = name + ":" + score;

 File scoreFile = new File("highscore.dat");
 if(!scoreFile.exists()){
 try{
 scoreFile.createNewFile();
 }
 catch(Exception e){
 e.printStackTrace();
 }
 }
 FileWriter writeFile = null;
 BufferedWriter writer = null;
 try{
 writeFile = new FileWriter(scoreFile);
 writer = new BufferedWriter(writeFile);
 writer.write(this.highscore);
 }
 catch(Exception e){
 }
 finally{
 try{
 if(writer !=null)
  writer.close();
 }
 catch(Exception e){}
 }
 }
 }

 public void drawGrid(Graphics g){
 //drawing an outside rectangle
 g.drawRect(0, 0, GRID_WIDTH * BOX_WIDTH, GRID_HEIGHT * BOX_HEIGHT);

}

public void drawSnake(Graphics g){
g.setColor(Color.GREEN);
for (Point p: snake){
g.fillRect(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
}
g.setColor(Color.BLACK);
}

public void drawFruit(Graphics g){
g.setColor(Color.RED);
g.fillOval(fruit.x * BOX_WIDTH, fruit.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
g.setColor(Color.BLACK);
}

public void PlaceFruit(){
Random rand = new Random();
int randomX = rand.nextInt(GRID_WIDTH);
int randomY = rand.nextInt(GRID_HEIGHT);
Point randomPoint = new Point(randomX, randomY);
while(snake.contains(randomPoint)){
randomX = rand.nextInt(GRID_WIDTH);
randomY = rand.nextInt(GRID_HEIGHT);
randomPoint = new Point (randomX, randomY);
}
fruit = randomPoint;
}

@Override
public void run(){
while(true){//runs indefinitely
Move();
repaint();

try{
Thread.currentThread();
Thread.sleep(100);
}
catch(Exception e){
e.printStackTrace();
}
}

}

public String GetHighScore(){

FileReader readFile = null;
BufferedReader reader = null;

try{
readFile = new FileReader("highscore.dat");
reader = new BufferedReader(readFile);
return reader.readLine();
}
catch(Exception e){
return "Nobody:0";
}

finally{
try{
if(reader != null)
reader.close();
}
catch(Exception e){
e.printStackTrace();
}
}

}

@Override
public void keyTyped(KeyEvent e){
//TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
if (direction != Direction.SOUTH)
direction = Direction.NORTH;
break;
case KeyEvent.VK_DOWN:
if (direction != Direction.NORTH)
direction = Direction.SOUTH;
break;
case KeyEvent.VK_RIGHT:
if (direction != Direction.WEST)
direction = Direction.EAST;
break;
case KeyEvent.VK_LEFT:
if (direction != Direction.EAST)
direction = Direction.WEST;
break;

}
}

@Override
public void keyReleased(KeyEvent e){

}

}

A: I think the easiest solution is make snakeApplet a JFrame.
public class SnakeFrame extends JFrame {
  private static final long serialVersionUID = 1L;
  private SnakeCanvas c;// 410x310

  public SnakeFrame() {
    c = new SnakeCanvas();
    c.setPreferredSize(new Dimension(410, 310));
    c.setVisible(true);
    c.setFocusable(true);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.add(c);
  }

  public static void main(String[] args) {
    Runnable doRun = new Runnable() {
      @Override
      public void run() {
        SnakeFrame sf = new SnakeFrame();
        sf.setSize(new Dimension(410, 310));
        sf.setVisible(true);
      }
    };
    new Thread(doRun).start();
  }
}


text:
Q: Handling Invalid SQLite Queries in Android I have a simple code that manages to successfully query an SQLite Database and convert that result from cursor to string in order to display it on screen.
My problem now would be invalid queries that make the App Crash. Would there be a way to successfully handle invalid queries? Preferably something that would keep my app from crashing and would just redirect the user to the home page and display a toast of warning.
So far my method for searching looks like this:
public String search(DataBaseHelper myDB){
    SQLiteDatabase db = myDB.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);

    cursor.moveToFirst();

    String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) + " " +
                    cursor.getString(cursor.getColumnIndex("Room"));

    //Toast msg = Toast.makeText(getBaseContext(),data, Toast.LENGTH_SHORT);
    //msg.show();

    cursor.close();

    return data;

}

A: Cursor cursor = NULL ;
try
{
   cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
   if(cursor != NULL)
   {
      try {
         if (cursor.moveToNext()) {
            String data = cursor.getString(cursor.getColumnIndexOrThrow("BuildingColor")) +
               " " + cursor.getString(cursor.getColumnIndex("Room"));
         } else {
            // Query result was empty, deal with it here.
         }
      } finally {
        // Cursors should be closed
        cursor.close();
      }
   }
}
catch (SQLiteException e) // (Exception e) catch-all:s are bad mmkay.
{
    //print exception
}

A: Cursor cursor = null;
String data = "";
try
{
    cursor = db.rawQuery("SELECT BuildingColor, Room FROM LSBuildingsDB WHERE _id =" + newString, null);
}catch (Exception e) {
    // TODO: handle exception
}


text:
Q: AutoHotKey Hot Strings auto capitalization of I When I type {space}i{space} I would love for this to automatically convert this to the capital "I". I've scanned all through the AHK syntax on hotstrings and I'm very unclear how i can incorporate leading and trailing spaces into my hotstrings.
this does not work as I expect it to. It only works when the line starts with "i"
:C: i :: I `

This doesn't work either
:CO: i:: I `

Neither does this:
:C: i:: I

A: You need the * option so you don't need to type an ending character to trigger the hotstring. And the ? option so it trigger when it's inside of another word. (Might not seem like it is inside of another word e.g. here test i , but it is since the leading space is included)
Also the C option in there couldn't hurt I guess. Will just make it so it doesn't do a redundant replace if you capitalize the i yourself.
:*?C: i :: I `


text:
Q: Logging error while doing a ajax post request Ajax call from cstml page:
function InvoiceableItems(data) {
            return $.ajax({
                type: 'POST',
                url: apiRoot + 'createOrUpdate',
                data: JSON.stringify(data),
                contentType: 'application/json',
                dataType: "json"
            });
        }

Api Controller:
[HttpPost]
public IHttpActionResult CreateOrUpdate(QuotationItemInvoiceableItemsSavingDto[] data)
{
    if (data == null || data.Length == 0)
    {
        return BadRequest();
    }
    return StatusCode(HttpStatusCode.NoContent);
}

Error in console in firefox:

The requested resource does not support http method
  'GET'.

The error also throws when we go to network in chrome and click on the api call request.

A: Are you missing a closing bracket on InvoiceableItems(data)? Or has apiRoot definitely been defined?
<script type="text/javascript">
    var apiRoot = "http://<myurlbase>";

    function InvoiceableItems(data) {
        return $.ajax({
            type: 'POST',
            url: apiRoot + 'createOrUpdate',
            data: JSON.stringify(data),
            contentType: 'application/json',
            dataType: "json" });
        }
    }
</script>

Presumably jQuery has already been defined before this gets called?
You can use fiddler to test that your method works as expected, setting the method as post. If you put a url into chrome, firefox, etc. it will default as get causing the error you saw.


text:
Q: Batch fetching messages performance I need to get the last 100 messages in the INBOX (headers only). For that I'm currently using the IMAP extension to search and then fetch the messages. This is done with two requests (SEARCH and then UID FETCH).
What's the Gmail API equivalent to fetching multiple messages in one request?
All I could find is a batch API, which seems way more cumbersome (composing a long list of messages:get requests wrapped in plain HTTP code).

A: Great reply!
If somebody wants to use a raw function in php to make batch requests for fetching emails corresponding to message ids, please feel free to use mine.
function perform_batch_operation($auth_token, $gmail_api_key, $email_id, $message_ids, $BOUNDARY = "gmail_data_boundary"){
    $post_body = "";
    foreach ($message_ids as $message_id) {
        $post_body .= "--$BOUNDARY\n";
        $post_body .= "Content-Type: application/http\n\n";
        $post_body .= 'GET https://www.googleapis.com/gmail/v1/users/'.$email_id.
                '/messages/'.$message_id.'?metadataHeaders=From&metadataHeaders=Date&format=metadata&key='.urlencode($gmail_api_key)."\n\n";
    }
    $post_body .= "--$BOUNDARY--\n";

    $headers = [ 'Content-type: multipart/mixed; boundary='.$BOUNDARY, 'Authorization: OAuth '.$auth_token  ];

    $curl = curl_init();
    curl_setopt($curl,CURLOPT_URL, 'https://www.googleapis.com/batch' );
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl,CURLOPT_CONNECTTIMEOUT , 60 ) ;
    curl_setopt($curl, CURLOPT_TIMEOUT, 60 ) ;
    curl_setopt($curl,CURLOPT_POSTFIELDS , $post_body);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $tmp_response =  curl_exec($curl);
    curl_close($curl);
    return $tmp_response;

}

FYI the above function gets just the headers for the emails, in particular the From and Date fields, please adjust according to the api documentation https://developers.google.com/gmail/api/v1/reference/users/messages/get

A: In addition to MaK you can perform multiple batch requests using the google-api-php-client and Google_Http_Batch()
        $optParams = [];
        $optParams['maxResults'] = 5;
        $optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox
        $optParams['q'] = 'subject:hello'; // search for hello in subject

        $messages = $service->users_messages->listUsersMessages($email_id,$optParams);

        $list = $messages->getMessages();

            $client->setUseBatch(true);

            $batch = new Google_Http_Batch($client);

            foreach($list as $message_data){

                $message_id = $message_data->getId();

                $optParams = array('format' => 'full');

                $request = $service->users_messages->get($email_id,$message_id,$optParams);

                $batch->add($request, $message_id);
            }

            $results = $batch->execute();

A: here is the python version, using the official google api client. Note that I did not use the callback here, because I need to handle the responses in a synchronous way.
from apiclient.http import BatchHttpRequest
import json

batch = BatchHttpRequest()

#assume we got messages from Gmail query API
for message in messages:
    batch.add(service.users().messages().get(userId='me', id=message['id'],
                                             format='raw'))
batch.execute()
for request_id in batch._order:
    resp, content = batch._responses[request_id]
    message = json.loads(content)
    #handle your message here, like a regular email object

A: solution from Walty Yeung is worked partially for my use case.
if you guys tried the code and nothing happens use this batch
batch = service.new_batch_http_request()

A: It's pretty much the same in the Gmail API as in IMAP. Two requests: first is messages.list to get the message ids.  Then a (batched) message.get to retrieve the ones you want.  Depending on what language you're using the client libraries may help with the batch request construction.

A batch request is a single standard HTTP request containing multiple Google Cloud Storage JSON API calls, using the multipart/mixed content type. Within that main HTTP request, each of the parts contains a nested HTTP request.

From: https://developers.google.com/storage/docs/json_api/v1/how-tos/batch
It's really not that hard, took me about an hour to figure it out in python even without the python client libraries (just using httplib and mimelib).
Here's a partial code snippet of doing it, again with direct python.  Hopefully it makes it clear that's there's not too much involved:
msg_ids = [msg['id'] for msg in body['messages']]
headers['Content-Type'] = 'multipart/mixed; boundary=%s' % self.BOUNDARY

post_body = []
for msg_id in msg_ids:
  post_body.append(
    "--%s\n"
    "Content-Type: application/http\n\n"
    "GET /gmail/v1/users/me/messages/%s?format=raw\n"
    % (self.BOUNDARY, msg_id))
post_body.append("--%s--\n" % self.BOUNDARY)
post = '\n'.join(post_body)
(headers, body) = _conn.request(
    SERVER_URL + '/batch',
    method='POST', body=post, headers=headers)


text:
Q: ERROR 1242: Subquery returns more than 1 row I have a problem and I dont know how to fix it. I was able to do this query in mysql:
UPDATE ARTICULO SET TITULO_ARTICULO= 'La casa' WHERE NUM_ARTICULO='1'

But I don't know what happen later than this does'nt work any more and I obtain this error:

Operation failed: There was an error while applying the SQL script to the database.
  ERROR 1242: 1242: Subquery returns more than 1 row

I see other people have this error with nested queries, but anyone with this that is very simple
Thanks!!
=== EDIT =====
Yes, I use procedures...but if I a drop my database and reload everything again it works, but then It doesnt..and this error happens in every update that I try to execute over the tables.... this the stored procedure :
DELIMITER $$
CREATE DEFINER=root@localhost
PROCEDURE ART_OBSER(IN numero_art int, IN observaciones varchar(200))
BEGIN
    UPDATE ARTICULO SET TITULO_ARTICULO=observaciones
    WHERE NUM_ARTICULO=numero_art;
END $$
DELIMITER ; –


text:
Q: Forcing talkback to read some specific characters - Flutter I would like to make the talkback say a simple mathematical expression like: "2 - (3/5)"
However, when it reads, talkback skips the parentheses, thus affecting the expression to take on a different meaning.
Thanks to @QuentinC I was able to read more questions on the subject. Would this fall under "it's best to leave it at that and not edit" cases, or should I instead be looking for ways to force talkback to speak every character?


text:
Q: iFrame in PWA (Progressive Web App) - 2 calls for Offline I am currently working on Progressive Web App.
I'm trying to create a PWA with an iFrame.
The problem is that I have to load the page twice, else that it can't be available offline.
Files are properlu cached on the first call but I realized that the fetch was only called for the second load. Is there a connection ?
If not, do you have any other idea where the problem might come from?
Thanks!

A: This is probably because of the waiting phase, check the lifecycle of service workers and how to skip the waiting phase.


text:
Q: Plotting an inverse regression curve using ggplot I am trying to plot two regression lines onto the same scatter plot. It looks like I have it almost right using ggplot. I have one fit, using a second order term and another fit where the inverse of hours is the dependent variable and the inverse of cases is the predictor. The data is as follows:
df <- read.table(textConnection(
  'hours cases
   1275 230
  1350 235
  1650 250
  2000 277
  3750 522
  4222 545
  5018 625
  6125 713
  6200 735
  8150 820
  9975 992
  12200 1322
  12750 1900
  13014 2022
  13275 2155
  '), header = TRUE)

I have the following, but it looks like the inverse regression fit is out of whack. What adjustment could be made to get the correct curve? I know the curve should be concave up and increasing.
ggplot(df, aes(x = cases, y = hours)) +
  geom_point(shape=21, size=3.2,fill="green",color="black")+
  geom_smooth(span=.4,method="lm",formula=y~x+I(x^2))+
  geom_smooth(span=.4,method="lm",formula=I(1/y)~I(1/x))

For reference, just a scatter plot of the predicted value of y against x, where note, the y axis is the inverse of the predicted value of 1/y, we get

The code used to produce this was
fit<-lm(I(1/hours)~I(1/cases),data=df)
summary(fit)

hw <- theme(
  plot.title=element_text(hjust=0.5,face='bold'),
  axis.title.y=element_text(angle=0,vjust=.5,face='bold'),
  axis.title.x=element_text(face='bold'),
  plot.subtitle=element_text(hjust=0.5),
  plot.caption=element_text(hjust=-.5),
  strip.text.y = element_blank(),
  strip.background=element_rect(fill=rgb(.9,.95,1),
                                colour=gray(.5), size=.2),
  panel.border=element_rect(fill=FALSE,colour=gray(.70)),
  panel.grid.minor.y = element_blank(),
  panel.grid.minor.x = element_blank(),
  panel.spacing.x = unit(0.10,"cm"),
  panel.spacing.y = unit(0.05,"cm"),

  axis.ticks=element_blank(),
  axis.text=element_text(colour="black"),
  axis.text.y=element_text(margin=margin(0,3,0,3)),
  axis.text.x=element_text(margin=margin(-1,0,3,0)),
  panel.background = element_rect(fill = "gray")
)

ggplot(df,aes(x=cases,y=1/fitted(fit))) +
  geom_point(shape=21, size=3.2,fill="green",color="black")+
  labs(x="Surgical Cases",
       y="Predicted Worker Hours",
       title="Predicted Worker Hours vs Surgical Cases")+hw

A: This should get you started. Including the confidence interval would require additional work (e.g., calculate values for the confidence band outside of ggplot2). I'll leave that as an exercise for the reader.
fit2 <- lm(I(1/hours)~I(1/cases), data = df)

ggplot(df, aes(x = cases, y = hours)) +
  geom_point(shape=21, size=3.2,fill="green",color="black")+
  geom_smooth(span=.4,method="lm",formula=y~x+I(x^2), aes(color = "polyn"))+
  stat_function(fun = function(x) 1 / predict(fit2, newdata = data.frame(cases = x)),
                aes(color = "inv-inv"), size = 1)

A: As @Roland said, you need to plot the actual model.
But, the problem is that geom_smooth has a formula argument that doesn't like formulas. So, even though the formula below is correct, it doesn't plot the right line.
Using summary(fit) to get a (-0.00005507) and b (0.1743), the intercept and slope of the line:
  geom_smooth(span=.4,method="lm", formula=y~I(1/((1/x)*0.1743-0.00005507)))


text:
Q: How to align any element in center? I have given fix width:350px; to div element and want to show in the center of the screen. I have used margin:auto; property. But, still I am not able to do the same. Please advise.

A: To center an element vertically and horizontally

TEXT

.container{
  display: flex;
  justify-content: center;
  align-items: center;
}

Your container must have a height I recommend

A: This will work ...

.center {width: 300px; height: 300px; margin: auto; background: #f00;}

But you need to check there should not be any float property in your element..!


text:
Q: How to populate value with input From a composer.lock I am creating json output of some fields, like this:
 <composer.lock jq  '.packages[] | {site: "foo", name: .name, version: .version, type: .type}' | jq -s

It works fine:
  {
    "site": "foo",
    "name": "webmozart/path-util",
    "version": "2.3.0",
    "type": "library"
  },
  {
    "site": "foo",
    "name": "webonyx/graphql-php",
    "version": "v14.9.0",
    "type": "library"
  }

but now I want to add a generated value, using uuidgen, but I can't figure out how to do that.
End result would be something like:
  {
    "site": "foo",
    "name": "webmozart/path-util",
    "version": "2.3.0",
    "type": "library",
    "uuid": "c4e97c3c-147d-4360-a601-6b4f6f5e71bb"
  },
  {
    "site": "foo",
    "name": "webonyx/graphql-php",
    "version": "v14.9.0",
    "type": "library",
    "uuid": "6fbe472b-49fe-4064-93f0-09a18a7e1c24"
  }

I think I should use input, but all I tried so far have failed.

A: Here's one possibility that does not require your shell to support "process substitution" but which entails two passes, the first for determining the number of UUIDs that are required:
# Syntax: generate N
function generate {
    for ((i=0; i<$1; i++)) ; do
    uuidgen
    done
}

generate $( <composer.lock jq '.packages|length') |
  jq -nR --argfile input composer.lock  '
    ($input
    | .packages[]
    | {site: "foo", name: .name, version: .version, type: .type,
       id: input})'

A: If your shell supports process substitution, you can avoid a two-pass solution as follows:
jq -nR  --argfile input composer.lock '
  $input
  | .packages[]
  | {site: "foo", name: .name, version: .version, type: .type, id: input}
 ' < <(while true; do uuidgen; done)

The point here is that by using process substitution as above, the termination of the "consumer" (jq) will also terminate the "producer"  of UUIDs.


text:
Q: FindBugs for NullPointerExceptions and Memory Leaks I am looking into using FindBugs to help find obvious bugs in my code.
I understand that any tool is limited in some ways, but the two most prevalent bugs I want to look for are:

*

*NullPointerExceptions; and

*Java memory leaks

Does FindBugs have the capabilities to find these? I'm sure one is never guaranteed to have all bugs uncovered, but it would be nice if FindBugs could detect even a fraction of them right there inside of Eclipse for me.
I have been reading the HTML manual and haven't come across anything that mentions these capabilities.

A: FindBugs uses static analysis to look for bugs in Java code.  You could get good tips about improving your code, but it cannot guarantee you will detect memory leaks or NullPointerExceptions due to the runtime nature of both kind of problems. Certainly you will get very good tips about avoiding bad practices that could cause memory leaks and null pointers, but it is just a starting point.
Also check this question about finding memory leaks in Java.
The following Findbugs checks helps avoiding NullPointerException:

*

*NP: Method with Boolean return type returns explicit null

*NP: Clone method may return null

*NP: equals() method does not check for null argument

*NP: toString method may return null

*NP: Null pointer dereference

*NP: Null pointer dereference in method on exception path

*NP: Method does not check for null argument

*NP: close() invoked on a value that is always null

*NP: Null value is guaranteed to be dereferenced

*NP: Value is null and guaranteed to be dereferenced on exception path

*NP: Method call passes null to a nonnull parameter

*NP: Method may return null, but is declared @NonNull

*NP: A known null value is checked to see if it is an instance of a type

*NP: Possible null pointer dereference

*NP: Possible null pointer dereference in method on exception path

*NP: Method call passes null for nonnull parameter

*NP: Method call passes null for nonnull parameter

*NP: Non-virtual method call passes null for nonnull parameter

*NP: Store of null value into field annotated NonNull

*NP: Read of unwritten field

*NP: Dereference of the result of readLine() without nullcheck

*NP: Immediate dereference of the result of readLine()

*NP: Load of known null value

*NP: Possible null pointer dereference due to return value of called method

*NP: Possible null pointer dereference on branch that might be infeasible

*NP: Parameter must be nonnull but is marked as nullable

*NP: Read of unwritten public or protected field

Some checks about memory issues that will help improve your code are

*

*Dm: Method invokes inefficient new String(String) constructor

*Dm: Method invokes inefficient new String() constructor

*Dm: Method invokes inefficient Boolean constructor; use Boolean.valueOf(...) instead

A: FindBugs is quite good at finding problems with nulls.
http://findbugs.sourceforge.net/bugDescriptions.html describes many bugs FindBugs can recognize to do with nulls.


text:
Q: Iterations of a sequence with files Ok, so here I asked how I can simplify a method of creating a certain series in a file. I came to the conclusion that I should use file handling.
Just to make myself clear, this is the algorithm of the sequence I intend to create:
_____
1 , 1  Take the 1st and 2nd numbers.

_____
1 , 1 , 2 , 1 Append Their sum, and Append the second value.

    _____
1 , 1 , 2 , 1 Take the 2nd and 3rd numbers

    _____
1 , 1 , 2 , 1 , 3 , 2 Append Their sum, and Append the second value.

        _____
1 , 1 , 2 , 1 , 3 , 2 Take the 3rd and 4th numbers

        _____
1 , 1 , 2 , 1 , 3 , 2 , 3 , 1 Append Their sum, and Append the second value.

This should create the sequence: 1 , 1 , 2 , 1 , 3 , 2 , 3 , 1 , 4 , 3 , 5 .....
Now, I have created some code in C that should be able to generate this sequence, but somehow does not.
#include <stdio.h>

int x=1;
int y=1;
int z=2;

int DataCount = 1;
FILE *fFs;

struct storeX
{
   int defX[16];
}stockX[16];

struct storeY
{
   int defY[16];
}stockY[16];

int main()
{
   fFs=fopen("Fibb.txt","w"); //Clears the file.
   fclose(fFs);

   fFs=fopen("Fibb.txt","a");
   fprintf(fFs,"%d\n",x);
   fprintf(fFs,"%d\n",y);

   DataCount = 1;
   do
   {
      z = x+y;
      fprintf(fFs,"%d\n",z);
      fprintf(fFs,"%d\n",y);
      DataCount = DataCount + 1;
      fscanf(fFs,"%16[^\n]%*c", stockX[DataCount].defX);
      fscanf(fFs,"%16[^\n]%*c", stockY[(DataCount+1)].defY);
      x= atoi(stockX[DataCount].defX);
      y= atoi(stockY[(DataCount+1)].defY);
   }
   while(DataCount < 100);

   fclose(fFs);
}

I think the problem lies in the scan, but I can't be too sure.
The file output: (going line by line down)
1
1
2
1
                                      0
0
                                      0
0
                                      0
0
                                      0
0
                                      0
0


text:
Q: find an error in installation of phonegap plugin in eclipse I am a beginner in phonegap.
I want to install it in eclipse but I always get error message: I use Windows 7, Eclipse Kepler, the latest version of the Android SDK, the latest version of ADT and finally to phonegap eclipse plugin C 'is the link:
http://svn.codespot.com/a/eclipselabs.org/mobile-web-development-with-phonegap/tags/r1.2/download
Installing the Android SDK and ADT is easily
Eclipse displays a message that it has encountered errors while installing phonegap eclipse plugin.
Help me please!
Installation is aborted of 49% of completion with this error:
An error occurred while collecting items to be installed
session context was:
(profile=profile, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, perand=, action=).
Problems downloading artifact: osgi.bundle,org.mozilla.javascript,1.7.2.v201005080400.
MD5 hash is not as expected.
Expected: 8785860e8f2a2a43fe10dd8b9eb334b6 and found  7ab8a5d6da46b081c83bfc81e7c880e6.


text:
Q: Not Skolem's Paradox - Part 3 This is a follow up to a previous question: Not Skolem's Paradox - Part 2.
Assume we have a countable, non-standard model of Peano Arithmetic in ZFC. This ZFC model must include a set of ordered triplets that defines addition in this model.
There are various ways to encode finite sets in PA. For example, we can say the binary expansion of a natural number defines a set. The number $7 = 2^0 + 2^1 + 2^2$ encodes the set $\{0,1,2\}$. We can similarly encode ordered pairs. Encode $[a,b]$ as $2^{2a} + 2^{2b+1}$. The ordered pair $[2,0]$ would be encoded as $18 = 2^4 + 2^1$. We can now encode sets of ordered pairs, etc. I want to encode a set of ordered triplets that defines addition in a ring $\mathbb{Z} /n \mathbb{Z}$. I want to define addition modulo $n$. For example, let $n=3$:
$0+0=0$
$0+1=1$
$0+2=2$
$1+0=1$
$1+1=2$
$1+2=0$
$2+0=2$
$2+1=0$
$2+2=1$
Lets call this the addition function. This is a finite set that I can encode as a natural number in our model of PA. Now assume $n$ is a nonstandard natural number larger than any standard natural number. Our nonstandard model of PA still considers the addition function modulo $n$ to be finite and we can still encode this function as a nonstandard natural number.
Tennenbaums' theorem proves neither addition nor multiplication can be recursive in any countable nonstandard model of arithmetic. This means ZFC has to prove the addition function modulo $n$ doesn't exist when $n$ is larger than any standard natural number.
My question is how can a set be definable inside the model (PA) and yet not exist in the meta-theory (ZFC)?

A: In the best case, what you get here is an encoding of addition for a subset of the model which happens to include the standard integers. That's not in conflict with Tennenbaum's theorem -- for example, there's nothing that prevents us from having a countable nonstandard model where the standard integer $n$ is represented by $2n$ and the nonstandard elements are all represented by odd numbers. In that case addition and multiplication of standard elements is easily possible. All Tennenbaum's theorem says is that we can't get a nonstandard model where the complete addition function is computable.
But we don't even get that far -- just because there's a number inside the model that encodes the addition table for standard (and some nonstancard) elements doesn't mean knowing that number lets us extract that information, working from the outside. Doing so would presumably require us to do some arithmetic inside the model (on nonstandard numbers) -- but that's exactly what we can't do!
Also, you seem to be confused between "is not computable" and "does not exist in the metatheory". The model and its addition and multiplication functions certainly exists in ZFC.

Note that we don't even need choice for the model to exist, so ZF is enough -- in fact even PA+con(PA) will suffice as the metatheory. By carefully tracing the details of the usual compactness argument and the proof of the completeness theorem, we can see that there must exist a nonstandard model of PA where the carrier set is $\mathbb N$ and the addition and multiplication are represented by particular $\Sigma^0_2$ arithmetical formulas.


text:
Q: Creating a function with a for loop into lapply I am trying to use a simple function to perform an operation on a column of each dataframe of a list.
Here is the data:
a<-LETTERS[1:6]
b<-1:6

df1<-as.data.frame(cbind(a,b))
df2<-as.data.frame(cbind(a,b))
df3<-as.data.frame(cbind(a,b))

df_list<-list(df1,df2,df3)

These are the names I want to use to rename the dataframes in the list:
df_names<-c("first","second","third")

By far, I have done this:
df2_list <- lapply(df_list, function(df_list) {
  for(i in df_list[[i]]$b) {
    df_double<-list((as.numeric(df_list[[i]]$b))*(2))
    names(df_double)<-df_names[i]
  }
  df_list
} )

That gives me this error:
 Error in .subset2(x, i, exact = exact) : invalid subscript type 'list'

But if I try to run separately these two commands, for instance on the first dataframe of the list, they do what I want:
df_double<-list((as.numeric(df_list[[1]]$b))*(2))
names(df_double)<-df_names[1]

I know I am missing something but I cannot see what... Thanks in advance!

A: Use lapply to multiply the b column with 2 and use setNames to assign names.
setNames(lapply(df_list, function(x) transform(x, b = b * 2)), df_names)

#$first
#  a  b
#1 A  2
#2 B  4
#3 C  6
#4 D  8
#5 E 10
#6 F 12

#$second
#  a  b
#1 A  2
#2 B  4
#3 C  6
#4 D  8
#5 E 10
#6 F 12

#$third
#  a  b
#1 A  2
#2 B  4
#3 C  6
#4 D  8
#5 E 10
#6 F 12

For clarity, you may also do this in separate steps.
names(df_list) <- df_names
lapply(df_list, function(x) transform(x, b = b * 2))


text:
Q: R: Swap Data Table Rows based on column values I have a data table with two columns: "id" and "prevId". I want to find all instances where one row has a "prevId" value equivalent to the "id" value of a row that comes after it. I then want to swap the order of those rows in the data table.
So far, I have tried messing around with the logic below:
data[, index:=.I]
data[, priorMatch:=index[1L], by = cumsum(prevId == id)]
apply(records, 1, FUN = function(x) {
if (!is.na(priorMatch)) {
  records[x[["index"]],] <- records[x[["index"]] - 1,]
  records[x[["index"]] - 1,] <- x
}
})

However, cumsum() does not actually take me the earliest prior row with a "prevId" equivalent to the present row's "id".
An example of desired results:
id prevId
ef     cd
cd     ab

Would be transformed to:
id prevId
cd     ab
ef     cd

Any assistance is appreciated. Thanks!

A: This will do the trick (at least for the sample data provided)
dt <- fread("id prevId
             ef     cd
             cd     ab")

#get rownumbers
dt[, row := .I]
#create a column with 'new' rownumbers to order on, using shift
dt[ prevId == shift(id, 1, type = "lead") , row := row + 1]
dt[ id == shift(prevId, 1, type = "lag") , row := row - 1]
#reorder
setkey(dt, row)
#drop the row-column
dt[, row := NULL][]
#    id prevId
# 1: cd     ab
# 2: ef     cd

A: Use -
df <- data.frame(id=c("ef", "cd"), "prevId"=c("cd", "ab"))
rows <- which(as.character(df[,"id"]) == as.character(shift(df[,"prevId"])))
for(i in 1:length(rows)){
  index <- rows[i]
  swap_index <- index - 1

  temp <- df[index, ]
  df[index, ] <- df[swap_index, ]
  df[swap_index, ] <- temp
}

Output
  id prevId
1 cd     ab
2 ef     cd


text:
Q: Issues with installing NPM mongoose I'm taking an intro class to Mean.  I installed MongoDB and mongoose but I don't think I installed them right in the same folder..as I'm learning.  When I try to run:  node nodemongoose.js I get this error: the nodemongoose.js is a file for the class...it is in the folder I am in for the Terminal window)
Error: Cannot find module 'mongoose'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/Dave/Documents/Software/mongoose/nodeapi.js:4:16)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)

I tried installing using npm install mongoose and then I get this error: npm WARN install Refusing to install mongoose as a dependency of itself
Any suggestions?  Do I need to uninstall and re-install?
Thanks

A: Remove mongoose, reinstall locally:

*

*npm uninstall mongoose run twice, to make sure any local and global installations are removed.

*npm install mongoose (do not use -g flag!) in your project root, from an elevated CMD.

Note the installation process, and make sure no errors come up. If anything shows that looks odd, please go ahead and add the log to your question.
Note that the warning you get regarding dependency is related to you trying to install mongoose while you are in mongoose directory. You should npm i mongoose in your project directory.


text:
Q: Is PDB required when I have my pods on multiple nodes? I have set up my K8s pods in such a way that the replicas get created on multiple nodes. So no node has 2 pods running the same application. HPA pods will be created on separate nodes too. Is the PDB required in this scenario?

A: No, Pod Disruption Budget (PDB) is not a requirement when deploying pods on multiple nodes.
It is primarily to handle disruptions due to the dynamic nature of Kubernetes. A PDB limits the number of Pods of a replicated application that are down simultaneously from disruptions. So, using PDB depends on a lot of things like, is the application critical to running of the cluster, criticality of the application to the business, how highly available you want the app to be, number of users affected if the app become unavailable etc.
Having said that, it is a good practice to use PDB on production clusters with proper planning.


text:
Q: Access to primefaces widgetvars on document ready Im trying to access to primefaces components on document ready like this:
$(function() {
  var showDialog = getUrlParameter("showDialog");
  if (showDialog == "true") {
    PF('myDialog').show();
  }
});

But in that moment the primefaces widgetvars are not available and I get the following error:

Widget for var 'myDialog' not available!

In PrimeFaces 6.2 and 7.0 (and maybe some earlier versions) the error you get is

TypeError: PF(...) is undefined

but when PrimeFaces.widgets['myDialog'].show() is used instead of PF('myDialog').show(); the error is comparable

TypeError: PrimeFaces.widgets.myDialog is undefined

When are the primefaces widgetvars ready to be accessed?

A: I had success with adding the javascript initialization code in the page AFTER the component with the widgetVar, ie
<p:dataTable widgetVar="test">

</p:dataTable>

<script  type="text/javascript">
  $(document).ready(function()  {
     PF('test'); // access and do whatever here
 }
</script>

Putting the script tag before the p:dataTable doesn't work.
More info here: http://forum.primefaces.org/viewtopic.php?f=3&t=35718

A: Sometimes the widgetVar needs some time to get initialized (in document.ready), like (non-extensive)

*

*upload

*dialog

*overlay

in that case you can use setTimeOut
setTimeout(PF('myDialog').show(), 2000);

Hope this helps.

A: I found a better solution for my case. I call a JavaScript method using the onload attribute of h:body
<h:body onload="checkIfShowDialog()">

And this is the JavaScript method:
function checkIfShowDialog(){
  var showDialog = getUrlParameter("showDialog");
  if (showDialog == "true") {
    PF('myDialog').show();
  }
}

This works as desired.

A: If you run into this error when usin a p:remoteCommand with autoRun="true",  like this
<h:body>
    <h:form>
        <p:remoteCommand autoRun="true" name="actualizarSaldosCajero"
            onstart="PF('ajaxStatus').show();"
            action="#{plantillaGeneralMB.actualizarSaldosCajero}" />
    </h:form>

    <p:dialog widgetVar="ajaxStatus">
       Content
    </p:dialog>
</h:body>

You should place the p:remoteCommand code after the components that you reference in the onstart or in a function you call from there.
<h:body>
    <p:dialog widgetVar="ajaxStatus">
       Content
    </p:dialog>

    <h:form>
        <p:remoteCommand autoRun="true" name="actualizarSaldosCajero"
            onstart="PF('ajaxStatus').show();"
            action="#{plantillaGeneralMB.actualizarSaldosCajero}" />
    </h:form>

</h:body>

(Tried with PrimeFaces 6.2 and 7.0)

A: You can try to call javascript initialization method from server side using RequestContext.
RequestContext.getCurrentInstance().execute("initialization script here");

For example:
@PostConstruct
public void init() {
    if(!FacesContext.getCurrentInstance().isPostback()) {
        RequestContext.getCurrentInstance().execute("alert('This onload script is added from backing bean.')");
    }
}

Reference: Execute javascript onload


text:
Q: Printing Uncommon Characters? Basically I have a program that finds the most common character from the Acsii table.  And then prints the number of times the character happened, the Ascii Number, and the "character".  But I would like to know the easiest and most computer science way of printing characters such as NEWLINE "\n" or "\t". I would like to avoid typing out all of the characters like those if possible.
If you need any code let me know!
Thank you!

A: You could always use Caret Notation, which has a fairly simple mapping of the non-printable ASCII codes to the caret symbol '^' plus a printable ASCII character.


text:
Q: How to get the value of an EAV attribute from a model class in Magento2 I have got an object of this model magento/catalog/model/product and I want to use one of the EAV attributes values of it. How to access this EAV attribute through model object.There is no issue with non-EAV attributes to be used.

A: You should use code like:
$product = $productRepo->get($productId);
$attributeValueId = $product->getCustomAttribute('my_custom_attribute_code');

A: You can create a new helper, add the product repository in the constructor and get eav custom attributes from here.
Please check details in this post :
Get product attribute in cart in Magento2


text:
Q: how can I have a function executed in the child component every time I meet a condition in the parent component to show the child component? I have a child component called Camera and I call it within a parent component when a condition is met in the style of:
<Camera showCamera = {fieldPhoto} />

  handleTakePictureAsync = ({ uri, fieldphoto }) => {
    setFieldPhoto(null);

  };

    const [fieldPhoto, setFieldPhoto] = useState (null)
    return(
        <View>
         <Camera
            showCamera = {fieldPhoto}
            handleTakePictureAsync={handleTakePictureAsync}

         />
         <Button transparent onPress = {() =>
             setFieldPhoto(true)
         </Button>)
        </View>)

In the child component I have a method to verify if the permissions to use the camera have been accepted, if they have not been accepted, the dialog should be asked asking to allow the camera to run, as many times until it is accepted.
I don't know how to make the confirmation message appear without loading the rest of the component.
<! -- Camera Component -->

  export const Camara = props => {
  const [hasPermission, setHasPermission] = useState(null);
  const [showCamera, setShowCamera] = useState(true);
  const propShowCamera = props.showCamera;

  const checkPermissionsCamera = () => {
    const status = Permissions.askAsync(Permissions.CAMERA).then(permission => {
      setHasPermission(status.status === "granted");
    });
  };

  return (
    <View>
      {checkPermissionsCamera()}
      {propShowCamera && hasPermission && ( rest of code
      .
      .
      .

I want to ensure that the rest of the code of the camera component is not loaded until the camera use permissions have been accepted, and that the message asking to accept permissions appears until they are accepted.

A: Your parent component is passing down prop showCamera which determines whether the Camera is shown. Since this is a boolean value, you should set initial values to false and not null:
const Parent = () => {
    handleTakePictureAsync = ({ uri, fieldphoto }) => {
        setFieldPhoto(false)
    }

    const [fieldPhoto, setFieldPhoto] = useState(false)
    return (
        <View>
            <Camera
                showCamera={fieldPhoto}
                handleTakePictureAsync={handleTakePictureAsync}
            />
            <Button transparent onPress={() => setFieldPhoto(true)}></Button>
        </View>
    )
}

In your child component, you should use a useEffect hook to run the checkPermissionsCamera function - don't call it directly in the render method as this function sets state, which means your component may rerender continuously:
    useEffect(() => {
        const checkPermissionsCamera = () => {
            const status = Permissions.askAsync(Permissions.CAMERA).then(
                permission => {
                    setHasPermission(status.status === 'granted')
                }
            )
        }

        checkPermissionsCamera()
    }, [setHasPermission])

return (
    <View>
    // Don't do this:
    // {checkPermissionsCamera()}
    {propShowCamera && hasPermission && ( rest of code...

I'm also unclear on why you need two showCamera values:
const [showCamera, setShowCamera] = useState(true);
const propShowCamera = props.showCamera;

Also:

the dialog should be asked asking to allow the camera to run, as many
  times until it is accepted

Are you sure this is what you want? A never-ending popup asking for camera permission until the user gives permission for the camera to be used? What if they don't want to give permission? You should probably accept that they don't want to and display a message "You need to give camera permission to use this part of the app".

One way to write your camera component could be like this:
export const Camara = ({ showCamera }) => {
    const [hasPermission, setHasPermission] = useState(false)

    useEffect(() => {
        const checkPermissionsCamera = () => {
            const status = Permissions.askAsync(Permissions.CAMERA).then(
                permission => {
                    setHasPermission(status.status === 'granted')
                }
            )
        }

        checkPermissionsCamera()
    }, [setHasPermission])

    return (
        <View>
            {showCamera && hasPermission &&
Rest of code
}
        </View>
    )
}

Then you wouldn't bug the user with an infinite loop of popups until they grant camera permission.
But if you need permission to show your camera, why render the Camera component in the first place? Would it not be better to handle the permission request in the parent component, then once permission has been granted, render Camera?
This would also fit with your requirement:

I want to ensure that the rest of the code of the camera component is
  not loaded until the camera use permissions have been accepted

Just don't render the Camera at all until permission has been granted.

Handling permissions in the parent would look something like this:
// Parent
const Parent = () => {
    const handleTakePictureAsync = ({ uri, fieldphoto }) => {
        setIsFieldPhoto(false)
    }

    const [hasCameraPermission, setHasCameraPermission] = useState(false)
    const [isFieldPhoto, setIsFieldPhoto] = useState(false)

    useEffect(() => {
        const requestCameraPermission = () => {
            Permissions.askAsync(Permissions.CAMERA).then(
                ({ status }) => {
                    setHasCameraPermission(status === 'granted')
                }
            )
        }

        if (!hasCameraPermission && isFieldPhoto) {
            requestCameraPermission()
        }
    }, [setHasCameraPermission, hasCameraPermission, isFieldPhoto])

    return (
        <View>
            {hasCameraPermission && isFieldPhoto && (
                <Camera handleTakePictureAsync={handleTakePictureAsync} />
            )}
            <Button transparent onPress={() => setIsFieldPhoto(true)}></Button>
        </View>
    )
}

// Camera
export const Camara = ({ handleTakePictureAsync }) => {
    return (
        <View>

Normal camera code

        </View>
    )
}


text:
Q: Reasons to NOT run a business-critical C# console application via the debugger? I'm looking for a few talking points I could use to convince coworkers that it's NOT OK to run a 24/7 production application by simply opening Visual Studio and running the app in debug mode.
What's different about running a compiled console application vs. running that same app in debug mode?
Are there ever times when you would use the debugger in a live setting?  (live: meaning connected to customer facing databases)
Am I wrong in assuming that it's always a bad idea to run a live configuration via the debugger?

A: Just in itself there's no issue in running it in debugging if the performance is good enough. What strikes me as odd is that you are running business critical 24/7 applications as users, perhaps even on a workstation. If you want to ensure robustness and avaliability you should consider running this on dedicated hardware that no one uses besides the application. If you are indeed running this on a users machine, accidents can be easily made, such as closing down the "wrong" visual studio, or crashing the computer etc.
Running in debug should be done in the test environment. Where I've work/worked we usually have three environments, Production, Release and Test.
Production

*

*Dedicated hardware

*Limited access, usually only the main developers/technology

*Version control, a certain tagged version from SVN/CVS

*Runs the latest stable version that has been promoted to production status

Release

*

*Dedicate hardware

*Full access to all developers

*Version control, a certain tagged version from SVN/CVS

*Runs the next version of the product, not yet promoted to production status, but will probably be. "Gold" if you like.

Test

*

*Virtual machine or louse hardware

*Full access

*No version control, could be the next, next version, or just a custom build that someone wanted to test out on "near prod environment"

This way we can easily test new version in Release, even debug them there. In Test environment it's anything-goes. It's more if someone want to test something involving more than one box (your own).
This way it will protect you against quick-hacks that wasn't tested enough by having dedicated test machines, but still allow you to release those hacks in an emergency.

A: Speaking very generically, when you run a program under a debugger you're actually running two processes - the target and the debugger - and tying them together pretty intimately.  So the opportunities for unexpected influences and errors (that aren't in a production run) exist.  Of course, the folks who write the debuggers do their best to minimize these effects, but running that scenario 24/7 is likely to expose any issues that do exist.
If you're trying to track down a particular failure, sometimes running under a debugger is the best solution; but even there, often enabling tracing of one sort or another is a lower-impact solution that is just as effective.
The debugger is also using up resources - depending on the machine and the app, that could be an issue.  If you need more specific examples of things that could go wrong using a debugger 24/7 let me know.

A: Ask them if they'd like to be publicly mocked on The Daily WTF. (Because with enough details in the write up, this would qualify.)

A: You will suffer from reduced performance when running under the debugger (not to mention the complexity concerns mentioned by Bruce), and there is nothing to keep you from getting the same functionality as running under the debugger when compiled in release mode -- you can always set your program up to log unhandled exceptions and generate a core dump that will allow you to debug issues even after restarting your app.
In addition, it sounds just plain wrong to be manually managing an app that needs 24/7 availability.  You should be using scheduled tasks or some sort of automated process restarting mechanism.
Stepping back a bit, this question may provide some guidance on influencing your team.

A: I can't speak for everyone's experience, but for me Visual Studio crashes a lot. It not only crashes itself, but it crashes explorer. This is exacerbated by add-ons and plugins. I'm not sure if its ever been tested to run for 24/7 over days and days and days the same way the OS has.
Your essentially putting the running of your app at the mercy of this huge behemoth of a second app that sounds like its easily orders-of-magnitude larger and more complex than your app. Youre just going to get bug reports and most of them are going to involve visual studio crashing.
Also, are you paying for visual studio licenses for production machines?

A: You definitely don't want an application that needs to be up 24/7 to be run manually from the debugger, regardless of the performance issues.  If you have to convince your co-workers of that, find a new job.
I have sometimes used the debugger live (i.e. against live customer data) to debug data-related application problems in situations where I couldn't exactly reproduce the production data in a test environment.

A: Simple answer: you will almost certainly reduce performance (most likely considerably) and you will vastly increase your dependencies. In one step you've added the entire VS stack including the IDE and every other little bit to your dependencies. Smart people keep the dependencies of high-uptime services as tight as possible.
If you want to run under a debugger then you should use a lighter weight debugger like ntsd, this is just madness.

A: We never run it via the debugger.  There are compiler options which may accidentally be turned on/off.  Optimizations aren't turned on, and running it in production is a huge security risk.

A: Aside from the debug code possibly having different code paths (#ifdef, Debug.Assert(), etc) code-wise it will run the same.
A little scary mind you - set breakpoints, set the next line of code you want to execute, interactive exceptions popup and the not-as-stable running under visual studio.There are also debugger options that allow you to break always when an exception occurs. Even inspecting classes can cause side-effects if you haven't written code properly... It sure isn't something i'd want to do as the normal 24x7 process.
The only reason to run from the debugger is to debug the application. If you're doing that on a regular basis in production, it's a big red flag that your code and your process need help.
To date I've never had to run debug mode interactively in production. The rare time we switched over to a debug version for extra logging, but never sat there with visual studio open.

A: I would ask them what is the advantage of running it via Visual Studio?
There are plenty of disadvantages that have been listed in the replies. I can't think of any advantages.


text:
Q: Тернарный оператор в примерах в книге Шилдта Не первый раз вижу,что в книге шилдта написано:
int max = x < y ? x : y;

Я так понимаю, это значит, что если х меньше y - выводим x, иначе y. Тогда почему он называет переменную max? Это опечатка или я неправильно понимаю конструкцию?

A: Вы вырвали строчку из контекста. Дальше по коду эта переменная используется в условии цикла именно как максимум:
/* Determine if x and v have a common divisor.
    If so, return least and greatest common factors in
    the out parameters. */

public bool HasComFactor(int x, int y, out int least, out int greatest)
{
    int i;
    int max = x < y ? x : y;
    bool first = true;

    least = 1;
    greatest = 1;

    // Find least and greatest common factors.
    for (i = 2; i <= max / 2 + 1; i++)
    {
        if (((y % i) == 0) & ((x % i) == 0))
        {
            if (first)
            {
                least = i;
                first = false;
            }
            greatest = i;
        }

    }

    if (least != 1) return true;
    else return false;
}

Собственно обычно и принято именовать переменные соответственно тому как они используются, а не тому как их инициализируют.

A: Данное выражение можно записать как:
if(x < y)
{
  max = x;
}
else
{
  max = y;
}

По логике мы нашли min.
Такой вид записи очень популярен и удобен, 8 строчек кода мы заменяем одной.

A: Тут говориться что вы как программист на N строке создаете переменную max типа int и инициализируете ее возвращаемым значением тернарного оператора у которого условие X меньше Y, если условие выполняется возвращаться левая часть после оператора "?" если нет то правая. Ну а насчет того что писал Шилд это нужно смотреть в контексте самого кода его программы.
К слову, использование тернарного оператора плохая практика так как затрудняет читаемость кода, ну а если мы хотим быть хорошими программистами то мы должны писать код который будет понятен другим людям сопровождающим этот код после вас, единственный случай когда можно использовать тернарный оператор это очень простые выражения, как в вашем примере)))


text:
Q: azure ignoring saml metadata descriptors We have received metadata from a large enterprise that has both IDPSSOdescriptor and SPSSOdescriptor tag. While uploading the metadata  to enterprise apps, Azure picks up the first logout settings present in the metadata, although its clearly marked as IDPSSOdescriptor tag. This can be further tested by switching the SPSSO section with the IDPSSO section. Azure ignores the tags and uploads the first logout URL it finds.
Am i doing something wrong? I have tested multiple metadata files of 3rd party apps this way, azure clearly ignores the tags and selects the first settings it finds.


text:
Q: Creating an new object from an existing object in javascript I am going through a challenge from devchallenges.io, Shoppingify challenge. Having read the prompt, I proceeded to create a model which has the following format when a request is made.
{
  "user": 1,
  "_id": 3393220221,
  "name": Chicken,
  "category": "Meat",
  "note": "This is an example note",
  "image_url": "www.exampleurl.com"
}

The issue I'm having is that the component expects the object in the following format.
{
"category": "Meat",
"items": [
{
"user": 1,
"_id": "3393220221",
"name": "Chicken",
"note": "This is an example note",
"image_url": "www.exampleurl.com"
}
]
}

The link to the challenge is https://devchallenges.io/challenges/mGd5VpbO4JnzU6I9l96x for visual reference.
I'm struggling with how to modify the object response from the request. I want to be able to find occurances of the same category name and push the items onto a new object as shown.

A: const users = [
    {
        "user": 1,
        "_id": 3393220221,
        "name": "Chicken",
        "category": "Meat",
        "note": "This is an example note",
        "image_url": "www.exampleurl.com"
    }
];

function modifyUserObject(users) {
    const result = {};

    users.forEach(user => {
        if (!result[user]) {
            result[user] = {
                category: user.category,
                items: []
            }
        }

        //code here..if want to remove user properties like user

        result[user].items.push(user);
    });

    return Object.values(result);
}

modifyUserObject(users);

Hope this will be helpful! Happy coding...

A: The value Chicken is not defined. Is this a typing error by you? Anyway this should do the trick:
const obj = {
    user: 1,
    _id: 3393220221,
    name: "Chicken",
    category: "Meat",
    note: "This is an example note",
    image_url: "www.exampleurl.com",
};

function createObj(arg) {
    let result = {
        category: arg.category,
        items: [
            {
                user: arg.user,
                _id: arg._id,
                name: arg.name,
                note: arg.note,
                image_url: arg.image_url,
            },
        ],
    };
    return result;
}

console.log(createObj(obj));

Edit:
If you want to create a new object that is not related to the old one (deep copy) you need to do JSON.parse(JSON.stringify(obj)) to not change the values of the original object.


text:
Q: Making Images Viewed By UIWebView Smaller i have a list of entries from a database and I'm feeding them in to HTML to a UIWebView that is making a list of the database entries on the page.
(Much Easyer/Better then extending UITableView Cells)
My Problem is with UITableView i was able to grab an image on a server as NSData and with UIImageJpegRepresentation set the quality for the image a bit lower to be better on the iPhone's cellular downloads.
Now i can go and grab an image from the server as NSData Compress the image then convert it to base 64string and spit it into the WebView but is there any other way to do this?
TLDR: How can i decrease the size of images seen in a HTML Page?

A: I fixed this by feeding the page i was going to visit to a web service. The web service then returns a set of images compressed at lower quality.
Because the only pages the app is going to visit were my own with user avatars and stuff i was able to profile what images would be needed.
On the iPhone i rebuilt the webpage with the set of those smaller images in a UIWebView.
So in the end i downloaded less cellular data and problem is solved.


text:
Q: iterating though an element using format method Here is my simplified code as i can't post my actual code in python 3:
class example(object):
    def __init__(self, list1):
        self.list1 = list1
    def __repr__(self):
        if len(self.list1) > 0:
            for i in self.list1:
                for j in range(1,len(self.list1)):
                    return ('{0:}{1:}').format(j, i)

x = example(['this', 'is', 'a', 'list'])
x

This should return:
1this

Now im wanting it to return:
1this
2is
3a
4list

How do i go about doing this?

A: Just use enumerate function as follows:
class example(object):
    def __init__(self, list1):
        self.list1 = list1
    def __repr__(self):
        return '\n'.join('{0}{1}'.format(c+1, el) for c, el in enumerate(self.list1))


text:
Q: How to mock camel endpoints in separate camel context I am writing test cases for a library that hides camel business from end users.
The library exposes methods such as sendMessages() etc and internally using ProducerTemplate sends the messages on to a camel route where they are aggregated and sent to destination eventually.
I want to be able to write tests that call the library method and mock the camel route endpoints to do asserts on it later.
If I use CamelSpringTestSupport, it basically creates a new ClassPathXmlApplicationContext, using which i can test the routes.
However I want to test the endpoints which are created within the library's camel contextso that I test-cover the library code as well.
Can this be done?

A: use Camel's AdviceWith to dynamically change the route behavior (intercept exchanges and send to mock endpoints for validation, etc)...its very flexible and leverages the familiar MockEndpoints, etc...
for example...to intercept the messages sent to the direct:start route
context.getRouteDefinition("myRouteId").adviceWith(context, new AdviceWithRouteBuilder() {
    @Override
    public void configure() throws Exception {
       interceptSendToEndpoint("direct:start")
                .skipSendToOriginalEndpoint()
                .to("mock:start");
    }
});

getMockEndpoint("mock:start").expectedBodiesReceived("Hello World");

A: My final test case looks like following, where existing context's routes get mocked.
    import org.apache.camel.Exchange;
    import org.apache.camel.builder.AdviceWithRouteBuilder;
    import org.apache.camel.component.mock.MockEndpoint;
    import org.apache.camel.test.spring.CamelSpringTestSupport;
    import org.junit.Assert;
    import org.junit.BeforeClass;
    import org.junit.Test;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.context.support.AbstractApplicationContext;
    import org.springframework.test.annotation.DirtiesContext;
    import java.net.URL;
    import java.nio.file.Paths;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    public class MyAppTest extends CamelSpringTestSupport {

    private static MyApp myapp;
    protected final Logger log = LoggerFactory.getLogger(MyAppTest.class);

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        return (AbstractApplicationContext) myApp.getContext();
    }

    @Override
    public boolean isUseAdviceWith() {
        // tell we are using advice with, which allows us to advice the route
        // before Camel is being started, and thus can replace myApp Endpoint with something else.
        return true;
    }

    @BeforeClass
    public static void oneTimeSetUp() throws Exception {
        myApp = new myApp();
    }

    @Test
    @DirtiesContext
    public void test01() throws Exception {

        log.info("TEST: Going to apply advideWith clause to existing route");

        context.getRouteDefinition("bulkIndexRoute").adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {

                weaveByToString(".*myAppEndpoint.*")
                        .replace()
                        .aggregate(header("ABC"), new ArrayListAggregationStrategy())
                        .completionSize(100)
                        .completionInterval(1000)
                        .to("mock:foo");
            }
        });
        log.info("TEST: Done applying adviceWith Clause");

        MockEndpoint mockedES = getMockEndpoint("mock:foo");
        mockedES.expectedMessageCount(2);
        mockedES.setAssertPeriod(10000);

        // Create 150 test documents and index them
        for(int i = 0; i < 150; i++) {
            Map<String, String> d = new HashMap<String, String>();
            d.put("key1", "value" + i);
            d.put("key2", "value" + i);
            myApp.send("param1", "param2", d);
        }

        mockedES.assertIsSatisfied();

        int count = 0;
        for(Exchange ex : mockedES.getExchanges()){
            List<Map<String, Object>> documentList = ex.getIn().getBody(List.class);
            count += documentList.size();
        }

        Assert.assertEquals("Received back 150 message", 150, count);
    }
}

MyApp class returns the context to the test, so that routes in the running context can be mocked.